简单的直接使用内置的atexit
库
def foo():
print("exit")
atexit.register(foo)
不过这种只能在退出的时候做一些操作,但不太好获取到退出时候的状态码和导致退出的异常之类,如果要使用的话,需要绑定sys
的excepthook
和exit
import atexit
import sys
import traceback
class 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:BaseException, tb,*args):
print(traceback.format_exception_only(exc_type,exc))
self.exception = exc
hooks = 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)
# test
print(1/0)