How to find exit code or reason when atexit callback is called in Python? How to find exit code or reason when atexit callback is called in Python? python python

How to find exit code or reason when atexit callback is called in Python?


You can solve this using sys.excepthook and by monkey-patching sys.exit():

import atexitimport sysclass ExitHooks(object):    def __init__(self):        self.exit_code = None        self.exception = None    def hook(self):        self._orig_exit = sys.exit        sys.exit = self.exit        sys.excepthook = self.exc_handler    def exit(self, code=0):        self.exit_code = code        self._orig_exit(code)    def exc_handler(self, exc_type, exc, *args):        self.exception = exchooks = ExitHooks()hooks.hook()def foo():    if hooks.exit_code is not None:        print("death by sys.exit(%d)" % hooks.exit_code)    elif hooks.exception is not None:        print("death by exception: %s" % hooks.exception)    else:        print("natural death")atexit.register(foo)# testsys.exit(1)