KeyboardInterrupt eats my error and then won't be caught

greg greg at
Sat Jun 20 06:09:08 CEST 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

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.


More information about the Python-list mailing list