Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: waiting for external launched process finish

The question already in title - how can one make the python script wait until some process launched with os.system() call is completed ? For example a code like

    for i in range( 0, n ):        os.system( 'someprog.exe %d' % i ) 

This launches the requested process n times simultaneously, which may make my pc to sweat a bit )

Thanks for any advice.

like image 307
Grigor Gevorgyan Avatar asked Jan 21 '12 12:01

Grigor Gevorgyan


People also ask

How do you wait until a function is complete in Python?

This wait()method in Python is a method of os module which generally makes the parent process to synchronize with its child process which means the parent will wait for the child process to complete its execution (i.e wait until the exit of the child process) and later continue with its process execution.

Does subprocess wait for command to finish?

subprocess. run() is synchronous which means that the system will wait till it finishes before moving on to the next command.

Does OS system wait until finish?

Answer #1: os. system() does wait for its process to complete before returning. If you are seeing it not wait, the process you are launching is likely detaching itself to run in the background in which case the subprocess.

What does OS system return in Python?

The os. system() function executes a command, prints any output of the command to the console, and returns the exit code of the command.


2 Answers

Use subprocess instead:

import subprocess for i in xrange(n):   p = subprocess.Popen(('someprog.exe', str(i))   p.wait() 

Read more here: http://docs.python.org/library/subprocess.html

like image 161
Dor Shemer Avatar answered Sep 19 '22 03:09

Dor Shemer


os.system() does wait for its process to complete before returning.

If you are seeing it not wait, the process you are launching is likely detaching itself to run in the background in which case the subprocess.Popen + wait example Dor gave won't help.

Side note: If all you want is subprocess.Popen + wait use subprocess.call:

import subprocess subprocess.call(('someprog.exe', str(i))) 

That is really no different than os.system() other than explicitly passing the command and arguments in instead of handing it over as a single string.

like image 39
gps Avatar answered Sep 18 '22 03:09

gps