Question

I have three python scripts that I am calling from a wrapper script using

subprocess.Popen(['python', script, '-i', In]).wait()

Where script is the name of the script being called and In is the argument it takes. Unfortunately now, if there is an error in one of the scripts, the wrapper prints out the error, but still goes on to call the next script.

Is there any way to make it terminate once an error is thrown by one of the subprocesses?

Thank you

Was it helpful?

Solution

The wait() method will set the returncode attribute of the Popen object when the child process exits. You should check that value to determine if the script should continue:

p = subprocess.Popen(['python', script, '-i', In])
p.wait()
if p.returncode != 0:
    sys.exit(p.returncode)

Edit: You could also consider using subprocess.call(), which will return the returncode attribute directly. That way you wouldn't need to create a Popen object. If you prefer the try/except pattern, you can use subprocess.check_call(), which will throw a CalledProcessError if the child process exits with a non-zero status.

OTHER TIPS

try:
    command
except Exception as e:
    print str(e)
    return

if command fails, the except block will run, printing the error and ending the script.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top