Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

So I noticed subprocess.call while it waits for the command to finish before proceeding with the python script, I have no way of getting the stdout, except with subprocess.Popen. Are there any alternative function calls that would wait until it finishes? (I also tried Popen.wait)

NOTE: I'm trying to avoid os.system call

result = subprocess.Popen([commands...,                         self.tmpfile.path()], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = result.communicate() print out+"HIHIHI" 

my output:

HIHIHI 

NOTE: I am trying to run wine with this.

like image 434
Stupid.Fat.Cat Avatar asked Nov 15 '12 13:11

Stupid.Fat.Cat


People also ask

How do you wait for a subprocess to finish?

A Popen object has a . wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status). If you use this method, you'll prevent that the process zombies are lying around for too long. (Alternatively, you can use subprocess.

Does subprocess run wait for finish?

subprocess. run() is synchronous which means that the system will wait till it finishes before moving on to the next command. subprocess. Popen() does the same thing but it is asynchronous (the system will not wait for it to finish).

How do you store output of subprocess call?

Popen(args,stdout = subprocess. PIPE). stdout ber = raw_input("search complete, display results?") print output #... and on to the selection process ... You now have the output of the command stored in the variable "output".

What is the difference between subprocess run and subprocess Popen?

The main difference is that subprocess. run() executes a command and waits for it to finish, while with subprocess. Popen you can continue doing your stuff while the process finishes and then just repeatedly call Popen. communicate() yourself to pass and receive data to your process.


2 Answers

I am using the following construct, although you might want to avoid shell=True. This gives you the output and error message for any command, and the error code as well:

process = subprocess.Popen(cmd, shell=True,                            stdout=subprocess.PIPE,                             stderr=subprocess.PIPE)  # wait for the process to terminate out, err = process.communicate() errcode = process.returncode 
like image 81
Alex Avatar answered Sep 23 '22 18:09

Alex


subprocess.check_output(...) 

calls the process, raises if its error code is nonzero, and otherwise returns its stdout. It's just a quick shorthand so you don't have to worry about PIPEs and things.

like image 40
Katriel Avatar answered Sep 22 '22 18:09

Katriel