Python實(shí)現(xiàn)程序開機(jī)自啟動(dòng)的常見(jiàn)方案
在 Python 中實(shí)現(xiàn)程序開機(jī)自啟動(dòng),有多種方法可以完成。以下是一些常見(jiàn)的方法,適用于不同的操作系統(tǒng)(Windows、Linux 和 macOS)。
Windows系統(tǒng)開機(jī)自啟動(dòng)方法
方法1:通過(guò)啟動(dòng)文件夾實(shí)現(xiàn)
import os
import sys
import shutil
import getpass
def set_autostart_windows_startup():
# 獲取當(dāng)前用戶的用戶名
username = getpass.getuser()
# 獲取當(dāng)前腳本的路徑
script_path = os.path.abspath(sys.argv[0])
# 啟動(dòng)文件夾路徑
startup_folder = f"C:\\Users\\{username}\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"
# 創(chuàng)建快捷方式
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"已創(chuàng)建開機(jī)啟動(dòng)快捷方式: {shortcut_path}")
return True
except Exception as e:
print(f"創(chuàng)建快捷方式失敗: {e}")
return False
else:
print("快捷方式已存在")
return True方法2:通過(guò)注冊(cè)表實(shí)現(xiàn)(更可靠)
import winreg
import sys
import os
def set_autostart_windows_registry(app_name, path_to_exe):
# 打開注冊(cè)表鍵
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"已添加注冊(cè)表開機(jī)啟動(dòng)項(xiàng): {app_name}")
return True
except WindowsError as e:
print(f"注冊(cè)表操作失敗: {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)Linux系統(tǒng)開機(jī)自啟動(dòng)方法
方法1:通過(guò).desktop文件實(shí)現(xiàn)(GNOME等桌面環(huán)境)
import os
import sys
import getpass
def set_autostart_linux_desktop():
# 獲取當(dāng)前用戶的用戶名
username = getpass.getuser()
# 獲取當(dāng)前腳本的路徑
script_path = os.path.abspath(sys.argv[0])
# .desktop文件內(nèi)容
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設(shè)備監(jiān)控程序
"""
# 創(chuàng)建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)
# 設(shè)置可執(zhí)行權(quán)限
os.chmod(desktop_file_path, 0o755)
print(f"已創(chuàng)建開機(jī)啟動(dòng).desktop文件: {desktop_file_path}")
return True
except Exception as e:
print(f"創(chuàng)建.desktop文件失敗: {e}")
return False方法2:通過(guò)systemd服務(wù)實(shí)現(xiàn)(適用于無(wú)桌面環(huán)境)
import os
import sys
import getpass
def set_autostart_linux_systemd():
# 獲取當(dāng)前用戶的用戶名
username = getpass.getuser()
# 獲取當(dāng)前腳本的路徑
script_path = os.path.abspath(sys.argv[0])
# systemd服務(wù)文件內(nèi)容
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權(quán)限寫入系統(tǒng)服務(wù)目錄
service_file_path = "/etc/systemd/system/usbmonitor.service"
print("需要root權(quán)限來(lái)創(chuàng)建systemd服務(wù)文件")
print(f"請(qǐng)手動(dòng)創(chuàng)建文件: {service_file_path}")
print("內(nèi)容如下:")
print(service_file_content)
print("\n然后執(zhí)行以下命令:")
print("sudo systemctl daemon-reload")
print("sudo systemctl enable usbmonitor.service")
print("sudo systemctl start usbmonitor.service")
return False # 需要手動(dòng)操作在PyQt應(yīng)用中集成開機(jī)自啟動(dòng)功能
服務(wù)器端添加設(shè)置選項(xiàng)
# 在USBServerGUI類中添加
class USBServerGUI(QMainWindow):
def __init__(self):
# ... 原有代碼 ...
self.create_autostart_menu()
def create_autostart_menu(self):
menubar = self.menuBar()
settings_menu = menubar.addMenu('設(shè)置')
autostart_action = QAction('開機(jī)自啟動(dòng)', 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):
"""檢查是否已設(shè)置開機(jī)自啟動(dòng)"""
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):
"""切換開機(jī)自啟動(dòng)設(shè)置"""
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:
# 顯示錯(cuò)誤消息
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setText("修改開機(jī)自啟動(dòng)設(shè)置失敗")
msg.setWindowTitle("錯(cuò)誤")
msg.exec_()客戶端同樣添加類似功能
# 在USBClientGUI類中添加類似代碼
class USBClientGUI(QMainWindow):
def __init__(self):
# ... 原有代碼 ...
self.create_autostart_menu()
def create_autostart_menu(self):
# 類似于服務(wù)器端的實(shí)現(xiàn)
pass完整實(shí)現(xiàn)步驟
選擇適合的方法:
- Windows: 推薦使用注冊(cè)表方法
- Linux桌面環(huán)境: 使用.desktop文件方法
- Linux服務(wù)器: 使用systemd方法
添加到你的PyQt應(yīng)用:
- 在設(shè)置菜單中添加"開機(jī)自啟動(dòng)"選項(xiàng)
- 實(shí)現(xiàn)檢查當(dāng)前狀態(tài)的函數(shù)
- 實(shí)現(xiàn)啟用/禁用的函數(shù)
測(cè)試:
- 重啟計(jì)算機(jī)驗(yàn)證是否自動(dòng)啟動(dòng)
- 測(cè)試禁用功能是否有效
打包注意事項(xiàng):
- 如果使用PyInstaller打包,路徑處理會(huì)有所不同
- 打包后應(yīng)該使用.exe路徑而不是.py路徑
注意事項(xiàng)
權(quán)限問(wèn)題:
- Windows需要管理員權(quán)限修改注冊(cè)表
- Linux需要root權(quán)限修改systemd服務(wù)
路徑問(wèn)題:
- 確保使用絕對(duì)路徑
- 打包后路徑會(huì)變化,需要特別處理
安全考慮:
- 不要硬編碼敏感信息
- 提供禁用自啟動(dòng)的選項(xiàng)
多平臺(tái)兼容:
- 使用
platform.system()檢測(cè)操作系統(tǒng) - 為不同平臺(tái)提供不同的實(shí)現(xiàn)
通過(guò)以上方法,開發(fā)的應(yīng)用可以在系統(tǒng)啟動(dòng)時(shí)自動(dòng)運(yùn)行,非常適合監(jiān)控類應(yīng)用程序的需求。
以上就是Python實(shí)現(xiàn)程序開機(jī)自啟動(dòng)的常見(jiàn)方案的詳細(xì)內(nèi)容,更多關(guān)于Python開機(jī)自啟動(dòng)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python+wxPython實(shí)現(xiàn)自動(dòng)生成PPTX文檔程序
這篇文章主要介紹了如何使用 wxPython 模塊和 python-pptx 模塊來(lái)編寫一個(gè)程序,用于生成包含首頁(yè)、內(nèi)容頁(yè)和感謝頁(yè)的 PPTX 文檔,感興趣的小伙伴可以學(xué)習(xí)一下2023-08-08
pytorch實(shí)現(xiàn)seq2seq時(shí)對(duì)loss進(jìn)行mask的方式
今天小編就為大家分享一篇pytorch實(shí)現(xiàn)seq2seq時(shí)對(duì)loss進(jìn)行mask的方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
Python PYQT界面點(diǎn)擊按鈕隨機(jī)變色功能
遇到這樣的需求寫一個(gè)pyqt界面,要求界面有一個(gè)按鈕,每次點(diǎn)擊這個(gè)按鈕,就會(huì)生成一個(gè)10以內(nèi)的隨機(jī)數(shù),當(dāng)隨機(jī)數(shù)出現(xiàn)的時(shí)候,界面底色要變成對(duì)應(yīng)的顏色,同時(shí)要求隨機(jī)數(shù)會(huì)在界面中展示出來(lái),并且按鈕和數(shù)字的顏色不會(huì)改變,下面給大家分享源代碼,一起看看吧2024-08-08
Python中判斷subprocess調(diào)起的shell命令是否結(jié)束
這篇文章主要介紹了Python中判斷subprocess調(diào)起的shell命令是否結(jié)束的方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04
基于nexus3配置Python倉(cāng)庫(kù)過(guò)程詳解
這篇文章主要介紹了基于nexus3配置Python倉(cāng)庫(kù)過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
詳解如何用django實(shí)現(xiàn)redirect的幾種方法總結(jié)
這篇文章主要介紹了如何用django實(shí)現(xiàn)redirect的幾種方法總結(jié),詳細(xì)的介紹3種實(shí)現(xiàn)方式,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
Python實(shí)現(xiàn)自動(dòng)化拆分Word文檔(按分節(jié)符與分頁(yè)符)的完整教程
在處理大型 Word 文檔時(shí),我們經(jīng)常需要將一個(gè)完整的文檔拆分成多個(gè)獨(dú)立的小文檔,下面我們就來(lái)看看Python如何實(shí)現(xiàn)按分頁(yè)符和分節(jié)符自動(dòng)化拆分 Word 文檔吧2026-04-04
Python機(jī)器學(xué)習(xí)k-近鄰算法(K Nearest Neighbor)實(shí)例詳解
這篇文章主要介紹了Python機(jī)器學(xué)習(xí)k-近鄰算法(K Nearest Neighbor),結(jié)合實(shí)例形式分析了k-近鄰算法的原理、操作步驟、相關(guān)實(shí)現(xiàn)與使用技巧,需要的朋友可以參考下2018-06-06

