如何在Python中检测ESCape按键? [英] How to detect ESCape keypress in Python?

查看:521
本文介绍了如何在Python中检测ESCape按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在命令窗口(Windows 7,Python 3.1)中运行一个进程,我希望用户按ESCape键中止进程。但是,按ESC ESC键不会出现任何事情:-(循环永远不会中断,我也尝试从IDE(Wing)中运行脚本,但是再次,循环不能中断。

I am running a process in a command window (Windows 7, Python 3.1) where I would like the user to abort the process by pressing the ESCape key. However, pressing the ESCape key doesn't appear to do anything :-(, the loop never breaks. I have also tried running the script from within my IDE (Wing), but again, the loop cannot be interrupted.

以下是我的概念验证测试的精简版本...

The following is a stripped-down version of my proof-of-concept test...

import msvcrt
import time

aborted = False

for time_remaining in range(10,0,-1):
    # First of all, check if ESCape was pressed
    if msvcrt.kbhit() and msvcrt.getch()==chr(27):
        aborted = True
        break

    print(str(time_remaining))       # so I can see loop is working
    time.sleep(1)                    # delay for 1 second
#endfor timing loop

if aborted:
    print("Program was aborted")
else:
    print("Program was not aborted")

time.sleep(5)  # to see result in command window before it disappears!

如果有人可以告诉m e我可能会出错,我会非常感激。

If anyone could tell me where I might be going wrong I would be most grateful.

推荐答案

Python 3字符串是unicode,因此必须被编码到字节进行比较。尝试这个测试:

Python 3 strings are unicode and, therefore, must be encoded to bytes for comparison. Try this test:

if msvcrt.kbhit() and msvcrt.getch() == chr(27).encode():
    aborted = True
    break

或此测试:

if msvcrt.kbhit() and msvcrt.getch().decode() == chr(27):
    aborted = True
    break

或此测试:

if msvcrt.kbhit() and ord(msvcrt.getch()) == 27:
    aborted = True
    break

这篇关于如何在Python中检测ESCape按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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