How to start a python file while Windows starts?

PythonWindows

Python Problem Overview


I have a python file and I am running the file.

If Windows is shutdown and booted up again, how I can run that file every time Windows starts?

Python Solutions


Solution 1 - Python

Depending on what the script is doing, you may:

  1. package it into a service, that should then be installed
  2. add it to the windows registry (HKCU\Software\Microsoft\Windows\CurrentVersion\Run)
  3. add a shortcut to it to the startup folder of start menu - its location may change with OS version, but installers always have some instruction to put a shortcut into that folder
  4. use windows' task scheduler, and then you can set the task on several kind of events, including logon and on startup.

The actual solution depends on your needs, and what the script is actually doing.
Some notes on the differences:

  • Solution #1 starts the script with the computer, while solution #2 and #3 start it when the user who installed it logs in.
  • It is also worth to note that #1 always start the script, while #2 and #3 will start the script only on a specific user (I think that if you use the default user then it will start on everyone, but I am not sure of the details).
  • Solution #2 is a bit more "hidden" to the user, while solution #3 leaves much more control to the user in terms of disabling the automatic start.
  • Finally, solution #1 requires administrative rights, while the other two may be done by any user.
  • Solution #4 is something I discovered lately, and is very straightforward. The only problem I have noticed is that the python script will cause a small command window to appear.

As you can see, it all boils down to what you want to do; for instance, if it is something for your purposes only, I would simply drag it into startup folder.

In any case, lately I am leaning on solution #4, as the quickest and most straightforward approach.

Solution 2 - Python

you can simply add the following code to your script. Nevertheless, this works only on windows!:

import getpass
USER_NAME = getpass.getuser()


def add_to_startup(file_path=""):
    if file_path == "":
        file_path = os.path.dirname(os.path.realpath(__file__))
    bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER_NAME
    with open(bat_path + '\\' + "open.bat", "w+") as bat_file:
        bat_file.write(r'start "" "%s"' % file_path)

this function will create a bat file in the startup folder that will run your script.

the file_path is the path to the file that you would like to run when your computer opens.

you can leave it blank in order to add the running script to startup.

Solution 3 - Python

Haven't tested this, but I'd create a batch file that contains "python yourfile.py" and put that in the autostart folder.

On Windows 7 you can find it here:

%APPDATA%\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Solution 4 - Python

In the following startup directory (at least this path exists on Windows XP):

C:\Documents and Settings\All Users\Start Menu\Programs\Startup

put a shortcut to your python program. It should be executed every time your system starts up.

Solution 5 - Python

  • click Win+R

  • type shell:startup

  • drag and drop your python file my_script.py

    • if you don't need the console: change extension from my_script.py to my_script.pyw
    • else: create run_my_script.cmd with content: python path\to\your\my_script.py

Solution 6 - Python

You can put run_script.cmd in

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

Content of run_script.cmd

python path\to\your\script.py

Solution 7 - Python

import winreg

def set_autostart_registry(app_name, key_data=None, autostart: bool = True) -> bool:
    """
    Create/update/delete Windows autostart registry key

    ! Windows ONLY
    ! If the function fails, OSError is raised.

    :param app_name:    A string containing the name of the application name
    :param key_data:    A string that specifies the application path.
    :param autostart:   True - create/update autostart key / False - delete autostart key
    :return:            True - Success / False - Error, app name dont exist
    """

    with winreg.OpenKey(
            key=winreg.HKEY_CURRENT_USER,
            sub_key=r'Software\Microsoft\Windows\CurrentVersion\Run',
            reserved=0,
            access=winreg.KEY_ALL_ACCESS,
    ) as key:
        try:
            if autostart:
                winreg.SetValueEx(key, app_name, 0, winreg.REG_SZ, key_data)
            else:
                winreg.DeleteValue(key, app_name)
        except OSError:
            return False
    return True


def check_autostart_registry(value_name):
    """
    Check Windows autostart registry status

    ! Windows ONLY
    ! If the function fails, OSError is raised.

    :param value_name:  A string containing the name of the application name
    :return: True - Exist / False - Not exist
    """

    with winreg.OpenKey(
            key=winreg.HKEY_CURRENT_USER,
            sub_key=r'Software\Microsoft\Windows\CurrentVersion\Run',
            reserved=0,
            access=winreg.KEY_ALL_ACCESS,
    ) as key:
        idx = 0
        while idx < 1_000:     # Max 1.000 values
            try:
                key_name, _, _ = winreg.EnumValue(key, idx)
                if key_name == value_name:
                    return True
                idx += 1
            except OSError:
                break
    return False

Create autostart:

set_autostart_registry('App name', r'C:\test\x.exe')

Update autostart:

set_autostart_registry('App name', r'C:\test\y.exe')

Delete autostart:

set_autostart_registry('App name', autostart=False)

Check autostart:

if check_autostart_registry('App name'):

Solution 8 - Python

try adding an entry to "HKLM/SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" . Right click ->new -> string value -> add file path

Solution 9 - Python

  1. Create an exe file, I use pyinstaller "yourCode.py"

  2. Add the execution file to your registry key: https://cmatskas.com/configure-a-runonce-task-on-windows/

Solution 10 - Python

Above mentioned all the methods did not worked I tried them all , I will tell you more simpler solution and alternative of windows task scheduler

Create a .bat file with content "ADDRESS OF YOUR PROJECT INTERPRETER" "ADDRESS OF YOUR PYTHON SCRIPT WITH SCRIPT NAME"

Store this bat file into the window startup folder(by default hidden) FYI: to find window startup folder press windos+r then type shell:startup -- it will directly take you to the startup folder

copy the bat file there with following 2 address in the same format , then simply restart the system or shut down and boot up.

The code will automatically run within 20 seconds of opening.

Thank me later

Solution 11 - Python

import shutil
from os import path
import getpass
USER_NAME = getpass.getuser()
source_path = "hi.txt"
    
if path.exists(source_path):
    destination_path = "C://Users//%s//AppData//Roaming//Microsoft//Windows//Start Menu//Programs//Startup" % USER_NAME
    new_location = shutil.copy(source_path, destination_path)
    print("% s перемещен в указанное место,% s" % (source_path , new_location))
    print(destination_path)
else :
    print ("Файл не существует.")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsamView Question on Stackoverflow
Solution 1 - PythonrobView Answer on Stackoverflow
Solution 2 - PythontzadokView Answer on Stackoverflow
Solution 3 - PythonLiMuBeiView Answer on Stackoverflow
Solution 4 - PythondariooView Answer on Stackoverflow
Solution 5 - PythonSzczerskiView Answer on Stackoverflow
Solution 6 - PythonRahulView Answer on Stackoverflow
Solution 7 - PythonscjvView Answer on Stackoverflow
Solution 8 - PythonRedDeathView Answer on Stackoverflow
Solution 9 - PythonNoelView Answer on Stackoverflow
Solution 10 - Pythonrajat prakashView Answer on Stackoverflow
Solution 11 - PythonXakn QurbonovView Answer on Stackoverflow