tags:

views:

1151

answers:

4

Why code like that is not catching CTRL-C?

MaxVal = 10000
StepInterval = 10

for i in range(1,MaxVal,StepInterval):
    try:
        print str(i)
    except KeyboardInterrupt:
        break

print "done"

My expectation is -- if CTRL-C is pressed while program is running, KeyboardInterrupt is supposed to leave the loop. It does not.

Any help on what I'm doing wrong?

A: 

It does break out of the loop and print "done".

Akbar ibrahim
A: 

It works.

I'm using Ubuntu Linux, and you? Test it again using something like MaxVal = 10000000

Andrea Ambu
I'm running it on Windows.
I see. It's not interrupting when running in Pythonwin (Python IDE). It perfectly interrupts if called from the command line. So looks like it's a problem with Pythonwin.
It works using IDLE in linux. Then the problem it's probably Pythonwin.
Andrea Ambu
+7  A: 

Sounds like the program is done by the time control-c has been hit, but your operating system hasn't finished showing you all the output. .

+4  A: 

code flow is as follows:

  1. for grabs new object from list (generated by range) and sets i to it
  2. try
  3. print
  4. go back to 1

If you hit CTRL-C in the part 1 it is outside the try/except, so it won't catch the exception.

Try this instead:

MaxVal = 10000
StepInterval = 10

try:
    for i in range(1, MaxVal, StepInterval):
        print i
except KeyboardInterrupt:
    pass

print "done"
nosklo