When is KeyboardInterrupt raised in Python?

不羁的心 提交于 2019-12-05 03:28:38

According to a note in the unrelated PEP 343:

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

Yes, a KeyboardInterrupt can occur in the place you marked.

To deal with this, you should use a with block:

with open('foo') as file_:
    # do some things
    raise KeyboardInterrupt

# file resource is closed no matter what, even if a KeyboardInterrupt is raised

However, the exception could occur even between the open() call and the assignment to file_. It's probably not worth worrying about this, because usually a ctrl-c will mean your program is about to end, so the "leaked" file handle will be cleaned up by the OS. But if you know that it is important, you can use a signal handler to catch the signal that raises KeyboardInterrupt (SIGINT).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!