Shutdown hook

Duncan Booth duncan.booth at invalid.invalid
Wed Nov 16 03:48:15 EST 2005


Lawrence Oluyede wrote:

> Il 2005-11-15, Ben Finney <bignose+hates-spam at benfinney.id.au> ha
> scritto: 
>> Steve <steve.morin at gmail.com> wrote:
>>> Does any one know if python has the ability to run a shutdown hook.
>>
>> When the Python runtime system wants to exit, it raises a SystemExit
>> exception.
>>
>> Catch that exception at the top level of your code, and do whatever
>> you like. (It might be polite to actually exit at some point, of
>> course. sys.exit(exitcode) will do so -- raising another SystemExit
>> exception.)
>>
> 
> I think using atexit module -
> http://docs.python.org/lib/module-atexit.html is cleaner
> 
Correct, although this won't catch all cases where a program is exiting. 
For example, on Windows, if you use Ctrl+C to terminate a program the 
atexit function *is* called, but if you use Ctrl+Break the atexit function 
is not called unless you install a suitable signal handler:

import signal
def sigbreak(signum, frame):
    sys.exit("***break")
    
signal.signal(signal.SIGBREAK, sigbreak)

Even then there are still other ways to terminate a process which will not 
be caught.




More information about the Python-list mailing list