303
303

Reputation: 1108

How to get the output of a Python subprocess and terminate it afterwards?

I want to get the output of my subprocess. As it runs indefinitely I want to terminate it when certain conditions are fulfilled.

When I start the subprocess by using check_output, I get the output but no handle to terminate the process:

output = subprocess.check_output(cmd, shell=True)

When I start the subprocess by using Popen or run, I get a handle to terminate the process, but no output.

p = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)

How can I get both?

Upvotes: 1

Views: 2704

Answers (3)

Ghassen
Ghassen

Reputation: 794

try this :

import subprocess
p = subprocess.Popen("ls -a", shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print((p.stdout.read()))
if p.stdout.read() or p.stderr.read():
    p.terminate()

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140307

when can you know that you've got the full process output? when the process terminates. So no need to terminate it manually. Just wait for it to end, and using check_output is the way.

Now if you want to wait for a given pattern to appear, then terminate, now that's something else. Just read line by line and if some pattern matches, break the loop and end the process

p = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid) # add stderr=subprocess.PIPE) to merge output & error
for line in p.stdout:
   if b"some string" in line:  # output is binary
       break
p.kill() # or p.terminate()

Upvotes: 1

AKX
AKX

Reputation: 169398

You'll need to tell Popen you want to read the standard output, but it can be a little tricky.

p = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid, stdout=subprocess.PIPE)
while True:
    chunk = p.stdout.read(1024)  # this will hang forever if there's nothing to read
p.terminate()

Upvotes: 0

Related Questions