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

Peter Otten __peter__ at web.de
Fri Mar 20 10:37:54 CET 2015


Alan Gauld wrote:

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

That reeks of cargo cult. Are there actual scenarios for each of the three 
mechanisms where it is the only one that works?

I would expect that

try:
    main program here
finally:
    close_relay()

provides the same level of confidence, i. e. the relay will be closed when 
the program closes normally or the main code raises an exception, but not if 
the process is killed.



More information about the Tutor mailing list