Search code examples
pythonstartup

Getting the program into Windows startup


Is there a way to make this function directly in the script so that when the program starts, it automatically goes to startup C: \ Users \% NaMe% \ AppData \ Roaming \ Microsoft \ Windows \ Start Menu \ Programs \ Startup.

Thanks for the ideas.


Solution

  • First of all, if this is your own PC you can physically go to that location and paste it and from task manager make it run on startup.

    But second, if you want to do on a different script I would recommend making an external python file with code something like this.

    import winreg as reg  
    import os              
    
    def AddToRegistry(): 
    
        # in python __file__ is the instant of 
        # file path where it was executed  
        # so if it was executed from desktop, 
        # then __file__ will be  
        # c:\users\current_user\desktop 
        pth = os.path.dirname(os.path.realpath(__file__)) 
    
        # name of the python file with extension 
        s_name="mYscript.py"     
    
        # joins the file name to end of path address 
        address=os.join(pth,s_name)  
    
        # key we want to change is HKEY_CURRENT_USER  
        # key value is Software\Microsoft\Windows\CurrentVersion\Run 
        key = HKEY_CURRENT_USER 
        key_value = "Software\Microsoft\Windows\CurrentVersion\Run"
    
        # open the key to make changes to 
        open = reg.OpenKey(key,key_value,0,reg.KEY_ALL_ACCESS) 
    
        # modifiy the opened key 
        reg.SetValueEx(open,"any_name",0,reg.REG_SZ,address) 
    
        # now close the opened key 
        reg.CloseKey(open) 
    
    if __name__=="__main__": 
        AddToRegistry()
    

    You can also add this to the same file, but it may result in unforeseen circumstances. You can click here or go to the below-mentioned link to learn more and add some other options.

    https://www.geeksforgeeks.org/autorun-a-python-script-on-windows-startup/