简体   繁体   English

Python 键盘中断不停止循环

[英]Python KeyboardInterrupt not stopping loop

Python 3.10 in macOS terminal macOS 终端中的 Python 3.10

I kick off this simple script in macOS terminal, which runs infinitely ( so please be warned when running it ):我在 macOS 终端中启动了这个简单的脚本,它无限运行(所以在运行时请注意):

import itertools
for i in itertools.count(start=1):
    try:
        p = pow(2,i)
        print(p)
    except KeyboardInterrupt:
        print("Loop terminated")
        raise

Yet clicking on the keyboard does not terminate the loop.然而,点击键盘并不会终止循环。

What am I missing?我错过了什么?

Thanks to everyone for the clarification.感谢大家的澄清。 The problem is I was under the assumption that KeyboardInterrupt would respond to any key pressed.问题是我假设KeyboardInterrupt会响应按下的任何键。 It actually only responds to Ctrl-C.它实际上只响应 Ctrl-C。 Everything works as expected when using Ctrl-C.使用 Ctrl-C 时一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM