I want to run a task when my Python program finishes, but only if it finishes successfully. As far as I know, using the atexit module means that my registered function will always be run at program termination, regardless of success. Is there a similar functionality to register a function so that it runs only on successful exit? Alternatively, is there a way for my exit function to detect whether the exit was normal or exceptional?
Here is some code that demonstrates the problem. It will print that the program succeeded, even when it has failed.
import atexit def myexitfunc(): print "Program succeeded!" atexit.register(myexitfunc) raise Exception("Program failed!") Output:
$ python atexittest.py Traceback (most recent call last): File "atexittest.py", line 8, in <module> raise Exception("Program failed!") Exception: Program failed! Program succeeded!