什么时候在Python中引发KeyboardInterrupt? [英] When is KeyboardInterrupt raised in Python?

查看:4749
本文介绍了什么时候在Python中引发KeyboardInterrupt?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所有文档告诉我们的是


在用户按下中断键时引发(通常 Control- C Delete )。在执行过程中,会定期检查中断。

Raised when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly.

但是从代码的角度来看,什么时候可以看到这个? ?是否在语句执行期间发生?仅在语句之间?

But from the point of the code, when can I see this exception? Does it occur during statement execution? Only between statements? Can it happen in the middle of an expression?

例如:

file_ = open('foo')
# <-- can a KeyboardInterrupt be raised here, after the successful
# completion of open but prior to the try? -->
try:
    # try some things with file_
finally:
    # cleanup

在适当的 KeyboardInterrupt 期间此代码会泄漏吗?还是在执行某些语句或表达式期间引发它?

Will this code leak during a well-timed KeyboardInterrupt? Or is it raised during the execution of some statements or expressions?

推荐答案

根据不相关的 PEP 343


即使您编写无错误的代码,KeyboardInterrupt异常仍可能导致它在任何两个虚拟机操作码之间退出。

Even if you write bug-free code, a KeyboardInterrupt exception can still cause it to exit between any two virtual machine opcodes.

因此,它基本上可以发生在任何地方。它确实可以在单个表达式的求值过程中发生。 (这并不奇怪,因为表达式可以包含函数调用,并且函数调用内部几乎可以发生任何事情。)

So it can occur essentially anywhere. It can indeed occur during evaluation of a single expression. (This shouldn't be surprising, since an expression can include function calls, and pretty much anything can happen inside a function call.)

这篇关于什么时候在Python中引发KeyboardInterrupt?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆