2

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.

5
  • 1
    Check the exit status after running your script (in bash that will be $?) Commented May 22, 2017 at 10:15
  • Is the exception caught (and handled) in Python, or does the Python script exit when the exception is raised? Commented May 22, 2017 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. Commented May 22, 2017 at 10:33
  • use return to exit from main shell script Commented May 22, 2017 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 Commented May 22, 2017 at 10:40

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.