Sunday, 16 October 2022

Subprocess.Popen get output even in case of timeout

I am using subprocess.Popenand Popen.communicate to run a process with a timeout, similar to the suggestion given is this question:

Subprocess timeout failure

Thus I am using the following code:

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

And I get the following output:

Output except b''

and b'' as a return value.

How can I get the output of the process (the output until it is killed) even though the TimeoutExpired exception is raised?



from Subprocess.Popen get output even in case of timeout

No comments:

Post a Comment