By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,035 Members | 1,984 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,035 IT Pros & Developers. It's quick & easy.

Signals and keyboard interupts

P: n/a
[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....f08170a?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

Oct 27 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.