我想在通常 24/7 运行的 Windows 机器上每 8 小时在后台运行一个 python 脚本
B
。另外,我还有另一个脚本A
,它是手动执行的,并使用后台脚本提供的数据(它查询大型数据库并提取相关数据,以便主脚本无需长时间等待) .
问题是:如何确保
B
在启动 A
时正在运行?
我的想法是在启动
A
时以某种方式检查 B
是否已经存在,如果不存在则通过 multiprocessing.Process
启动它。但我如何识别这个过程呢?
我唯一想到的就是将进程ID保存到磁盘文件中的某个位置,然后每次检查是否存在具有该ID的进程 - 但据我所知,这个ID不一定引用my进程,以防崩溃与此同时,Windows 向另一个进程提供了相同的 id。
使用基于文件的锁**。它简单、强大,并且不需要外部工具。
import os
import time
LOCK_FILE = 'script_b.lock'
def is_running():
"""Check if the lock file exists."""
return os.path.exists(LOCK_FILE)
def create_lock_file():
"""Create the lock file and write the current process ID."""
with open(LOCK_FILE, 'w') as f:
f.write(str(os.getpid()))
def remove_lock_file():
"""Remove the lock file."""
if os.path.exists(LOCK_FILE):
os.remove(LOCK_FILE)
try:
if is_running():
print("Script B is already running.")
exit(0) # Exit if already running
create_lock_file()
print("Script B is running in the background...")
# Simulate continuous work (replace this with your actual logic)
while True:
time.sleep(1)
finally:
remove_lock_file()
import os
import psutil
import subprocess
LOCK_FILE = 'script_b.lock'
def get_running_pid():
"""Get the PID from the lock file if it exists."""
if os.path.exists(LOCK_FILE):
with open(LOCK_FILE, 'r') as f:
return int(f.read().strip())
return None
def is_process_running(pid):
"""Check if a process with the given PID is still running."""
try:
p = psutil.Process(pid)
return p.is_running()
except (psutil.NoSuchProcess, ValueError):
return False
def start_script_b():
"""Start Script B as a detached process."""
print("Starting Script B...")
subprocess.Popen(['python', 'script_b.py'], creationflags=subprocess.DETACHED_PROCESS)
pid = get_running_pid()
if pid and is_process_running(pid):
print(f"Script B is running with PID {pid}.")
else:
print("Script B is not running. Starting it now.")
start_script_b()
script_b.lock
)。如果锁定文件存在,则假定它已经在运行。psutil
库验证进程是否处于活动状态。subprocess.Popen
启动它。psutil
库 (pip install psutil
)。此解决方案保持轻量级、仅限 Python 并且易于管理!