I want to
- call shell commands (for example 'sleep' below) in parallel,
- report on their individual starts and completions and
- be able to kill them with 'kill -9 parent_process_pid'.
There is already a lot written on these kinds of things already but I feel like I haven't quite found the elegant pythonic solution I'm looking for. I'm also trying to keep things relatively readable (and short) for someone completely unfamiliar with python.
My approach so far (see code below) has been:
- put subprocess.call(unix_command) in a wrapper function that reports the start and completion of the command.
- call the wrapper function with multiprocess.Process.
- track the appropriate pids, store them globally, and kill them in the signal_handler.
I was trying to avoid a solution that periodically polled the processes but I'm not sure why.
Is there a better approach?
import subprocess,multiprocessing,signal
import sys,os,time
def sigterm_handler(signal, frame):
print 'You killed me!'
for p in pids:
os.kill(p,9)
sys.exit(0)
def sigint_handler(signal, frame):
print 'You pressed Ctrl+C!'
sys.exit(0)
signal.signal(signal.SIGINT, sigint_handler)
signal.signal(signal.SIGTERM, sigterm_handler)
def f_wrapper(d):
print str(d) + " start"
p=subprocess.call(["sleep","100"])
pids.append(p.pid)
print str(d) + " done"
print "Starting to run things."
pids=[]
for i in range(5):
p=multiprocessing.Process(target=f_wrapper,args=(i,))
p.daemon=True
p.start()
print "Got things running ..."
while pids:
print "Still working ..."
time.sleep(1)