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

evamvid picture evamvid · Mar 12, 2014 · Viewed 20k times · Source

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

Answer

wizard23 picture wizard23 · Mar 12, 2014

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)