在超时使用模块“子进程”

在超时使用模块“子进程”

下面是运行返回它的任意命令的Python代码stdout数据,或对非零退出代码引发异常:

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

communicate用于等待进程退出:

stdoutdata, stderrdata = proc.communicate()

这个subprocess因此,模块不支持超时-停止运行超过X秒的进程的能力-因此,communicate可能要花很长时间才能跑。

什么是最简单在运行在Windows和Linux上的Python程序中实现超时的方法?


弑天下
浏览 637回答 3
3回答

慕尼黑的夜晚无繁华

在Python3.3+中:from subprocess import STDOUT, check_output output = check_output(cmd, stderr=STDOUT, timeout=seconds)output是一个字节字符串,它包含命令的合并的stdout、stderr数据。此代码引发CalledProcessError问题文本中指定的非零退出状态与proc.communicate()方法。我把shell=True因为它经常被不必要地使用。如果cmd确实需要它。如果你加上shell=True即,如果儿童进程产生自己的后代;check_output()可以比超时指示的时间晚得多返回,请参见子进程超时故障.超时功能可在Python2.x上通过subprocess323.2+子进程模块的后端端口。

ITMISS

可以使用螺纹班级:import shlexfrom subprocess import Popen, PIPEfrom threading import Timerdef run(cmd, timeout_sec):     proc = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE)     timer = Timer(timeout_sec, proc.kill)     try:         timer.start()         stdout, stderr = proc.communicate()     finally:         timer.cancel()# Examples: both take 1 secondrun("sleep 1", 5)  # process ends normally at 1 secondrun("sleep 5", 1)           # timeout happens at 1 second
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python