shavenwarthog

multiple procs w/o threading/multiprocessing

Jul 11th, 2014
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.80 KB | None | 0 0
  1. '''
  2. pwait2.py -- multiple subprocesses without threading/multiprocessing
  3. '''
  4.  
  5. import random, time
  6. from subprocess import Popen
  7.  
  8.  
  9. def work_diligently():
  10.     cmd = ["/bin/sleep", str(random.randrange(2,4))]
  11.     proc = Popen(cmd)
  12.     print '\t{}\t{}'.format(proc.pid, cmd) # pylint: disable=E1101
  13.     return proc
  14.  
  15.  
  16. def spawn(num):
  17.     return [ work_diligently() for _ in xrange(num) ]
  18.  
  19.  
  20. # keep a 'pool' of NUM_PROCS Popen's running at one time
  21. NUM_PROCS = 3
  22. procs = spawn(NUM_PROCS)
  23. while True:
  24.     print time.ctime(), 'scan'
  25.     procs = [
  26.         proc for proc in procs
  27.         if proc.poll() is None
  28.     ]
  29.     num_exited = NUM_PROCS - len(procs)
  30.     if num_exited:
  31.         print 'Uhoh! Restarting {} procs'.format(num_exited)
  32.         procs.extend( spawn(num_exited) )
  33.     time.sleep(1)
Advertisement
Add Comment
Please, Sign In to add comment