7人参与 • 2026-03-17 • Python
在 python 中实现程序开机自启动,有多种方法可以完成。以下是一些常见的方法,适用于不同的操作系统(windows、linux 和 macos)。
import os
import sys
import shutil
import getpass
def set_autostart_windows_startup():
# 获取当前用户的用户名
username = getpass.getuser()
# 获取当前脚本的路径
script_path = os.path.abspath(sys.argv[0])
# 启动文件夹路径
startup_folder = f"c:\\users\\{username}\\appdata\\roaming\\microsoft\\windows\\start menu\\programs\\startup"
# 创建快捷方式
shortcut_path = os.path.join(startup_folder, "usbmonitor.lnk")
if not os.path.exists(shortcut_path):
try:
import winshell
from win32com.client import dispatch
shell = dispatch('wscript.shell')
shortcut = shell.createshortcut(shortcut_path)
shortcut.targetpath = sys.executable # python解释器路径
shortcut.arguments = f'"{script_path}"' # 脚本路径
shortcut.workingdirectory = os.path.dirname(script_path)
shortcut.iconlocation = script_path
shortcut.save()
print(f"已创建开机启动快捷方式: {shortcut_path}")
return true
except exception as e:
print(f"创建快捷方式失败: {e}")
return false
else:
print("快捷方式已存在")
return trueimport winreg
import sys
import os
def set_autostart_windows_registry(app_name, path_to_exe):
# 打开注册表键
key = winreg.hkey_current_user
key_path = r"software\microsoft\windows\currentversion\run"
try:
registry_key = winreg.openkey(key, key_path, 0, winreg.key_write)
winreg.setvalueex(registry_key, app_name, 0, winreg.reg_sz, path_to_exe)
winreg.closekey(registry_key)
print(f"已添加注册表开机启动项: {app_name}")
return true
except windowserror as e:
print(f"注册表操作失败: {e}")
return false
# 使用方法
if __name__ == "__main__":
app_name = "usbmonitor"
# 如果是.py文件
python_exe = sys.executable
script_path = os.path.abspath(sys.argv[0])
path_to_exe = f'"{python_exe}" "{script_path}"'
# 如果是打包后的.exe文件
# path_to_exe = os.path.abspath(sys.argv[0])
set_autostart_windows_registry(app_name, path_to_exe)import os
import sys
import getpass
def set_autostart_linux_desktop():
# 获取当前用户的用户名
username = getpass.getuser()
# 获取当前脚本的路径
script_path = os.path.abspath(sys.argv[0])
# .desktop文件内容
desktop_file_content = f"""[desktop entry]
type=application
exec={sys.executable} {script_path}
hidden=false
nodisplay=false
x-gnome-autostart-enabled=true
name=usbmonitor
comment=usb设备监控程序
"""
# 创建autostart目录(如果不存在)
autostart_dir = f"/home/{username}/.config/autostart"
os.makedirs(autostart_dir, exist_ok=true)
# 写入.desktop文件
desktop_file_path = os.path.join(autostart_dir, "usbmonitor.desktop")
try:
with open(desktop_file_path, 'w') as f:
f.write(desktop_file_content)
# 设置可执行权限
os.chmod(desktop_file_path, 0o755)
print(f"已创建开机启动.desktop文件: {desktop_file_path}")
return true
except exception as e:
print(f"创建.desktop文件失败: {e}")
return falseimport os
import sys
import getpass
def set_autostart_linux_systemd():
# 获取当前用户的用户名
username = getpass.getuser()
# 获取当前脚本的路径
script_path = os.path.abspath(sys.argv[0])
# systemd服务文件内容
service_file_content = f"""[unit]
description=usb device monitor
after=network.target
[service]
type=simple
user={username}
execstart={sys.executable} {script_path}
restart=on-failure
[install]
wantedby=multi-user.target
"""
# 需要root权限写入系统服务目录
service_file_path = "/etc/systemd/system/usbmonitor.service"
print("需要root权限来创建systemd服务文件")
print(f"请手动创建文件: {service_file_path}")
print("内容如下:")
print(service_file_content)
print("\n然后执行以下命令:")
print("sudo systemctl daemon-reload")
print("sudo systemctl enable usbmonitor.service")
print("sudo systemctl start usbmonitor.service")
return false # 需要手动操作# 在usbservergui类中添加
class usbservergui(qmainwindow):
def __init__(self):
# ... 原有代码 ...
self.create_autostart_menu()
def create_autostart_menu(self):
menubar = self.menubar()
settings_menu = menubar.addmenu('设置')
autostart_action = qaction('开机自启动', self, checkable=true)
autostart_action.setchecked(self.check_autostart())
autostart_action.triggered.connect(self.toggle_autostart)
settings_menu.addaction(autostart_action)
def check_autostart(self):
"""检查是否已设置开机自启动"""
if platform.system() == 'windows':
try:
key = winreg.hkey_current_user
key_path = r"software\microsoft\windows\currentversion\run"
registry_key = winreg.openkey(key, key_path, 0, winreg.key_read)
value, _ = winreg.queryvalueex(registry_key, "usbmonitor")
winreg.closekey(registry_key)
return os.path.exists(value.split('"')[1]) # 检查路径是否存在
except windowserror:
return false
else: # linux
username = getpass.getuser()
desktop_file = f"/home/{username}/.config/autostart/usbmonitor.desktop"
return os.path.exists(desktop_file)
def toggle_autostart(self, enabled):
"""切换开机自启动设置"""
if platform.system() == 'windows':
app_name = "usbmonitor"
python_exe = sys.executable
script_path = os.path.abspath(sys.argv[0])
path_to_exe = f'"{python_exe}" "{script_path}"'
if enabled:
success = set_autostart_windows_registry(app_name, path_to_exe)
else:
success = remove_autostart_windows_registry(app_name)
else: # linux
if enabled:
success = set_autostart_linux_desktop()
else:
success = remove_autostart_linux_desktop()
if not success:
# 显示错误消息
msg = qmessagebox()
msg.seticon(qmessagebox.warning)
msg.settext("修改开机自启动设置失败")
msg.setwindowtitle("错误")
msg.exec_()# 在usbclientgui类中添加类似代码
class usbclientgui(qmainwindow):
def __init__(self):
# ... 原有代码 ...
self.create_autostart_menu()
def create_autostart_menu(self):
# 类似于服务器端的实现
pass选择适合的方法:
添加到你的pyqt应用:
测试:
打包注意事项:
权限问题:
路径问题:
安全考虑:
多平台兼容:
platform.system()检测操作系统通过以上方法,开发的应用可以在系统启动时自动运行,非常适合监控类应用程序的需求。
以上就是python实现程序开机自启动的常见方案的详细内容,更多关于python开机自启动的资料请关注代码网其它相关文章!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论