【问题标题】:Why subprocess can't successfully kill the old running process?为什么子进程无法成功杀死旧的正在运行的进程?
【发布时间】: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)

【问题讨论】:

标签: python subprocess kill terminate


【解决方案1】:

虽然我完全不同意你的设计,但具体问题在这里:

except Exception as e:
        terminated = True
finally:
        p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)

在抛出Exception 的情况下,您将terminated 设置为true,然后立即重新启动子进程。然后,稍后,您检查:

if terminated:
    p = subprocess.Popen(['python.exe', r'D:\test.py'], shell=True)

此时,terminatedtrue,所以它启动了一个新的子进程。但是,它已经在 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 子句将正确地重新启动该过程并且您不会有重复。

【讨论】:

  • 完全同意你的看法。非常感谢。
  • 您提到“此时,终止为真,因此它启动了一个新的子进程。”。但是由于我在“finally”子句中重新启动它,是否应该在下面的“try”子句中使用“terminated==None”?你的意思是这个时间太短了,不能让程序再次运行,以至于到那时'终止==True'?
  • 您并没有重新启动进行这些调用的脚本,而是重新启动了它的子进程p。无论如何,第二个try 块与if terminated 语句的评估无关,while 循环的每次迭代都会检查该语句。
猜你喜欢
  • 1970-01-01
  • 2018-10-14
  • 2022-11-10
  • 2019-02-18
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多