# -*- coding:utf-8 -*-
# author:lizonezhi
import os
import sys
import pythoncom
import win32com.client as client
def createShortCut(filename): # 目前创建的无起始位置
"""filename should be abspath, or there will be some strange errors"""
try:
# 设置快捷方式的起始位置,此处设置为windows启动目录
working_directory = os.getenv(
'USERPROFILE') + '\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\\'
# 创建快捷方式的目标绝对路径
lnkname = working_directory + filename + '.lnk'
# 要创建快捷方式的文件的绝对路径,此处是获取当前路径
filename = os.path.dirname(os.path.realpath(sys.argv[0])) + '\\' + filename
shortcut = client.Dispatch("WScript.Shell").CreateShortCut(lnkname)
shortcut.TargetPath = filename
shortcut.save()
print('配置开机自启')
except Exception as e:
print(e.args)
def set_shortcut(filename): # 如无需特别设置图标,则可去掉iconname参数
try:
from win32com.shell import shell
from win32com.shell import shellcon
iconname = ""
# 设置快捷方式的起始位置,此处设置为windows启动目录
working_directory = os.getenv(
'USERPROFILE') + '\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\\'
# 创建快捷方式的目标绝对路径
lnkname = working_directory + filename + '.lnk'
# 要创建快捷方式的文件的绝对路径,此处是获取当前路径
filename = os.path.dirname(os.path.realpath(sys.argv[0])) + '\\' + filename
shortcut = pythoncom.CoCreateInstance(
shell.CLSID_ShellLink, None,
pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
shortcut.SetPath(filename)
# 设置快捷方式的起始位置, 不然会出现找不到辅助文件的情况
shortcut.SetWorkingDirectory(working_directory)
# 可有可无,没有就默认使用文件本身的图标
shortcut.SetIconLocation(iconname, 0)
if os.path.splitext(lnkname)[-1] != '.lnk':
lnkname += ".lnk"
shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(lnkname, 0)
return True
except Exception as e:
print(e.args)
return False
set_shortcut('test.exe')
以上代码打包为test.exe后,双击启动,可配置自身开机自启(exe不能是uac管理员权限)。或者配置其它程序。
按 WIN + R 输入 shell:startup 回车打开windows启动目录查看结果。
参考文章: