How to run a Python file when windows starts

In this tutorial, we are going to learn how to run a Python file when windows starts, what we really mean here is as soon as we boot up our windows the Python script should start running. It can be either achieved by it by adding the script of our Python file to the windows startup folder in which we generally add out file script to the windows startup folder or WE can add the script to windows Registry, this is not a safe process we have to do it with utmost care because we are editing the Windows registry key.

Processes by which we can run a Python file when windows starts

Method 1:

As soon as windows boots up, it executes (opens) all the applications present in the startup folder or catalog or directory.

 

Address

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

Eg :- C:\Users\Anmol\AppData\Roaming\Microsoft\Windows\Start Menu\Programs

You can get the location by these simple steps:

  1. Go to the Start
  2. Search run
  3. Search for “ Shell:startup “
  4. Now you can extract the location of your startup folder.

The.PY files by default they should be set to Python IDE else script opens as a text instead of executing the file.

 

Method 2:  WE can add the script to Windows Registry

This is not a safe process we have to do it with utmost care cause if it is to done properly because we are editing the windows registry key HKEY_CURRENT_USER from the Python script itself. This registry contains the list of all the programs that are to be run once the windows boots up and we perform user-login. just like few other applications which Start up when windows start because of the change in registry and add their path to it.

import winreg as reg10  
import os
  • We import winreg as reg10 because This function helps us to use the Windows registry API to Python.
  • Importing os as It offers portable operating system functionalities.
file_path = os.path.dirname(os.path.realpath(__file__)) 
source_file_name="anmol.py" 
add_file=os.join(file_path,source_file_name)
key_curr_user = HKEY_CURRENT_USER 
val_key = "Software\Microsoft\Windows\CurrentVersion\Run"
  • __file__ means the file path where it was executed
  • anmol.py is the name of the file with py extension
  • Now we are joining the name to the end of the path address
  • We want to change  HKEY_CURRENT_USER
  • Value_key is Software\Microsoft\Windows\CurrentVersion\Run
open_key = reg10.OpenKey(key,val_key ,0,reg10.KEY_ALL_ACCESS)
reg10.SetValueEx(open,"anyname",0,reg10.REG_SZ,address)
  • Opening the key to make changes
  • Now modify the opened key
reg10.CloseKey(open) 
if __name__=="__main__": 
    AddToRegistry()
  • Now closing the opened key

Leave a Reply