为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

弑天下 2019-06-09 16:24:19
在超时使用模块“子进程”下面是运行返回它的任意命令的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程序中实现超时的方法?
查看完整描述

3 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

在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+子进程模块的后端端口。


查看完整回答
反对 回复 2019-06-09
?
ITMISS

TA贡献1871条经验 获得超8个赞

可以使用螺纹班级:

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


查看完整回答
反对 回复 2019-06-09
  • 3 回答
  • 0 关注
  • 636 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信