相比于修改注册表实现开机自启动,可以直接在windows的本用户目录的自启动文件夹下创建快捷方式同样实现开机自启动,并且无需管理员权限
import os
from win32com.client import Dispatch
def auto_start_on():
create_shortcut(get_shortcut_create_path())
def auto_start_off():
delete_shortcut(get_shortcut_create_path())
def get_shortcut_create_path():
current_username = os.getlogin()
full_filename = os.path.basename(__file__)
filename, ext = os.path.splitext(full_filename)
shortcut_location = r"C:\Users\{}\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\{}.lnk".format(
current_username, filename)
return shortcut_location
def create_shortcut(shortcut_location):
target_path = os.path.abspath(__file__)
shell = Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(shortcut_location)
shortcut.Targetpath = target_path
shortcut.save()
def delete_shortcut(shortcut_location):
if os.path.exists(shortcut_location):
try:
os.remove(shortcut_location)
except Exception as e:
print("删除文件失败",e)
else:
print("没有找到快捷方式")
if __name__ == '__main__':
auto_start_on()