If you simply use subprocess.Popen
, you'll be fine - here's how:
import subprocess
def spawn_some_children():
subprocess.Popen(["sleep", "3"])
subprocess.Popen(["sleep", "3"])
subprocess.Popen(["sleep", "3"])
def do_some_stuff():
spawn_some_children()
# do some stuff
print "children went out to play, now I can do my job..."
# do more stuff
if __name__ == '__main__':
do_some_stuff()
You can use .poll()
on the object returned by Popen to check whether it finished (without waiting). If it returns None
, the child is still running.
Make sure you don't keep references to the Popen objects - if you do, they will not be garbage collected, so you end up with zombies. Here's an example:
import subprocess
def spawn_some_children():
children = []
children.append(subprocess.Popen(["sleep", "3"]))
children.append(subprocess.Popen(["sleep", "3"]))
children.append(subprocess.Popen(["sleep", "3"]))
return children
def do_some_stuff():
children = spawn_some_children()
# do some stuff
print "children went out to play, now I can do my job..."
# do more stuff
# if children finish while we are in this function,
# they will become zombies - because we keep a reference to them
In the above example, if you want to get rid of the zombies, you can either .wait()
on each of the children or .poll()
until the result is not None
.
Either way is fine - either not keeping references, or using .wait()
or .poll()
.