【发布时间】:2015-04-14 01:10:48
【问题描述】:
我运行一个程序test.py。
由于它经常崩溃,我导入subprocess 以在它停止时重新启动它。
有时我发现子进程无法成功重新启动它。
因此,我强制程序每 60 分钟重新启动一次。
但我发现有时会同时运行两个 test.py 处理。
我的代码有什么问题以及如何修复它?
我使用 Windows 7 操作系统。
请检查以下代码并提前感谢:
import subprocess
import time
from datetime import datetime
p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)
minutes = 1
total_time = 0
while True:
now = datetime.now()
#periodly restart
total_time += 1
if total_time % 100 == 0:
try:
p.kill()
except Exception as e:
terminated = True
finally:
p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)
#check and restart if it stops
try:
terminated = p.poll()
except Exception as e:
terminated = True
if terminated:
p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)
time.sleep(minutes * 60)
【问题讨论】:
-
drop
shell=True-- 它在这里创建了不必要的cmd.exe进程(p.kill()杀死了那个进程)。
标签: python subprocess kill terminate