Can I catch and dump an exception (and the corresponding stacktrace) that would make the program crash without doing something like :
try:
# whole program
except Execption as e:
dump(e)
raise
Sometime a external library crashes, and I'd like to react to Python dying and log the reasons it does so. I don't want to prevent the Exception from crashing the program, I just want the debug information.
Something like:
signals.register('dying', callback)
def callback(context):
# dumping the exception and
# stack trace from here
Is that even possible ?
Yes, by registering a sys.excepthook()
function:
import sys
def myexcepthook(type, value, tb):
dump(type, value, tb)
sys.excepthook = myexcepthook
This replaces the default hook, which prints out the traceback to stderr
. It is called whenever an uncaught exception is raised, and the interpreter is about to exit.
If you want to reuse the original exception hook from your custom hook, call sys.__excepthook__
:
def myexcepthook(type, value, tb):
dump(type, value, tb)
sys.__excepthook__(type, value, tb)
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