繁体   English   中英

在引发异常时捕获subprocess.Popen的stdout

[英]capture stdout of subprocess.Popen when there is exception raised

当引发异常时,如何从subprocess.Popen CMD调用中捕获stdout / stderr?

代码段:

p_cmd = subprocess.Popen(CMD, bufsize=0, shell=True, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(cmd_stdo, cmd_stde) = p_cmd.communicate(timeout=60)

如果CMD timeout超过60 secs ,如何在cmd_stdocmd_stde获得CMD stdout输出?

我尝试尝试获取它try, exception块为NULL。 而且,我非常确定运行CMD时会有输出。

如果超时,则永远不会将变量cmd_stdocmd_stde分配给它,因为在分配之前会发生异常。

为了确保即使在异常情况下也可以捕获stdoutstderr ,我将捕获到(临时)文件,然后将它们读入变量。

import subprocess
from tempfile import TemporaryFile as Tmp

CMD = [ 'echo "before sleep" ; sleep 7 ; echo "after sleep"' ]

with Tmp() as out, Tmp() as err:
    p_cmd = subprocess.Popen(CMD, bufsize=0, shell=True, stdin=None, stdout=out, stderr=err)
    timed_out = False
    try:
        p_cmd.wait(timeout=5)
    except subprocess.TimeoutExpired:
        timed_out = True
    out.seek(0)
    err.seek(0)
    str_out = out.read()
    str_err = err.read()

print('Has timed out:', timed_out)
print('Stdout:', str_out)
print('Stderr:', str_err)

(尝试此操作时,请在代码中使用睡眠和超时​​时间进行操作,以使超时发生与否)

由于我没有足够的声誉,因此我必须以这种方式要求澄清。

您要在Windows或Linux上运行它吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM