python 使用 ord() 和 getch() 获取 unicode

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

我目前正在学习 python,我尝试获取键盘输入,无需使用 getch()ord() 按下回车键即可使用(至少对我而言)return 来自 getch().

的胡言乱语

在我的理解中 getch() return 是一个字节流,并且 ord 确实将该字节数据转换为 unicode。如果我没记错的话,会有像箭头键这样的键(这是我的意图,build cmd“ui”来导航)被分成不同的 unicode 值。

到目前为止,在自己尝试和搜索网络后,我想出了一个解决方案,由互联网上的人提供(信息仅供不要将别人的代码声称为我的代码)

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")

这工作正常,但我不明白的是,为什么有必要进行第二个变量赋值。在我的理解中 getch() 应该立即 return 值,所以我不明白第二个 key = ord... 语句从哪里获取数据以将其分配给关键变量。

我将不胜感激。

来自 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 '[=11=]0' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function.

因此,如果按下了一个特殊的功能键(例如箭头键),我们必须测试 0xE0 (224) 然后读取下一个值。