python - os.fork exit the script if the child fails to run command -


i novice in python trying use multi-process fork. wanted run command on few hosts. able below code want stop execution if of child fails run command or command fails.

def runcommand(host,comp):     if os.system("ssh "+host+" 'somecommand'") != 0:             print "somecommand failed on "+host+" "+comp             sys.exit(-1)  def runmulti():     children = []     comp,host in conhosts.iteritems():             pid = os.fork()             if pid:                     children.append(pid)             else:                     sleep(5)                     runcommand(host,comp)                     os._exit(0)      i, child in enumerate(children):             os.waitpid(child, 0) 

os.fork() returns 0 in child process. can do:

if not os.fork():     # know we're child process     execute_the_work()     if failed:         sys.exit() 

sys.exit() pythonic way exit python program. don't forget import sys.

since seem beginner, replace failed condition judge if task failed.


Comments