如何在Python中检测ESCape按键?

发布于 2024-10-19 21:22:57 字数 758 浏览 1 评论 0原文

我正在命令窗口(Windows 7、Python 3.1)中运行一个进程,我希望用户通过按 Esc 键来中止该进程。但是,按 Esc 似乎没有执行任何操作,循环永远不会中断。我还尝试从 IDE (Wing) 中运行脚本,但同样,循环无法中断。

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

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!

如果有人能告诉我哪里可能出错,我将不胜感激。

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 Esc key. However, pressing Esc 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!

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

冬天旳寂寞 2024-10-26 21:22:57

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

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

Or this test:

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

Or this test:

if msvcrt.kbhit() and ord(msvcrt.getch()) == 27:
    aborted = True
    break
地狱即天堂 2024-10-26 21:22:57

您确实应该精简更多内容,如下所示:

>>> import msvcrt
>>> ch = msvcrt.getch()
# Press esc
>>> ch
b'\x1b'
>>> chr(27)
'\x1b'
>>> ch == chr(27)
False

所以问题是: msvcrt.getch() 返回 字节chr(27) 返回字符串。在 Python 3 中,它们是两种不同的类型,因此“==”部分永远不会起作用,并且 if 语句将始终被评估为 False

解决方案对您来说应该是显而易见的。

关于字符串与字节的更多,来自《Dive into Python 3》一书。

交互式控制台非常好用。对于调试很有用,请尝试更多地使用它:)

You should really strip down more, like this one below:

>>> import msvcrt
>>> ch = msvcrt.getch()
# Press esc
>>> ch
b'\x1b'
>>> chr(27)
'\x1b'
>>> ch == chr(27)
False

So here is the problem: msvcrt.getch() returns bytes, chr(27) returns string. In Python 3 they are two distinct types, so the "==" part will never work, and the if statement will always be evaluated as False.

The solution should be obvious to you.

More about strings vs bytes, from the book Dive into Python 3.

The interactive console is very useful for debugging, try use it more :)

亢潮 2024-10-26 21:22:57

您不需要编码,解码,chr,ord,...

if msvcrt.kbhit() and msvcrt.getch() == b'\x1b':

或者如果您想在代码中的某处看到“27”:

if msvcrt.kbhit() and msvcrt.getch()[0] == 27:

You don't need encode, decode, chr, ord, ....

if msvcrt.kbhit() and msvcrt.getch() == b'\x1b':

or if you'd like to see "27" in the code somewhere:

if msvcrt.kbhit() and msvcrt.getch()[0] == 27:
调妓 2024-10-26 21:22:57

Python 2/3 兼容代码:

import time, sys

ESC = '\x1b'
PY3K = sys.version_info >= (3,)
if PY3K:
    from msvcrt import kbhit, getwch as _getch
else:
    from msvcrt import kbhit, getch as _getch
while not kbhit() or _getch() != ESC:
    print(time.asctime())
    time.sleep(1)

代码部分取自 pager< /code>模块,里面有更多东西。

Python 2/3 compatible code:

import time, sys

ESC = '\x1b'
PY3K = sys.version_info >= (3,)
if PY3K:
    from msvcrt import kbhit, getwch as _getch
else:
    from msvcrt import kbhit, getch as _getch
while not kbhit() or _getch() != ESC:
    print(time.asctime())
    time.sleep(1)

Code parts are taken from pager module with more stuff inside.

风尘浪孓 2024-10-26 21:22:57

您是否尝试过使用不同的密钥来测试它是否不仅仅是该密钥?

您是否也尝试过此处的示例 看看它们是否有效?

Have you tried using a different key to test if it's not just that key?

Did you also try the examples here to see if they worked?

早乙女 2024-10-26 21:22:57

将 cv2 导入为 cv

a = cv.waitkey(0)

if (a == 27 或 ord('esc') == 27):
中止=真
休息

import cv2 as cv

a = cv.waitkey(0)

if (a == 27 or ord('esc') == 27):
aborted = True
break

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文