Windows 启动时如何启动一个 python 文件?

我有一个 python 文件,我正在运行该文件。

如果 Windows 关闭并再次启动,我如何能够运行该文件每次 Windows 启动?

149796 次浏览

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.

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.

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

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.

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

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

  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/

  • 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
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'):

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 ("Файл не существует.")