atexit.register in case of errors

Mel Wilson mwilson at the-wire.com
Wed Feb 15 08:33:51 EST 2012


Andrea Crotti wrote:

> I have the following very simplified situation
> 
> from atexit import register
> 
> 
> def goodbye():
>      print("saying goodbye")
> 
> 
> def main():
>      while True:
>          var = raw_input("read something")
> 
> 
> if __name__ == '__main__':
>      register(goodbye)
>      main()
> 
> 
> But in my case the "goodbye" function is deleting the logging file which
> was created
> during the application execution.
> Now the problem is that it *always* executes, even when the applications
> quits for
> some bad errors.
> 
> Is there a way to have an exit hook, which doesn't execute in case of
> errors?
> I've seen the code of atexit and it apparently doesn't know anything
> about the current
> status and why the application is actually quitting, is that correct?

That's sort of the point: to do things that simply *have* to happen, even if 
you've lost control of the program.

The usual way to do what you're asking is

if __name__ == '__main__':
    main()
    goodbye()

and write main so that it returns after it's done all the things it's 
supposed to do.  If you've sprinkled `sys.exit()` all over your code, then 
don't do that.  If you're forced to deal with a library that hides 
`sys.exit()` calls in the functions, then you have my sympathy.  Library 
authors should not do that, and there have been threads on c.l.p explaining 
why they shouldn't.

	Mel.




More information about the Python-list mailing list