Python 为什么子流程可以';无法成功终止旧的正在运行的进程?
我运行一个程序Python 为什么子流程可以';无法成功终止旧的正在运行的进程?,python,subprocess,kill,terminate,Python,Subprocess,Kill,Terminate,我运行一个程序test.py。 由于它经常崩溃,我导入子流程,在它停止时重新启动它。 有时我发现子进程无法成功地重新启动它。 因此,我强制程序每60分钟重新启动一次。 但我发现有时两个test.py进程同时运行。 我的代码有什么问题,如何修复? 我使用Windows7操作系统。 请检查以下代码并提前致谢: import subprocess import time from datetime import datetime p = subprocess.Popen(['python.exe',
test.py
。
由于它经常崩溃,我导入子流程
,在它停止时重新启动它。
有时我发现子进程无法成功地重新启动它。
因此,我强制程序每60分钟重新启动一次。
但我发现有时两个test.py进程同时运行。
我的代码有什么问题,如何修复?
我使用Windows7操作系统。
请检查以下代码并提前致谢:
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)
虽然我完全不同意您的设计,但具体问题是:
except Exception as e:
terminated = True
finally:
p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)
如果抛出了异常
,则将终止
设置为真
,然后立即重新启动子流程。然后,稍后检查:
if terminated:
p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)
此时,终止
为真
,因此它启动一个新的子流程。然而,它已经在finally
块中完成了这项工作
实际上,您应该做的是,在杀戮尝试期间不要麻烦重新启动它:
try:
p.kill()
except Exception:
# We don't care, just means it was already dead
pass
finally:
# Either the process is dead, or we just killed it. Either way, need to restart
terminated = True
然后您的
if terminated
子句将正确地重新启动流程,您将不会有重复的。非常同意您的观点。非常感谢。您提到“在这一点上,terminated是真的,所以它会启动一个新的子进程。”。但是,既然我在'finally'子句中重新启动了它,那么在下面的'try'子句中应该是'terminated==None'吗?您的意思是周期太短,无法让程序再次运行,因此在该点“terminated==True”?您不是在重新启动进行这些调用的脚本,而是在重新启动其子进程,p
。无论如何,第二个try
块与语句的计算无关,如果终止语句,则每次循环时都会检查语句,而loop.dropshell=True
——它会在此处创建不必要的cmd.exe
进程(p.kill()
杀死该进程)。相关: