I use a lot of os.system calls to create background processes inside a for loop. How can I wait for all the background processes to end ?
os.wait tells me there are no child process.
ps: I am using Solaris
here is my code :
#!/usr/bin/python
import subprocess
import os
pids = []
NB_PROC=30
for i in xrange(NB_PROC):
p = subprocess.Popen("(time wget http://site.com/test.php 2>&1 | grep real )&", shell=True)
pids.insert(0,p)
p = subprocess.Popen("(time wget http://site.com/test.php 2>&1 | grep real )&", shell=True)
pids.insert(0,p)
for i in xrange(NB_PROC*2):
pids[i].wait()
os.system("rm test.php*")
Normally,
os.system()returns when the child process is finished. So there is indeed nothing foros.wait()to do. It is equivalent tosubprocess.call().Use
subprocess.Popen()to create background processes, and then thewait()orpoll()methods of thePopenobjects to wait for them to quit.By default, Popen does not spawn a shell but executes the program directly. This saves resources and prevents possible shell injection attacks.
According to the documentation for
os.system():If you want to do multiple jobs in parallel, consider using
multiprocessing, especially thePoolobject. It takes care of a lot of the details of farming work out over several processes.Edit: Timing the execution of a program;