import os
import pythoncom
from win32com.shell import shell
from win32com.shell import shellcondef set_shortcut(): # 如無需特別設置圖標,則可去掉iconname參數try:filename = r"D:\AppServ\timer\win_cron_zq\timer.exe" # 要創建快捷方式的文件的完整路徑iconname = ""lnkname = r"C:\Users\pc1\Desktop" + r"\timer.exe.lnk" # 將要在此路徑創建快捷方式shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None,pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)shortcut.SetPath(filename)shortcut.SetWorkingDirectory(r"D:\AppServ\timer\win_cron_zq") # 設置快捷方式的起始位置, 不然會出現找不到輔助文件的情況shortcut.SetIconLocation(iconname, 0) # 可有可無,沒有就默認使用文件本身的圖標if os.path.splitext(lnkname)[-1] != '.lnk':lnkname += ".lnk"shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(lnkname, 0)return Trueexcept Exception as e:print(e.args)return False
剛開始沒有設置shortcut.SetWorkingDirectory(r"D:\AppServ\timer\win_cron_zq")這一步,結果快捷方式雖然能執行,總是提示找不到相應的其他相輔相成的文件, 加上這個起始位置設置后, 就可以了 ,這里記一下