1

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?

Sleik
  • 271
  • 4
  • 10

1 Answers1

0

Popen objects have a kill method, why not use that instead? After a process is killed, you can just read it's stdout. Does this work?

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
calico_
  • 1,111
  • 12
  • 22
  • Unfortunately not, since this does not kill the process group - thus the python script is blocked. If I kill the process manually, the output variable remains empty. – Sleik Jun 03 '17 at 10:54