[Tutor] Error Handling in python

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Thu Jul 24 14:01:40 CEST 2014

On 24.07.2014 13:35, jitendra gupta wrote:
> Hi All
> My shell script is not throwing any error when I am having  some error
> in Python code.
> ~~~~~~~~ test.py ~~~~~~
> def main():
>      print "Test"
>      #some case error need to be thrown
>      raise Exception("Here is error")
> if __name__ == "__main__"
>      main()
> ~~~~~~
> ~~~~~~~~ second.py ~~~~~~
> def main():
>      print "Second function is called"
> if __name__ == "__main__"
>      main()
> ~~~~~~
> ~~~~~ shellTest.sh ~~~~~~~
> python test.py
> python second.py
> ~~~~~~~~~~~~~~~~~~~~~~~
> In this case, I dont want to run my second.py
> Even I am throwing error from my test.py, but still second.py is getting
> executed, which i dont want,

Your shell script calls runs the two Python scripts separately, that is, 
it first starts a Python interpreter telling it to run test.py .
When that is done (with whatever outcome !), it starts the interpreter a 
second time telling it to run second.py now.
The exception stops the execution of test.py, of course, and causes the 
interpreter to return, but your shell script is responsible for checking 
the exit status of the first script if it wants to run the second call 
only conditionally.

Try something like this (assuming bash):

python test.py
if [ $? = 0 ]; then
     python second.py

as your shell script.

By the way, both Python scripts you posted contain a syntax error, but I 
leave spotting it up to you.


More information about the Tutor mailing list