I would like to "sow" a number of processes and then "harvest" them when they're done. Using the subprocess
module I have the following code in subrun.py
:
import time, subprocess, shlex, os
ok = subprocess.Popen(shlex.split("python ok.py"),
stdout=subprocess.PIPE,
stderr=open(os.devnull, 'w'))
nok = subprocess.Popen(shlex.split("python nok.py"),
stdout=subprocess.PIPE,
stderr=open(os.devnull, 'w'))
procs = {'ok': ok, 'nok': nok}
while procs:
running = procs.keys()
print "running:", running
for k in running:
proc = procs[k]
rc = proc.poll()
if rc is None:
pass # still running
else:
del procs[k]
print proc.stdout.read()
time.sleep(.4)
ok.py
is as follows
import sys
print "OK"
sys.exit(0)
and nok.py
is
import sys
print "NOK" * 5000
sys.exit(0)
The output is
(dev) C:\work\dev\test>python subrun.py
running: ['ok', 'nok']
running: ['ok', 'nok']
OK
running: ['nok']
running: ['nok']
running: ['nok']
running: ['nok']
running: ['nok']
running: ['nok']
running: ['nok']
Traceback (most recent call last):
File "subrun.py", line 27, in <module>
time.sleep(.4)
ie. Popen.poll()
returns None
when the subprocess has blocked on IO.
I could probably start a thread per process, which would call .communicate()[0]
, but that seems like a lot of extra book keeping...
Is there any way to get this to work?