守護關鍵進程(如 main.exe),定期檢查是否存活,掛掉則自動重啟。Windows 下用 tasklist 過濾映像名稱,Linux 可改 pgrep/ps。
import threading, time, os, subprocess
def get_process_count(image_name):
"""Windows tasklist 統計進程數"""
cmd = f'tasklist /FI "IMAGENAME eq {image_name}"'
return os.popen(cmd).read().count(image_name)
def watch_func(msg):
print(f"I'm watch_func, {msg}")
if get_process_count('main.exe') == 0:
print("Process dead, restarting...")
subprocess.Popen([r'D:\shuaji\bin\main.exe'])
timer_start() # 重新排程
def timer_start():
t = threading.Timer(120, watch_func, ("is running...",))
t.daemon = True # 主線程退出時自動結束
t.start()
if __name__ == '__main__':
timer_start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Stopped by user")
threading.Timer(interval, func, args):一次性定時器,執行完需手動重新排程(見 watch_func 尾部)。daemon=True:守護線程,主程序退出時自動終止,避免殭屍線程。os.popen(cmd).read():同步執行命令捕獲輸出,簡單但阻塞;高頻場景建議 subprocess.run(..., capture_output=True)。subprocess.Popen([exe]):非阻塞啟動新進程,不等待其結束。
import sys, subprocess, threading, time
def is_alive(name):
if sys.platform.startswith('win'):
cmd = ['tasklist', '/FI', f'IMAGENAME eq {name}']
out = subprocess.run(cmd, capture_output=True, text=True).stdout
return out.count(name) > 0
else:
# Linux/macOS: pgrep -x 精確匹配
return subprocess.run(['pgrep', '-x', name], capture_output=True).returncode == 0
def restart(exe_path):
subprocess.Popen([exe_path], start_new_session=True)
def guardian(exe_path, check_interval=60):
name = os.path.basename(exe_path)
def check():
if not is_alive(name):
print(f"[{time.ctime()}] {name} dead, restarting...")
restart(exe_path)
threading.Timer(check_interval, check).start()
check() # 立即首檢
# 主線程保持
threading.Event().wait()
if __name__ == '__main__':
guardian(r'D:\shuaji\bin\main.exe' if sys.platform.startswith('win') else './main')
threading.Timer + tasklist/pgrep + subprocess.Popen 構成極簡進程守護腳本。理解定時器重排程、守護線程、跨平台進程檢測三要點,可快速構建原型;生產環境請交給專業進程管理器。