Search code examples
pythonkeyboard-eventsgetch

python using ord() with getch() to get unicode


i am learning python at the moment and i tried to get keyboard input, without the need to press the enter key with getch() and ord() in order to work with the (at least for me) gibberish that returns from getch().

in my understanding getch() returns a byte stream, and ord does translate that byte data into unicode. and if iam not wrong there are keys like the arrow keys (this is my intention, to build a cmd "ui" to navigate) that are seperated into different unicode values.

so far, after trying myself and searching the web i come up with a soultion, provided by a person on the internet(information only for not claimig someone elses code as mine)

import msvcrt

while True:
    key = ord(msvcrt.getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        print("select")
    elif key == 224: #thing i do not understand
        key = ord(msvcrt.getch()) #thing i do not understand
        if key == 80: #Down arrow
            print("moveDown")
        elif key == 72: #Up arrow
            print("moveUp")
        elif key == 77: #Right arrow
            print("moveRight")
        elif key == 75: #Left arrow
            print("moveLeft")

this works fine, but the thing that i do not understand is, why it is necessary to make the second variable assignment. in my understanding getch() should return the value instantly, so i do not understand where the second key = ord... statement gets the data to assign it to the key variable.

I would appreciate an explanation.


Solution

  • From the documentation for msvcrt.getch:

    msvcrt.getch()

    Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function.

    So, if a special function key (e.g. an arrow key) was pressed, we have to test for 0xE0 (224) and then read the next value.