在 Windows 启动时自动运行 Python 脚本?
pythonserver side programmingprogramming更新于 2025/4/14 7:08:17
将 Python 脚本附加到 Windows 启动基本上表示 Python 脚本将在 Windows 启动时运行。这可以通过两个步骤完成 -
步骤 1:将脚本附加或添加到 Windows 启动文件夹
启动 Windows 后,它会执行(相当于双击)其启动文件夹或目录中存在的所有应用程序。
地址
C:\Users\current_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\
默认情况下,current_user 下的 AppData 目录或文件夹是隐藏的,允许隐藏文件获取它并将脚本的快捷方式粘贴到给定的地址或脚本本身中。除此之外,.PY 文件的默认设置必须设置为 python IDE,否则脚本最终可能会以文本形式打开而不是执行。
步骤 #2:将脚本附加或添加到 Windows 注册表
如果操作不当,此过程可能会有风险,它包括从 Python 脚本本身编辑 Windows 注册表项 HKEY_CURRENT_USER。此注册表包含用户登录后必须执行的程序列表。注册表路径−
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
以下是 Python 代码
# 用于将当前脚本附加或添加到注册表的 Python 代码 # 用于修改或编辑 Windows 注册表的模块 importwinreg as reg1 importos
defAddToRegistry() −
# in python __file__ is denoeted as the instant of # file path where it was run or executed # so if it was executed from desktop, # then __file__ will be # c:\users\current_user\desktop pth1 =os.path.dirname(os.path.realpath(__file__)) # Python file name with extension s_name1="mYscript.py" # The file name is joined to end of path address address1=os.join(pth1,s_name1) # key we want to modify or change is HKEY_CURRENT_USER # key value is Software\Microsoft\Windows\CurrentVersion\Run key1 =HKEY_CURRENT_USER key_value1 ="Software\Microsoft\Windows\CurrentVersion\Run" # open the key to make modifications or changes to open=reg1.OpenKey(key1,key_value1,0,reg1.KEY_ALL_ACCESS) # change or modifiy the opened key reg1.SetValueEx(open,"any_name",0,reg1.REG_SZ,address1) # now close the opened key reg1.CloseKey(open) # Driver Code if__name__=="__main__": AddToRegistry()
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

