简体   繁体   中英

Python script autorun on windows startup

I am trying to create a script that will display a page in chrome on startup. That is, I am trying to run a python script on startup. I am using the winreg module to do so.

Here is my script to add a my page display script on startup:

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()

Here is my page display script:

import webbrowser

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

chrome_path = 'path_to_chrome/chrome.exe %s'

webbrowser.get(chrome_path).open(url)

The script runs fine without any errors but on restarting my machine, the chrome does not open up by itself nor does it display the page. Basically, my script does not run. What is wrong? Kindly help me out.

The problem isn't with your script. It's with your registry key.

You need to tell windows to invoke Python.exe C:\path_to_script\test.py , not test.py .

So instead of this:

This:

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;

Or if Python.exe is guaranteed to be in your PATH, simply this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM