我有一个Python文件,正在运行该文件。
如果Windows系统被关闭并重新启动,我该如何使该文件在每次Windows启动时自动运行?
根据脚本的实际功能,你可能需要:
实际解决方案取决于您的需求以及脚本实际要做什么。
一些关于区别的注释:
正如您所看到的,所有这些都归结于你想要做什么;例如,如果只是为了您自己的目的,我会简单地将其拖放到启动文件夹中。
无论如何,最近我倾向于使用解决方案#4,因为它是最快和最直接的方法。
您可以将以下代码简单地添加到您的脚本中。然而,这只适用于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)
这个函数将在启动文件夹中创建一个批处理文件,该文件将运行您的脚本。
file_path
是您想要在计算机开机时运行的文件路径。
如果您想将运行的脚本添加到启动项中,则可以将其留空。
start
后面要加上 ""
。我以为它必须放在 %s
周围来处理空格,但是当我尝试这样做时,它没有起作用(只是打开了一个命令提示符)。 - Frak按下Win+R
输入shell:startup
将你的Python文件my_script.py
拖放进去
my_script.py
改为my_script.pyw
run_my_script.cmd
并添加内容:python path\to\your\my_script.py
我没有测试过,但我会创建一个包含"python yourfile.py"的批处理文件,并将其放入自动启动文件夹中。
在Windows 7上,您可以在这里找到它:
%APPDATA%\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
shell:common startup
- Vivek S.C:\Documents and Settings\All Users\Start Menu\Programs\Startup
在你的Python程序中创建一个快捷方式。它应该在每次系统启动时被执行。
bat
文件,其中包含python path_to_your_python_program.py
的内容。 - darioo您可以将 run_script.cmd 放在
C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
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
创建自启动:
set_autostart_registry('应用名称', r'C:\test\x.exe')
更新自启动:
set_autostart_registry('应用名称', r'C:\test\y.exe')
删除自启动:
set_autostart_registry('应用名称', autostart=False)
检查自启动状态:
if check_autostart_registry('应用名称'):
尝试将一个条目添加到"HKLM/SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"。 右键单击->新建->字符串值->添加文件路径
创建一个exe文件,我使用pyinstaller "yourCode.py"
将执行文件添加到您的注册表键中: https://cmatskas.com/configure-a-runonce-task-on-windows/
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 ("Файл не существует.")