Search code examples
pythonwindowspython-3.xmsvcrtgetch

msvcrt.getch() detects space every time


Im writting a simple python code that should detect the my keystrokes but for some reason in detects space after everysingle keystroke.

The code:

import msvcrt

print("press 'escape' to quit...")
text=""
while 1:
    char = msvcrt.getch()
    print(ord(char))

Sample run:

Input: aaaaa

Output:
97
0
97
0
97
0
97
0
97
0

Solution

  • It's not detecting space. Space is 32, not 0.

    What's happening is that you're using a wide-character terminal, but reading it as bytes, so you're seeing the UTF-16-LE bytes. In UTF-16-LE, an a is two bytes, 97 and 0. If you read those as if they were two ASCII characters instead of one UTF-16-LE character, you'll get a followed by \0.

    Notice that what you get back isn't actually 'a\0a\0a\0', but b'a\0a\0a\0'. So you could buffer these up into a bytes or bytearray and use decode('utf-16-le') on it. But that defeats the purpose of reading one character at a time.

    The simplest fix is to use getwch instead of getch. This will mostly just do what you want—return a single-character str value like 'a' rather than two separate single-byte bytes values.

    There may still be some problems with astral characters (everything above U+FFFF) showing up as two separate surrogates instead of one single character, and "special keys" will still show up as a Unicode U+0000 or U+00E0 followed by a keycode (or, if you have an older Python, possibly as a broken U+E0xx with the keycode embedded in the character). But otherwise, it'll work the way you expected.