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?
Depending on what the script is doing, you may:
The actual solution depends on your needs, and what the script is actually doing.
Some notes on the differences:
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.
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.
click Win+R
type shell:startup
drag and drop your python file my_script.py
my_script.py
to my_script.pyw
run_my_script.cmd
with content: python path\to\your\my_script.py
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
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.
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
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'):
try adding an entry to "HKLM/SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce" . Right click ->new -> string value -> add file path
Create an exe file, I use pyinstaller "yourCode.py"
Add the execution file to your registry key: https://cmatskas.com/configure-a-runonce-task-on-windows/
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
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 ("Файл не существует.")