即使在超时的情况下,Subprocess.Popen也会获得输出

时间:2017-06-02 18:34:38

标签: python subprocess python-3.5

我使用subprocess.PopenPopen.communicate来运行超时的进程,类似于给出的建议是这个问题:

Subprocess timeout failure

因此我使用以下代码:

with Popen(["strace","/usr/bin/wireshark"], stdout=subprocess.PIPE,stderr=subprocess.PIPE, preexec_fn=os.setsid) as process:
    try:
        output  = process.communicate(timeout=2)[0]
        print("Output try", output)
    except TimeoutExpired:
        os.killpg(process.pid, signal.SIGINT)  # send signal to the process group
        output = process.communicate()[0]
        print("Output except",output)
return output

我得到以下输出:

Output except b''

b''作为返回值。

即使引发TimeoutExpired异常,如何获取进程的输出(输出直到被杀死)?

1 个答案:

答案 0 :(得分:0)

Popen个对象有一个kill方法,为什么不使用它呢?一个进程被杀死后,你可以只读它的标准输出。这有用吗?

with Popen(["strace","/usr/bin/wireshark"], stdout=subprocess.PIPE,stderr=subprocess.PIPE, preexec_fn=os.setsid) as process:
    try:
        output  = process.communicate(timeout=2)[0]
        print("Output try", output)
    except TimeoutExpired:
        process.kill()
        output = process.stdout.read().decode()
        print("Output except",output)
return output