当前位置:   article > 正文

Python添加程序退出钩子(Exit Hook)_python3 程序退出时 hook

python3 程序退出时 hook

简单的直接使用内置的atexit

def foo():
    print("exit")
atexit.register(foo)
  • 1
  • 2
  • 3

不过这种只能在退出的时候做一些操作,但不太好获取到退出时候的状态码和导致退出的异常之类,如果要使用的话,需要绑定sysexcepthookexit

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)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/918295
推荐阅读
相关标签
  

闽ICP备14008679号