【问题标题】:How to skip sys.exitfunc when unhandled exceptions occur发生未处理的异常时如何跳过 sys.exitfunc
【发布时间】:2008-09-17 08:05:18
【问题描述】:

如您所见,即使在程序本应死去之后,它也会从坟墓中说话。有没有办法在出现异常时“注销”exitfunction?

import atexit

def helloworld():
    print("Hello World!")

atexit.register(helloworld)

raise Exception("Good bye cruel world!")

输出

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    raise Exception("Good bye cruel world!")
Exception: Good bye cruel world!
Hello World!

【问题讨论】:

    标签: python exception atexit


    【解决方案1】:

    我真的不知道你为什么要这样做,但你可以安装一个异常钩子,只要引发未捕获的异常,Python就会调用它,并在其中清除atexit模块中的注册函数数组.

    类似的东西:

    import sys
    import atexit
    
    def clear_atexit_excepthook(exctype, value, traceback):
        atexit._exithandlers[:] = []
        sys.__excepthook__(exctype, value, traceback)
    
    def helloworld():
        print "Hello world!"
    
    sys.excepthook = clear_atexit_excepthook
    atexit.register(helloworld)
    
    raise Exception("Good bye cruel world!")
    

    请注意,如果从 atexit 注册函数引发异常,它可能会出现错误行为(但即使不使用此钩子,行为也会很奇怪)。

    【讨论】:

      【解决方案2】:

      除了调用 os._exit() 来避免注册的退出处理程序之外,您还需要捕获未处理的异常:

      import atexit
      import os
      
      def helloworld():
          print "Hello World!"
      
      atexit.register(helloworld)    
      
      try:
          raise Exception("Good bye cruel world!")
      
      except Exception, e:
          print 'caught unhandled exception', str(e)
      
          os._exit(1)
      

      【讨论】:

        【解决方案3】:

        如果你打电话

        import os
        os._exit(0)
        

        不会调用退出处理程序,您的或应用程序中其他模块注册的退出处理程序。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-06
          • 2023-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多