【问题标题】:Capture output from subprocess with a timeout set使用超时设置从子进程捕获输出
【发布时间】:2021-02-14 19:29:48
【问题描述】:

我正在使用subprocess.run 运行命令并捕获输出,如下所示:

proc = subprocess.run([commandAndFlags], capture_output=True)

if proc.stdout:
    print('stdout:', str(proc.stdout))
if proc.stderr:
    print('stderr:', str(proc.stderr))

我想添加一个超时,但仍会在超时前捕获发送到 stdout/stderr 的任何输出。

但是,如果我简单地添加超时并将其包装在 try/except 中,我将无法捕获子进程输出。

try:
    proc = subprocess.run([commandAndFlags], capture_output=True, timeout=2000)
except subprocess.TimeoutExpired:
    print('Timeout!!')

if proc.stdout:
    print('stdout:', str(proc.stdout))
if proc.stderr:
    print('stderr:', str(proc.stderr))

现在proc 在我尝试打印 stdout/stderr 时未定义。

如何设置超时但仍捕获超时前打印的任何输出?

【问题讨论】:

    标签: python python-3.x subprocess


    【解决方案1】:

    您仍然可以使用原始代码中的capture_output 属性,当抛出TimeoutExpired 异常时,您可以从那里收集stdoutstderr。例如:

    try:
        proc = subprocess.run([commandAndFlags], capture_output=True, text=True, timeout=2000)
        outs = proc.stdout
        errs = proc.stderr
    except subprocess.TimeoutExpired as timeErr:
        outs = timeErr.stdout
        errs = timeErr.stderr
    
    

    【讨论】:

      【解决方案2】:

      最终我发现你可以将文件直接传递给subprocess.run

      outfile = 'outfile.txt'
      errfile = 'errfile.txt'
      try:
        proc = subprocess.run([commandAndFlags], timeout=2000
                              stdout=open(outfile, 'w'), stderr=open(errfile, 'w'))
      except subprocess.TimeoutExpired:
          print('Timeout!!')
      
      # check if outfile/errfile files exist and print contents
      

      无论子进程是否因超时而停止,子进程都会将 stdout/stderr 直接保存到可以稍后查看的文件中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-20
        • 2012-08-24
        • 2010-12-09
        • 2016-07-21
        • 1970-01-01
        • 2011-02-01
        • 2013-01-22
        • 2019-10-01
        相关资源
        最近更新 更多