Why is KeyboardInterrupt not working in python?

前端 未结 4 1775
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-19 00:01

Why doesn\'t code like the following catch CTRL-C?

MAXVAL = 10000
STEP_INTERVAL = 10

for i in range(1, MAXVAL, STEP_INTERVAL):
    try:
        print str(i)         


        
相关标签:
4条回答
  • 2020-12-19 00:39

    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"
    
    0 讨论(0)
  • 2020-12-19 00:42

    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. .

    0 讨论(0)
  • 2020-12-19 00:42

    I was having this same problem and I just found out what was the solution:

    You're running this code in an IDE like PyCharm. The IDE is taking ctrl+c (keyboardinterrupt) as copy. Try running your code in the terminal.

    0 讨论(0)
  • 2020-12-19 00:52

    It works.

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

    0 讨论(0)
提交回复
热议问题