trapping keyboard interupt

sismex01 at hebmex.com sismex01 at hebmex.com
Mon Oct 7 11:51:09 EDT 2002


> From: Rob Hall [mailto:bloke at ii.net]
> 
> Having a bit of trouble trapping the keyboard interupt.  I 
> have something like this:
> 
> continueFlag = 1
> 
> try:
>     while continueFlag:
>         doSomeStuff
> except KeyboardInterrupt:
>     continueFlag = 0
> 
> doCleanUpOperations
> 
> Basically, I have a program that runs continuously.  
> Sometimes I need to terminate the program, save its state,
> and restart it at a later time.  However,  In it, I have a
> long process that can take 5 minutes to complete, and once
> this process starts, i don't want it to stop.  But I
> would like it to know that as soon as it has finnished this
> process it should terminate.
> 
> My intention was to trap the Keyboard Interupt, reset a flag
> that would tell the program to exit the main loop.  But I can't
> figure how to resume execution from the point I gave the Keyboard
> Interupt.
> 
> Can someone help?
> 
> Rob
>

I'd recommend you move the try:... except KeyboardInterrupt:...
section inside the loop, or inside the task if possible,
so you can continue processing.

For example, you have this:

> try:
>     while continueFlag:
>         doSomeStuff
> except KeyboardInterrupt:
>     continueFlag = 0
> 
> doCleanUpOperations

The keyboard interrupt will toss you outside the while: loop,
and you've no way to return to it.  Also, you're already
outside "doSomeStuff", ¿is it restartable? ¿can you simply
reenter it and continue where you left off?  Somehow I don't
think so, by your description.

So, you've some design decisions.  You can move the try:
except: block *inside* "doSomeStuff", in which case you can
trap the interrupt in an innocous place, set the flag,
and keep running until you're *outside* "doSomeStuff" again
and the while: can exit.

Another way to do this, if you can use signals, is to
catch the SIGINT signal generated by a ^C (same as KeyboardInterrupt)
and let it set your flag.  Kinda like this:

-------------------------------------------------
import signal

continueFlag = 1

# Define new handler.
def New_SIGINT(*args):
  continueFlag = 0

# Install new handler to be called by a ^C.
signal.signal(signal.SIGINT, New_SIGINT)

# Run loop normally.
while continueFlag: doSomeStuff()

# Shutdown gracefully.
doCleanupOperations()
-------------------------------------------------

Now, beware of threads because threads and signals don't
really mix all that well. :-/

Good luck, hope this helps :-)

-gustavo













More information about the Python-list mailing list