How to start a python file while Windows starts?

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.


if can simply add the following code to your script. Nevertheless, this only works 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.