【问题标题】:python: run a process with timeout and capture stdout, stderr and exit status [duplicate]python:运行一个超时的进程并捕获stdout、stderr和退出状态[重复]
【发布时间】:2010-12-06 02:16:23
【问题描述】:

可能重复:
subprocess with timeout

在 Python 中执行以下操作的最简单方法是什么:

  • 运行外部进程
  • 在字符串中捕获标准输出、标准错误和退出状态
  • 设置超时。

我想要这样的东西:

import proc

try:
    status, stdout, stderr = proc.run(["ls", "-l"], timeout=10)
except proc.Timeout:
    print "failed"

【问题讨论】:

标签: python process external-process


【解决方案1】:

我讨厌自己做这项工作。只需将其复制到您的 proc.py 模块中即可。

import subprocess
import time
import sys

class Timeout(Exception):
    pass

def run(command, timeout=10):
    proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    poll_seconds = .250
    deadline = time.time()+timeout
    while time.time() < deadline and proc.poll() == None:
        time.sleep(poll_seconds)

    if proc.poll() == None:
        if float(sys.version[:3]) >= 2.6:
            proc.terminate()
        raise Timeout()

    stdout, stderr = proc.communicate()
    return stdout, stderr, proc.returncode

if __name__=="__main__":
    print run(["ls", "-l"])
    print run(["find", "/"], timeout=3) #should timeout

【讨论】:

  • 此版本可能由于管道缓冲区溢出而超时(当 stdout 或 stderr ~64K 时)。
  • 如果命令超时,在超时之前您不会得到任何输出。
  • print run(["ping www.redicecn.com"], timeout=10),脚本抛出Timeout异常,但ping进程仍在运行。
【解决方案2】:

注意在 linux 上使用 coreutils >= 7.0,您可以在命令前添加超时,例如:

timeout 1 sleep 1000

【讨论】:

    猜你喜欢
    • 2014-10-14
    • 2020-06-23
    • 2011-04-07
    • 2021-06-19
    • 2010-12-04
    • 2014-06-26
    • 1970-01-01
    • 2013-09-02
    • 2015-07-04
    相关资源
    最近更新 更多