通过python中的键盘输入中断循环

Mik*_*han 2 python python-2.7

我在按一个键跳出循环时遇到问题。

我用谷歌搜索并找到了msvcrt 模块,但它没有解决我的问题。

这是我的代码。

while True:
    """some code"""
    if *keyboard_input: space* == True:
        break
Run Code Online (Sandbox Code Playgroud)

我知道这是一个简单的问题,但我就是找不到要导入的正确模块。

谢谢!

bca*_*tle 7

使用 try/except 拦截KeyboardInterrupt

while True:
    try:
        # some code
    except KeyboardInterrupt:
        print 'All done'
        # If you actually want the program to exit
        raise
Run Code Online (Sandbox Code Playgroud)

现在您可以使用 CTRL-C 跳出循环。如果您希望程序继续运行,请不要raise在最后一行包含该语句。