Signals and keyboard interupts

M

Martin Miller

[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
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:
try:
if QUIT:
break # exit loop

print "Processing..."
time.sleep(2)

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

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
http://groups.google.com/group/comp.lang.python/msg/5b27edd0df08170a?hl=en&,
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.
-Martin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top