话不多说,先上代码
代码部分
import sys
import os
import winreg
def add_to_startup(name,file_path=""):
#By IvanHanloth
if file_path == "":
file_path = os.path.realpath(sys.argv[0])
auth="IvanHanloth"
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Run",winreg.KEY_SET_VALUE, winreg.KEY_ALL_ACCESS|winreg.KEY_WRITE|winreg.KEY_CREATE_SUB_KEY)#By IvanHanloth
winreg.SetValueEx(key, name, 0, winreg.REG_SZ, file_path)
winreg.CloseKey(key)
def remove_from_startup(name):
auth="IvanHanloth"
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Run", winreg.KEY_SET_VALUE, winreg.KEY_ALL_ACCESS|winreg.KEY_WRITE|winreg.KEY_CREATE_SUB_KEY)#By IvanHanloth
try:
winreg.DeleteValue(key, name)
except FileNotFoundError:
print(f"{name} not found in startup.")
else:
print(f"{name} removed from startup.")
winreg.CloseKey(key)
使用说明
基于sys、os、winreg模块实现的程序开机自启,其中add_to_startup()
函数用于添加自启动项,remove_from_startup()
函数用于删除启动项
依赖模块
无需自行安装额外模块
自带模块:sys、os、winreg
参数说明
name(str)
:添加到注册表中的键值,需要具有一定标识性、独特性,避免与其他键重复,推荐使用程序名称
file_path(str)
(可选):需要添加到启动项的文件地址,不填写默认为当前脚本所在地址
使用实例(For 可执行文件)
#注意!演示默认你已经引入了模块和函数
#添加当前文件至启动项
add_to_startup("MyApp")
#添加其他文件至启动项
add_to_startup("AnotherApp","D:\path\another.exe")
#删除第一次添加的启动项
remove_from_startup("MyApp")
#删除第二次添加的启动项
remove_from_startup("AnotherApp")
使用实例(For Python文件)
#注意!演示默认你已经引入了模块和函数
#添加当前py文件至启动项
add_to_startup("MyPythonFile",sys.executable+os.path.realpath(sys.argv[0]))
#添加其他py文件至启动项
add_to_startup("AnotherPythonFile",sys.executable+"D:\path\another.py")
#删除第一次添加的启动项
remove_from_startup("MyPythonFile")
#删除第二次添加的启动项
remove_from_startup("AnotherPythonFile")
函数实现步骤&winreg.OpenKey()函数详解
不告诉你,被我吃掉了
来作者博客看>>
https://blog.ivan-hanloth.cn/index.php/archives/593/