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()
Walklikeapenguin
  • 127
  • 2
  • 10

1 Answers1

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 :)

0xPrateek
  • 1,158
  • 10
  • 28