6

I am running a python script from another python script and I am wondering how I can catch exceptions from the parent python script.

My parent python script calls another python script n amount of times. Eventually that called script will exit with a 'ValueError' exception. I'm wondering if there is a way for my parent python script to notice this and then stop executing.

Here is the base code as-is:

import os

os.system('python other_script.py')

I have tried things such as this to no avail:

import os

try:
   os.system('python other_script.py')
except ValueError:
   print("Caught ValueError!")
   exit()

and

import os

try:
   os.system('python other_script.py')
except:
   print("Caught Generic Exception!")
   exit()
1
  • 1
    Exceptions don't cross process boundaries.
    – chepner
    Commented Jun 11, 2019 at 18:08

1 Answer 1

7

The os.system() always returns an integer result code. And,

When it returns 0, the command ran successfully; when it returns a nonzero value, that indicates an error.

For checking that you can simply add a condition,

import os

result = os.system('python other_script.py')
if 0 == result:
    print(" Command executed successfully")
else:
    print(" Command didn't executed successfully")

But, I recommend you to use subprocess module insted of os.system(). It is a bit complicated than os.system() but it is way more flexible than os.system().

With os.system() the output is sent to the terminal, but with subprocess, you can collect the output so you can search it for error messages or whatever. Or you can just discard the output.

The same program can be done using subprocess as well;

# Importing subprocess 
import subprocess

# Your command 
cmd = "python other_script.py"

# Starting process
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE.PIPE)

# Getting the output and errors of the program
stdout, stderr = process.communicate()

# Printing the errors 
print(stderr)

Hope this helps :)

3
  • Combining that with "raise SystemExit()" in the script my parent script runs worked perfectly. Thank you!! Commented Jun 11, 2019 at 18:19
  • That's Great..!
    – 0xPrateek
    Commented Jun 11, 2019 at 18:55
  • 1
    Couldn't upvote at the time because I didn't have the minimum required rep. Just did though, thanks again Commented Jun 30, 2019 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.