Wei-Ting Liao
Wei-Ting Liao

Reputation: 115

Terminate all subprocesses if any one of subprocess has error

I am trying to run two subprocesses simultaneously. My current program looks like if one of subprocess has error and terminated, it cannot relaunch again after 1 min. It needs to wait another subprocess failed also and both of them start together. I found some posts about how to kill specific subprogress, but how can I (1) if one subprocess has error, all subprocesses will be terminated and relaunch again after 1 min? Or (2) the subprocess with error can relaunch again after 1 min without waiting another running subprocess? Will it work if I change

proc.wait()

to

proc.kill()

in the following code? Is there any better way to deal with it?

import sys
import subprocess
import os               
import time

def executeSomething():
    # This setting is very important to avoid errors 
    os.environ['PYTHONIOENCODING'] = 'utf-8'    

    procs = []
    files = ["TwitterDownloader_1.py","TwitterDownloader_2.py"]   
    try:
        for i in files:
            proc = subprocess.Popen([sys.executable,i])
            procs.append(proc)

        for proc in procs:
            proc.wait() 
    except AttributeError:
        print 'Attribute Error found and skiped' 
    time.sleep(61)

while True:
    executeSomething()       

Upvotes: 2

Views: 1172

Answers (1)

Barry Rogerson
Barry Rogerson

Reputation: 598

How about running a loop to check the status of the processes?

Something like this:

for proc in procs:
    if proc.poll() is not None:  # it has terminated
        # check returncode and handle success / failure

Upvotes: 1

Related Questions