Adding Function To Sys.excepthook
Solution 1:
You can just check if sys.excepthook
is still built-in function before registering your handler:
>>>import sys, types>>>isinstance(sys.excepthook, types.BuiltinFunctionType)
True
>>>sys.excepthook = lambda x: x>>>isinstance(sys.excepthook, types.BuiltinFunctionType)
False
Solution 2:
If you put the code in your question into a module, you can import it many times, but it will be executed only the first time.
Solution 3:
Having a module-level "have the hook already been registered" variable seems like the simplest and most reliable way of doing this.
The other possible solutions would fall over in certain (rather obscure) circumstances -
checking if the sys.excepthook
is a builtin function will fail if an application registers a custom excepthook
, storing the original excepthook
at function-definition time will clobber subsequently registered excepthook functions.
import sys
_hook_registered = Falsedefregister_handler(force = False):
global _hook_registered
if _hook_registered andnot force:
return
orig_excepthook = sys.excepthook
deferror_catcher(*exc_info):
import logging
log = logging.getLogger(__name__)
log.critical("Unhandled exception", exc_info=exc_info)
orig_excepthook(*exc_info)
sys.excepthook = error_catcher
_hook_registered = True
Solution 4:
If you make orig_excepthook
an argument with a default value, the default value is fixed once at definition-time. So repeated calls to register_handler
will not change orig_excepthook
.
import sys
defregister_handler(orig_excepthook=sys.excepthook):
deferror_catcher(*exc_info):
import logging
log = logging.getLogger(__name__)
log.critical("Unhandled exception", exc_info=exc_info)
orig_excepthook(*exc_info)
sys.excepthook = error_catcher
import logging
logging.basicConfig()
register_handler()
register_handler()
register_handler()
undefined()
produces only one call to log.critical
.
Solution 5:
You should use sys.__excepthook__
[1].
It is an object that contains the original values of sys.excepthook
[2] at the start of the program.
ie;
import sys
import logging
def register_handler():
log = logging.getLogger(__name__)
def error_catcher(*exc_info):
log.critical("Unhandled exception", exc_info=exc_info)
sys.__excepthook__(*exc_info)
sys.excepthook = error_catcher
Reference: 1. https://docs.python.org/3/library/sys.html#sys.excepthook 2. https://docs.python.org/3/library/sys.html#sys.excepthook
Post a Comment for "Adding Function To Sys.excepthook"