2008-09-17 83 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) 
相關問題