Autorun a Python script on windows startup?


Appending a Python script to windows start-up basically indicates the python script will run as the windows boots up. This can be accomplished by two step processes -

Step #1: Appending or Adding script to windows Startup folder

After booting up of the windows, it executes (equivalent to double-clicking) all the application present in its startup folder or directory.

Address

C:\Users\current_user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\

By default, the AppData directory or folder under the current_user is hidden that enable hidden files to get it and paste the shortcut of the script in the given address or the script itself. Besides this the .PY files default must be set to python IDE else the script may end up opening as a text instead of executing.

Step #2: Appending or adding script to windows Registry

This process may be risky if not accomplished properly, it includes editing the windows registry key HKEY_CURRENT_USER from the python script itself. This registry consists of the list of programs that must execute once the user Login. Registry Path

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

Below is the Python code

# Python code to append or add current script to the registry
# module to modify or edit the windows registry
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()

Updated on: 29-Jan-2020

995 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements