2008-09-17 84 views
4

正如你所看到的,即使在程序死亡之后,它也会从坟墓中发出。是否有办法在异常情况下“撤销”退出功能?如何在发生未处理的异常时跳过sys.exitfunc

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! 

回答

5

我真的不知道为什么要这样做,但是您可以安装一个excepthook,只要引发未捕获的异常,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注册功能提高(但随后的行为将是奇怪的,即使没有使用这个钩子)。

0

如果你打电话

import os 
os._exit(0) 

的退出处理程序将不会被调用,你的还是那些通过在应用程序的其它模块的注册。

0

除了呼吁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) 
相关问题