$ 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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With