Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Exception When Running Python Script From Another Python Script

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()
like image 381
Walklikeapenguin Avatar asked Jun 11 '19 17:06

Walklikeapenguin


People also ask

Is try catch Pythonic?

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.

How do you deal with exception handling in Python effectively?

To handle exceptions in Python, you first need to wrap your code in a try... except block. Occasionally, you might need to include a finally statement to handle further actions, depending on your needs. As mentioned earlier, you can also use finally in an exception block.

How do you catch a specific exception in Python?

Catching Specific Exceptions in PythonA try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs. We can use a tuple of values to specify multiple exceptions in an except clause.

How to catch and handle exceptions in Python?

Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause. Example: Let us try to access the array element whose index is out of bound and handle the corresponding exception.

What happens if no exceptions are raised in Python?

If no exceptions are raised, the code will run as expected. Now that you know what exceptions are and why you should we handle them, we will start diving into the built-in tools that the Python languages offers for this purpose. First, we have the most basic statement: try ... except.

How to run one Python script from another?

Steps to Run One Python Script From Another Step 1: Place the Python Scripts in the Same Folder To start, you’ll need to place your Python scripts in the same... Step 2: Add the Syntax Next, add the syntax to each of your scripts. For instance, I added the following syntax under... Step 3: Run One ...

What is the difference between try and except statement in Python?

The second print statement tries to access the fourth element of the list which is not there and this throws an exception. This exception is then caught by the except statement. A try statement can have more than one except clause, to specify handlers for different exceptions.


Video Answer


1 Answers

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

like image 82
0xPrateek Avatar answered Oct 17 '22 17:10

0xPrateek