超时子进程:TimeoutExpired Exception 后怎么办?

subprocess with timeout: What to do after TimeoutExpired Exception?

如果我遵循 python 文档的建议,subprocess timeout=SECONDS 对我不起作用:

# copy+pasteable snippet :-)
import subprocess32 as subprocess
import datetime

now=datetime.datetime.now()
pipe=subprocess.Popen('sleep 5', shell=True, stdout=subprocess.PIPE)
try:
    pipe.communicate(timeout=1)
except subprocess.TimeoutExpired, exc:
    time_delta=datetime.datetime.now()-now
    print(time_delta)
    assert time_delta<datetime.timedelta(seconds=3), time_delta
    pipe.kill()
    outs, errs = pipe.communicate()
    time_delta=datetime.datetime.now()-now
    print(time_delta)
    assert time_delta<datetime.timedelta(seconds=3), time_delta
    print('OK')

文档建议在 TimeoutExpired 后使用 pipe.kill() 和 pipe.communicate():https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate

它对我不起作用。第二个communicate()不return很快。

异常:

0:00:01.001234
0:00:05.002919
Traceback (most recent call last):
  File "/home/foo/src/test_timeout.py", line 16, in <module>
    assert time_delta<datetime.timedelta(seconds=3), time_delta
AssertionError: 0:00:05.002919

如果我使用 ['sleep', '5'] 而不是 shell=True,那么就可以了。 如果我不提供 stdout=subprocess.PIPE,那么它也可以。

我猜 shell 对 pipe.kill() 没有反应。

解决这个问题的最佳方法是什么?

一般模式:捕获TimeoutExpired,杀死启动的进程,再次调用.communicate()是正确的。

问题是您代码中的 pipe.kill() 仅杀死 shell,而其后代进程(例如 /bin/sleep 可能会继续 运行。参见 How to terminate a python subprocess launched with shell=True

注意:如果需要;没有必要等待孙进程。参见