468,288 Members | 1,978 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,288 developers. It's quick & easy.

Signals and keyboard interupts

[Using Windows XP and Python 2.4.1]

I have question about the following code, which basically accomplished
what what I want, which is to gracefully exit the main loop when the
user presses either the control-c or control-break key:

import signal
import sys
import time
import traceback

QUIT = False

def mySigHandler(*whatever):
global QUIT # Change value of QUIT
QUIT = True
print "Interrupt caught and QUIT flag set"

# call the above procedure, when control-c or control-break is pressed.
old_SIGINT_Handler = signal.signal(signal.SIGINT, mySigHandler)
old_SIGBREAK_Handler = signal.signal(signal.SIGBREAK, mySigHandler)

while 1:
if QUIT:
break # exit loop

print "Processing..."

except IOError, (errno, strerror):
if errno == 4: # Interrupted function call
# mySigHandler called, so will ignore here
else: # some other IOerror -- print info and break out of loop
print "IOError[%s] exception occured: %s" % (errno,

print "finished"
# restore old signal handlers
signal.signal(signal.SIGINT, old_SIGINT_Handler)
signal.signal(signal.SIGBREAK, old_SIGBREAK_Handler)

My question is why is the a try/except block necessary? If it's left
out, and unhandled exception occurs. Seems like catching the signals
before python's default handler gets them should prevent it from being
turned into an exception. I don't understand how this is happening in
the above code.

I read several other posts about the subject, notably the one by Bengt
Richter in
but haven't been able to figure out why the [much more involved]
example in his post does not seem to exhibit this problem (i.e. it has
no try/except block).

Thanks in advance for any help.

Oct 27 '05 #1
0 1322

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Isidro Vila Verde | last post: by
4 posts views Thread by Gabriele Bartolini | last post: by
1 post views Thread by Leo Kirch | last post: by
4 posts views Thread by maxmagna | last post: by
2 posts views Thread by roaddogg | last post: by
11 posts views Thread by vippstar | last post: by
2 posts views Thread by wongjoekmeu | last post: by
reply views Thread by NPC403 | last post: by
2 posts views Thread by MrBee | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.