How to skip sys.exitfunc when unhandled exceptions occur

As you can see, even after the program should have died it speaks from the grave. Is there a way to "deregister" the exitfunction in case of exceptions?

import atexit

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


raise Exception("Good bye cruel world!")


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

Asked by: Robert940 | Posted: 24-09-2021

Answer 1

I don't really know why you want to do that, but you can install an excepthook that will be called by Python whenever an uncatched exception is raised, and in it clear the array of 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

raise Exception("Good bye cruel world!")

Beware that it may behave incorrectly if the exception is raised from an atexit registered function (but then the behaviour would have been strange even if this hook was not used).

Answered by: Brooke664 | Posted: 25-10-2021

Answer 2

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

import atexit
import os

def helloworld():
    print "Hello World!"


    raise Exception("Good bye cruel world!")

except Exception, e:
    print 'caught unhandled exception', str(e)


Answered by: William276 | Posted: 25-10-2021

Answer 3

If you call

import os

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

Answered by: Charlie523 | Posted: 25-10-2021

Similar questions

python - matplotlib: Error in sys.exitfunc

I keep getting error in sys.exitfunc when working with matplotlib. For example, the following code throw it for matplotlib 1.3.0 / Python 2.7.3 / Ubuntu 12.04.3 LTS from matplotlib.pyplot import figure, show from numpy.random import random fh = figure(figsize = (15, 10, )) ax = fh.add_axes((.1, .1, .8, .8, )) ax.scatter(random((100, )), random((100, ))) This yields

sys.exitfunc not working in python

I am trying to run following simple code import sys print("Starting Test Python Module"); def testmethod(): print("From test method") sys.exitfunc = testmethod print("Terminating Test Python Module"); and it prints C:\Users\athakur\Softwares&gt;python Starting Test Python Module Terminating Test Python Module I am not able to understand why ...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python