Windows启动时Python脚本自动运行

时间:2019-10-31 10:08:32

标签: python windows winreg

我正在尝试创建一个脚本,该脚本将在启动时以chrome显示页面。也就是说,我正在尝试在启动时运行python脚本。我正在使用winreg模块来做到这一点。

这是我的脚本,用于在启动时添加我的页面显示脚本:

import winreg  
import os    
import sys, traceback          

def AddToRegistry(): 


    pth = os.path.dirname(os.path.realpath(path_to_page_display_script)) 

    s_name="test.py"     

    address=os.path.join(pth,s_name)  

    try:
        open = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\\Microsoft\\Windows\\CurrentVersion\\Run", reserved=0, access = winreg.KEY_ALL_ACCESS) 

        winreg.SetValueEx(open,"pytest",0,winreg.REG_SZ,address) 

        winreg.CloseKey(open)

    except Exception:
        traceback.print_exc(file=sys.stdout)

if __name__=="__main__": 
    AddToRegistry()

这是我的页面显示脚本:

import webbrowser

url = 'http://docs.python.org/'

chrome_path = 'path_to_chrome/chrome.exe %s'

webbrowser.get(chrome_path).open(url)

脚本运行正常,没有任何错误,但是在重新启动计算机后,Chrome无法自行打开,也不会显示页面。基本上,我的脚本无法运行。怎么了 ?请帮我。

1 个答案:

答案 0 :(得分:2)

问题不在于您的脚本。这是您的注册表项。

您需要告诉Windows调用Python.exe C:\path_to_script\test.py,而不是test.py

所以代替这个:

此:

path_to_python_exe = "C:\\python\\python38";
address=os.path.join(pth,s_name)  
address = os.path.join(path_to_python_exe, "python.exe") + " " + address;

或者,如果保证Python.exe位于您的PATH中,则只需执行以下操作:

address = "Python.exe" + " " + os.path.join(pth,s_name)