How to skip sys.exitfunc when unhandled exceptions occur
Asked Answered
J

2

5

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

atexit.register(helloworld)

raise Exception("Good bye cruel world!")

outputs

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!
Janniejanos answered 17/9, 2008 at 8:5 Comment(0)
E
7

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
atexit.register(helloworld)

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).

Edita answered 17/9, 2008 at 8:21 Comment(0)
E
0

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

atexit.register(helloworld)    

try:
    raise Exception("Good bye cruel world!")

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

    os._exit(1)
Entertaining answered 17/9, 2008 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.