How to skip sys.exitfunc when unhandled exceptions occur

As you can see, even after the program was supposed to die, it speaks from the grave. Is there a way to β€œunregister” the exit function in case of exceptions?

import atexit def helloworld(): print("Hello World!") atexit.register(helloworld) raise Exception("Good bye cruel world!") 

exits

 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! 
+4
source share
3 answers

I really don't know why you want to do this, but you can install an excepthook that Python will call whenever an exception is thrown, and it clears the array of the registered function in the atexit module.

Something like that:

 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!") 

Beware that it can behave incorrectly if an exception arises from the registered atexit function (but then the behavior would be strange even if this hook was not used).

+5
source

If you call

 import os os._exit(0) 

exit handlers will not be called, yours or those that have been registered by other modules in the application.

0
source

In addition to calling os._exit (), to avoid a registered exit handler, you also need to catch an unhandled exception:

 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) 
0
source

Source: https://habr.com/ru/post/1276795/


All Articles