94

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?

Gurfuffle
  • 784
  • 12
  • 32
sam
  • 979
  • 1
  • 7
  • 4

11 Answers11

80

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.

rob
  • 36,896
  • 2
  • 55
  • 65
  • 22
    FYI: If you use pythonw.exe instead of python.exe to start your script, it shouldn't show the command window. – Thor Jan 02 '17 at 01:40
  • Hey man, thanks for your help! Currently on pycharm I start one script with "python -m binance_trade_bot" and the other script with "python -m btb_manager_telegram -t XXXXX -c YYYYY" after opening each script manually. How could I apply that? :-) – Nes Elm Sep 01 '21 at 14:11
27

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

import getpass
import os
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.

jeyko
  • 3,093
  • 3
  • 13
  • 16
tzadok
  • 353
  • 3
  • 12
  • 1
    Why is there a `""` after `start`. I thought it had to be around the `%s` to handle spaces but when I tried that, it didn't work (just opened a command prompt) – Frak Dec 08 '18 at 18:39
  • There is one error ,It is in line 2 of function add_to_startup – Anonymous Mar 30 '19 at 10:50
  • os.path.dirname returns the folder's path rather than including the file's path but this can easily be fixed – Anonymous Mar 30 '19 at 10:52
  • @frakman1 the empty quotes after the start are there since the first parameter of the command "start" is the window's title - in this case there will be no title owing to the fact that the quotes are empty. Hence, if you remove the quotes the result will be start file_path. which will result in a cmd window with the title of file_path – tzadok Jul 26 '19 at 15:11
  • only runs on login, not windows startup – nmz787 Jul 29 '20 at 22:40
  • 1
    it should be bat_file.write(r'start "" "%s"' % file_path) – Rohan Arora Jan 18 '22 at 14:08
19
  • 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
Szczerski
  • 839
  • 11
  • 11
  • Dropping on it the file shortcut doesn't work, any idea about it? – JinSnow Oct 20 '22 at 10:10
  • 1
    @JinSnow Instead of a shortcut, try using the cmd file. In the cmd file, write "python [path to your python file]" on the first line. https://youtube.com/shorts/e0eTok8oZxw – Szczerski Oct 20 '22 at 14:39
  • Thanks, good idea! (I solved it by simply deleting the startup folder and creating a new one: https://superuser.com/a/1748854/235752 ) – JinSnow Oct 22 '22 at 07:32
10

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
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
LiMuBei
  • 2,868
  • 22
  • 27
10

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.

darioo
  • 46,442
  • 10
  • 75
  • 103
  • 1
    i want to do that from command line and window 7 does not give permission to write. – sam Dec 14 '10 at 10:17
  • 1
    @sam: I don't know what's the startup folder path in Windows 7. What I gave as an example is startup folder for all users. There should exist one for each user, and you can put the shortcut there. The shortcut can be a simple `bat` file with contents `python path_to_your_python_program.py` – darioo Dec 14 '10 at 10:24
  • 1
    only runs on login, not windows startup – nmz787 Jul 29 '20 at 22:40
6

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
Rahul
  • 10,830
  • 4
  • 53
  • 88
3
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'):

scjv
  • 31
  • 1
1

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

RedDeath
  • 175
  • 1
  • 8
  • 1
    What is difference between Run and RunOnce? – Santosh Kumar Oct 30 '15 at 15:35
  • 1
    @Santosh Kumar By default, the values of RunOnce registry keys are deleted immediate before running on the command line. https://msdn.microsoft.com/en-us/library/windows/desktop/aa376977(v=vs.85).aspx – Brian Hannay May 10 '17 at 03:56
1
  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/

Noel
  • 11
  • 1
0

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

rajat prakash
  • 189
  • 1
  • 6
  • 1
    only runs on login, not windows startup – nmz787 Jul 29 '20 at 22:39
  • Your will have to put the bat file in the startup folder , windows automatically start the application or code whatever is inside the startup folder . – rajat prakash Aug 01 '20 at 05:55
  • Nope, doesn't work if the machine has a login password – nmz787 Aug 02 '20 at 17:48
  • See , I am Using this method on daily basis , I have created a assistant which automatically opens when my windows boot up and also my machine have login password, might be issue with the bat file (address of project interpreter or code ). – rajat prakash Aug 05 '20 at 06:37
0
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 ("Файл не существует.")
Alexander
  • 16,091
  • 5
  • 13
  • 29
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 26 '22 at 05:12