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.