KeyboardInterrupt eats my error and then won't be caught

greg greg at cosc.canterbury.ac.nz
Sat Jun 20 00:09:08 EDT 2009


Philip Semanchuk wrote:

> try:
>    sem.acquire()   # User hits Ctrl + C while this is waiting
> except:
>    print "********* I caught it!"

> Instead a KeyboardInterrupt error is propagated up to the interpreter  
> and the process is killed as if the try/except wasn't there at all.

Not sure exactly what's happening, but I think I can guess.
Python installs a signal handler for Ctrl-C that sets a
flag in the interpreter. Every so many bytecodes executed,
the flag is checked and KeyboardInterrupt raised if it's
set.

So there can be a short delay between the Ctrl-C signal
being received and KeyboardInterrupt being raised, and it
seems that this delay results in it happening after the
try-except has exited.

You could try using signal.signal() to install a handler
for Ctrl-C that does nothing in a section around the
sem.acquire call(). That should prevent the KeyboardInterrupt
flag from being set, but the signal will still be occurring
at the Unix level, so the system call will get interrupted.

-- 
Greg



More information about the Python-list mailing list