Newsgroups: comp.lang.python
From: Piet van Oostrum <p...@cs.uu.nl>
Date: Sat, 20 Jun 2009 10:19:28 +0200
Local: Sat, Jun 20 2009 4:19 am
Subject: Re: KeyboardInterrupt eats my error and then won't be caught
>>>>> greg <g...@cosc.canterbury.ac.nz> (g) wrote: I think you are approaching the cause of the problem. >g> 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. >g> Not sure exactly what's happening, but I think I can guess. >g> Python installs a signal handler for Ctrl-C that sets a >g> flag in the interpreter. Every so many bytecodes executed, >g> the flag is checked and KeyboardInterrupt raised if it's >g> set. >g> So there can be a short delay between the Ctrl-C signal >g> being received and KeyboardInterrupt being raised, and it >g> seems that this delay results in it happening after the >g> try-except has exited. Your answer triggered the following thought in my head: There are actually two exceptions occurring: One is the Ctrl-C, which as As the call to sem.acquire releases and reacquires the GIL, I think >g> You could try using signal.signal() to install a handler Your suggestion seems to work: >g> for Ctrl-C that does nothing in a section around the >g> sem.acquire call(). That should prevent the KeyboardInterrupt >g> flag from being set, but the signal will still be occurring >g> at the Unix level, so the system call will get interrupted. import posix_ipc sem = posix_ipc.Semaphore(None, posix_ipc.O_CREX) sem.close() prints: ['Trying', 'I caught it!'] I also tried some other variants, catching the KeyboardInterrupt at This one prints: ['Trying', 'Keyboard Interrupt'] import posix_ipc sem = posix_ipc.Semaphore(None, posix_ipc.O_CREX) status = [] sem.close() And this one prints: ['Trying', 'I caught it!'] import posix_ipc sem = posix_ipc.Semaphore(None, posix_ipc.O_CREX) status = [] sem.close() I was actually a bit surprised that the addition of the try/except Folding the two try's into one with two except clauses will not help as I also added traceback printout in the outer exception handler and it My conclusion is that if there are two exceptions at the same time, the I think you can only have two exceptions at the same time if at least You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
| ||||||||||||||