Python Windows `msvcrt.getch()` only detects every 3rd keypress?

独自空忆成欢 提交于 2019-12-17 19:25:14

问题


My code is below:

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 code is based on this question; I was using it to acquaint myself with getch.

I've noticed that it takes 3 pressing the key 3 times to output the text once. Why is this? I'm trying to use it as an event loop, and that's too much of a lag...

Even if I type 3 different keys, it only outputs the 3rd keypress.

How can I force it to go faster? Is there a better way to achieve what I'm trying to achieve?

Thanks!

evamvid


回答1:


you call the function 3 times in your loop. try calling it only once like this:

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)



回答2:


You can optimize things a little bit by also using themsvcrt.kbhit function which will allow you callmsvcrt.getch()only as much as is necessary:

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

Note that theKey Pressedvalue printed won't make sense for things like function keys. That's because it those cases it's really the Windows scan code for the key, not a regular key code for the character.



来源:https://stackoverflow.com/questions/22365473/python-windows-msvcrt-getch-only-detects-every-3rd-keypress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!