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

发布于 2021-02-02 23:22:38

这是运行任意命令以返回其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程序中实现超时的最简单方法是什么?

关注者
0
被浏览
109
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    在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+子进程模块的反向端口使用。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看