[Tutor] finally without try or except

eryksun eryksun at gmail.com
Mon Jul 30 22:01:05 CEST 2012


On Mon, Jul 30, 2012 at 3:10 PM, Tino Dai <oberoc at gmail.com> wrote:
> On Mon, Jul 30, 2012 at 1:52 PM, Mark Lawrence <breamoreboy at yahoo.co.uk>
> wrote:
>
>> Sorry I'm not completely sure what you're asking for but will this help
>> http://docs.python.org/library/atexit.html ?
>>
> I think this might be what I'm looking for. But for about 2 minutes, I was
> like a-texit....what does that have to do with....oooohhhh it's at exit.

You might want to install a SIGINT (ctrl-c) signal handler. If you
manually handle the SIGINT signal, you can ignore it after the first
signal (users tend to press ctrl-c repeatedly). You could also apply
this to a regular try/finally approach instead of using atexit. If you
choose to use atexit, don't expect magic compared to try/finally. If
the OS kills the process or the interpreter crashes, your atexit
function won't run. I'd periodically save the data (probably based on
both time and quantity) for a long-run process.

For example:

import signal

def sigint(signum, stack):
    #dummy handler to ignore future SIGINT signals
    dummy = lambda si, st: None
    signal.signal(signal.SIGINT, dummy)
    raise KeyboardInterrupt

signal.signal(signal.SIGINT, sigint)

def save_data():
    print "Saving"
    for k in xrange(1<<24):
        pass
    print "\nSaved {0} entries".format(k + 1)

try:
    print "Waiting for signal..."  #press ctrl-c
    signal.pause()
except:
    pass  #At least log here
finally:
    save_data()

The original SIGINT handler is signal.default_int_handler in case you
need to restore it.


More information about the Tutor mailing list