gpt4 book ai didi

python - 了解subprocess.TimeoutExpired,想在超时发生后杀死一个子进程

转载 作者:太空狗 更新时间:2023-10-30 01:21:56 33 4
gpt4 key购买 nike

谁能帮我理解 subprocess 模块中超时参数的工作原理,以及如何正确使用 subprocess.TimeoutExpired 异常?

我的用例是我有一个主运行程序,它运行一个子进程作为其重复例程的一部分。众所周知,子进程有时会挂起。我想防止这个挂起阻碍一切。

我在想我可以使用超时参数让 child 只跑这么长时间。但是,在我下面的示例程序中,行为并不是我所期望的。当运行 parent.py 时,它确实会启动 child.py,我可以看到 child.py 的输出正在计数。 4 秒后,parent.py 确实收到 subprocess.TimeoutExpired 异常,但是 child.py 的输出不断出现。这让我相信 child.py 进程实际上并没有被杀死。文档似乎暗示它将被杀死:

The timeout argument is passed to Popen.wait(). If the timeout expires, the child process will be killed and then waited for again. The TimeoutExpired exception will be re-raised after the child process has terminated.

那么我该如何解决这个问题呢?当我收到超时异常时,我是否需要以某种方式自行终止我的子进程?

感谢您的帮助。

父类.py

#!/usr/bin/env python3

import os
import sys
import subprocess

p = subprocess.Popen("/path/to/python3 /path/to/child.py", shell=True)
try:
p.wait(timeout=4)
except subprocess.TimeoutExpired:
print("we got a timeout. exiting")
sys.exit(1)

child .py

#!/usr/bin/env python3

import os
import sys
import time

for i in range(200):
print("i is {}".format(i))
time.sleep(1)

最佳答案

看来您确实需要添加一个调用:

p.terminate()

在您的父进程中的 sys.exit 之前,根据当前 documentation您引用的位仅适用于 subprocess.call,这不是您在此处使用的内容。

关于python - 了解subprocess.TimeoutExpired,想在超时发生后杀死一个子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28131659/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com