I Have a shell script which in turn runs a python script, I have to exit from the main shell script when an exception is caught in python. Can anyone suggest a way on how to achieve it.
Asked
Active
Viewed 2,421 times
2
-
1Check the exit status after running your script (in `bash` that will be `$?`) – donkopotamus May 22 '17 at 10:15
-
Is the exception *caught* (and handled) in Python, or does the Python script exit when the exception is raised? – unutbu May 22 '17 at 10:30
-
python script is exited and the control returns to shell, I want the shell script to be terminated at that point of time. – Deepak May 22 '17 at 10:33
-
use **return** to exit from main shell script – Maninder Singh May 22 '17 at 10:38
-
Or `set -e` in the bash script, to immediately terminate if any of the commands it runs returns a non-zero exit status. It's a good safety tip for bash scripts – Simon Fraser May 22 '17 at 10:40
1 Answers
2
In Python you can set the return value using sys.exit()
. Typically when execution completed successfully you return 0, and if not then some non-zero number.
So something like this in your Python will work:
import sys
try:
....
except:
sys.exit(1)
And then, as others have said, you need to make sure your bash script catches the error by either checking the return value explicitly (using e.g. $?
) or using set -e
.

Duncan WP
- 830
- 5
- 19