Setting the exit status from sys.excepthook

Peter Otten __peter__ at web.de
Mon Nov 21 07:57:36 EST 2016


Steven D'Aprano wrote:

> I have script with an exception handler that takes care of writing the
> traceback to syslog, and I set it as the global exceptionhook:
> 
> sys.excepthook = my_error_handler
> 
> 
> When my script raises, my_error_handler is called, as expected, and the
> process exits with status 1.
> 
> How can I change the exit status to another value, but only for exceptions
> handled by my_error_handler?

Why not just put

try:
   ...
except:
   ...

around the main function?

That said, it looks like you can exit() from the errorhandler:

$ cat bend_exit.py
import sys

def my_error_handler(etype, exception, traceback):
    print("unhandled", exception)
    sys.exit(2)

sys.excepthook = my_error_handler

1/int(sys.argv[1])
print("bye")
$ python3 bend_exit.py 0; echo $?
unhandled division by zero
2
$ python3 bend_exit.py 1; echo $?
bye
0

If "bad things" can happen I don't know...




More information about the Python-list mailing list