32

How can one make the python script wait until some process launched with os.system() call is completed? For example, code like

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

This launches the requested process n times simultaneously.

2 Answers 2

30

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.

1
  • 2
    What to do if the process is running in the background? Is there no way to make python wait until next loop? Sep 29, 2021 at 16:30
28

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

1
  • 1. this leaks the pipe handle, p must be close()d. Use with subprocess.Popen(('command', str(i)) as p: p.wait() instead. 2. If you don't read the pipe, and the process outputs a lot to stdout, the pipe clogs, and you get deadlocked. Mar 16 at 22:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.