小编典典

Python-使用带超时的模块“subprocess”

python

这是运行任意命令以返回其stdout数据或在非零退出代码上引发异常的Python代码:

proc = subprocess.Popen(
    cmd,
    stderr=subprocess.STDOUT,  # Merge stdout and stderr
    stdout=subprocess.PIPE,
    shell=True)

communicate 用于等待进程退出:

stdoutdata, stderrdata = proc.communicate()

subprocess模块不支持超时-杀死运行时间超过X秒的进程的能力-因此communicate可能需要永远运行。

在打算在WindowsLinux上运行的Python程序中实现超时的最简单方法是什么?


阅读 1522

收藏
2020-02-10

共1个答案

小编典典

在Python 3.3+中:

from subprocess import STDOUT, check_output

output = check_output(cmd, stderr=STDOUT, timeout=seconds)

output 是一个字节字符串,其中包含命令的合并标准输出,标准错误数据。

check_output加注CalledProcessError在不同问题的文本中指定的非零退出状态proc.communicate()的方法。

我已删除,shell=True因为它经常被不必要地使用。如果cmd确实需要,可以随时将其添加回去。如果添加,shell=True即子进程是否产生了自己的后代;check_output()可以比超时指示晚得多返回,请参阅子进程超时失败。

超时功能可在Python 2.x上通过subprocess323.2+子进程模块的反向端口使用。

2020-02-10