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

gen*_*tle 8 python finally ctrl

如果你用Ctrl + C停止一个python脚本,它会执行任何finally块,还是它会在字面上停止脚本的位置?

Ser*_*sta 13

那么,答案主要取决于它.这是实际发生的事情:

  • Python在try:... finally:块中执行代码
  • 发出Ctrl-C并在KeyboardInterrupt异常中进行转换
  • 处理被中断,控件传递给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
Run Code Online (Sandbox Code Playgroud)


Acu*_*nus 6

是的,假设一个 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)
Run Code Online (Sandbox Code Playgroud)

这是输出:

$ ./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
Run Code Online (Sandbox Code Playgroud)


Nem*_*eme 1

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