收到Ctrl + C后,Python会执行finally块

时间:2016-12-22 09:56:15

标签: python finally ctrl

如果你用Ctrl + C停止一个python脚本,它会执行任何finally块,还是会直接停止脚本呢?

3 个答案:

答案 0 :(得分:12)

嗯,答案主要是取决于。这是实际发生的事情:

  • Python在try:... finally:
  • 中执行代码
  • 发出Ctrl-C并在KeyboardInterrupt Exception中翻译
  • 处理被中断,控件传递给finally块
乍一看,一切都按预期进行。但...

当用户(不是您,而是其他人......)想要中断任务时,他通常会多次按Ctrl-C。第一个将在finally块中分支执行。如果在finally块的中间发生了另一个Ctrl-C,因为它包含操作,比如关闭文件,将会引发一个新的KeyboardInterrupt,并且没有任何保证整个块将被执行,你可以拥有类似的东西:

Traceback (most recent call last):
  File "...", line ..., in ...
    ...
KeyboardInterrupt

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "...", line ..., in ...
    ...
  File "...", line ..., in ...
    ...
KeyboardInterrupt

答案 1 :(得分:4)

是的,假设只有一个Ctrl + C,至少在Linux下它会。您可以使用以下Python 3代码对其进行测试:

import time

try:
    print('In try.')
    time.sleep(1000)
finally:
    print('  <-- Note the Ctrl+C.')
    for i in range(1, 6):
        print(f'Finishing up part {i} of 5.')
        time.sleep(.1)

这是输出:

$ ./finally.py
In try.
^C  <-- Note the Ctrl+C.
Finishing up part 1 of 5.
Finishing up part 2 of 5.
Finishing up part 3 of 5.
Finishing up part 4 of 5.
Finishing up part 5 of 5.
Traceback (most recent call last):
  File "./finally.py", line 7, in <module>
    time.sleep(1000)
KeyboardInterrupt

答案 2 :(得分:0)

是的,它通常会引发KeyboardInterrupt异常,但请记住,您的应用程序可能会在任何时候意外终止,因此您不应该依赖它。