Out of the box atexit not quite suitable for what you want to do: first of all, it is used to clean resources at the very last moment when everything stops and exits. By analogy, this is "finally" try / except, whereas you want an "else" try / except.
The easiest way I can think of is to create a global flag that you set only when your script "succeeds" ... and then all the functions that you attach to atexit check this flag and do nothing if it doesn't it was found.
For instance:
_success = False def atsuccess(func, *args, **kwds): def wrapper(): if _success: func(*args,**kwds) atexit(wrapper) def set_success(): global _success _success = True
One limitation is if you have code that calls sys.exit(0) before setting the success flag. Such code should (probably) be reorganized to return to the main function, so you call set_success and sys.exit only one place. Otherwise, you will need to add something like the following shell around the main entry point in the script:
try: main() except SystemExit, err: if err.code == 0: set_success() raise
source share