On Jul 9, 7:28 pm, Miles Kaufmann <mile...@umich.edu> wrote: > On Jul 9, 2009, at 9:20 AM, Lie Ryan wrote: > > > Michael Mossey wrote: > >> I want to understand better what the "secret" is to responding to a > >> ctrl-C in any shape or form. > > > Are you asking: "when would the python interpreter process > > KeyboardInterrupt?" > > ... > > In single threaded python program, the currently running thread is > > always the main thread (which can handle KeyboardInterrupt). I believe > > SIGINT is checked at every ticks. But SIGINT cannot interrupt atomic > > operations (i.e. it cannot interrupt long operations that takes a > > single > > tick). > > Some otherwise atomic single-bytecode operations (like large integer > arithmetic) do manual checks for whether signals were raised (though > that won't help at all if the operation isn't on the main thread). > > > I believe a tick in python is equivalent to a single bytecode, but > > please correct me if I'm wrong. > > Not all opcodes qualify as a tick. In general, those opcodes that > cause control to remain in the eval loop (and not make calls to other > Python or C functions) don't qualify as ticks (but there are > exceptions, e.g. so that while True: pass is interruptible). In > Python/ceval.c: PyEval_EvalFrameEx(), those opcodes that don't end in > goto fast_next_opcode are ticks. > > Please correct me if _I'm_ wrong! :) > -Miles
You don't need to do I/O. This works: try: process_forever() except KeyboardInterrupt: save critical stuff write nice messages I often wrap a large computational task like this, with the idea that the exception can let me exit safely, in my case by writing restart parameters and printing a summary pf progress to date. Gerry -- http://mail.python.org/mailman/listinfo/python-list