【问题标题】:Python Windows `msvcrt.getch()` only detects every 3rd keypress?Python Windows `msvcrt.getch()` 仅检测每 3 次按键?
【发布时间】:2014-04-17 09:52:00
【问题描述】:

我的代码如下:

import msvcrt
while True:
    if msvcrt.getch() == 'q':    
       print "Q was pressed"
    elif msvcrt.getch() == 'x':    
       sys.exit()
    else:
       print "Key Pressed:" + str(msvcrt.getch()

此代码基于this question;我用它来认识getch

我注意到需要 3 次按键 3 次才能输出一次文本。为什么是这样?我正在尝试将其用作事件循环,这太滞后了...

即使我键入 3 个 不同的 键,它也只会输出第三个按键。

我怎样才能让它跑得更快?有没有更好的方法来实现我想要实现的目标?

谢谢!

伊夫维德

【问题讨论】:

    标签: python python-2.7 msvcrt event-loop getch


    【解决方案1】:

    您在循环中调用该函数 3 次。尝试像这样只调用一次:

    import msvcrt
    while True:
        pressedKey = msvcrt.getch()
        if pressedKey == 'q':    
           print "Q was pressed"
        elif pressedKey == 'x':    
           sys.exit()
        else:
           print "Key Pressed:" + str(pressedKey)
    

    【讨论】:

    • 为什么是'var pressKey = msvcrt.getch()'?不要认为它是有效的 python 语法
    • @wizard23 可能戴着他的 JavaScript 帽子,但他的想法是正确的。只需删除var
    • 我看到答案已经确定了:) tnx!是的 js 溜进来了...我无法现场测试它,因为我这里没有 Windows,而且 msvcrt 是特定于 win32 的 ;)
    【解决方案2】:

    您还可以通过使用msvcrt.kbhit 函数来稍微优化一下,这将允许您只在必要时调用msvcrt.getch()

    while True:
        if msvcrt.kbhit():
            ch = msvcrt.getch()
            if ch in '\x00\xe0':  # arrow or function key prefix?
                ch = msvcrt.getch()  # second call returns the scan code
            if ch == 'q':
               print "Q was pressed"
            elif ch == 'x':
               sys.exit()
            else:
               print "Key Pressed:", ch
    

    请注意,打印的Key Pressed值对于功能键之类的东西没有意义。那是因为在这些情况下,它实际上是 Windows scan code 的键,而不是字符的常规键码。

    【讨论】:

    • “msvcrt.khbit()”究竟是如何工作的?它是否只在检测到按键时才调用mscvrt.getch()
    • 我不知道细节,它是 MS C/C++ 运行时库的一部分。它不调用mscvrt.getch()AFAIK,它只是告诉您是否有可用的密钥。击键由操作系统和键盘硬件缓冲。
    • 请注意,通过使用扫描码表,您可以检测除常规键之外的功能键和箭头键。
    • 我不会称之为优化。事实上,当代码中有if msvcrt.kbhit(): 时,它会使用更多的CPU。尝试删除 if msvcrt.kbhit():,您会看到 CPU 使用率要小得多(getch() 会阻塞,因此您建议的没有 if msvcrt.kbhit(): 的代码使用的 CPU 会少得多)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    相关资源
    最近更新 更多