python除了最后不能使用KeyboardInterrupt

时间:2017-08-22 14:51:31

标签: python-2.7 try-except keyboardinterrupt

执行以下代码后,当我按下control + C时,执行结束,并且没有任何内容打印到控制台

import time

x = 1

try:
    while True:
    print x
    time.sleep(.3)
    x += 1

except KeyboardInterrupt:
    print "Bye"


finally:
    print "this one"

2 个答案:

答案 0 :(得分:0)

您的代码中存在缩进问题。如果改为:

import time

x = 1

try:
    while True:
        print x
        time.sleep(.3)
        x += 1

except KeyboardInterrupt:
    print "Bye"


finally:
    print "this one"

输出是:

1
2
3
4
5
6
Bye
this one

答案 1 :(得分:0)

当我在sublime文本中执行代码时出现问题,从终端

运行时效果很好