[Tutor] UPDATE: Is there a 'hook' to capture all exits from a python program?

Alan Gauld alan.gauld at btinternet.com
Fri Mar 20 10:02:54 CET 2015


On 20/03/15 02:57, Doug Basberg wrote:

> Still, I would like to know if a 'hook' exists on exit from Python.  I am
> running Linux on a Raspberry Pi with Python 2.7.4  I also run an Apache
> server on the Pi for monitor and control of power, HVAC, and security.

Your previous mail got you three options. I'd use all of them!

 > > https://docs.python.org/3/library/atexit.html
 >
 > ... But that's only for normal program termination; sys.excepthook is 
 > for unexpected exits


def close_relay(e=None,v=None,t=None):
    try:
       if not relay_closed()
          really_close_relay()
    except:
       really_close_relay()

import sys, atexit
atexit.register(close_relay)
sys.excepthook = close_relay


try:
    main program here
finally:
    close_relay()



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list