Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting exit code in Python when an exception is raised

$ cat e.py raise Exception $ python e.py Traceback (most recent call last):   File "e.py", line 1, in <module>     raise Exception Exception $ echo $? 1 

I would like to change this exit code from 1 to 3 while still dumping the full stack trace. What's the best way to do this?

like image 695
sh-beta Avatar asked Jul 16 '11 20:07

sh-beta


People also ask

How do you handle a raised exception in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.

How do you set an exit code in Python?

Exit Codes in Python Using sysThe sys module has a function, exit() , which lets us use the exit codes and terminate the programs based on our needs. The exit() function accepts a single argument which is the exit code itself. The default value of the argument is 0 , that is, a successful response.

Does raising an exception stop the program Python?

except block is completed and the program will proceed. However, if an exception is raised in the try clause, Python will stop executing any more code in that clause, and pass the exception to the except clause to see if this particular error is handled there.


1 Answers

Take a look at the traceback module. You could do the following:

import sys, traceback  try:   raise Exception() except:   traceback.print_exc()   sys.exit(3) 

This will write traceback to standard error and exit with code 3.

like image 179
tomasz Avatar answered Sep 19 '22 04:09

tomasz