Python 程序中有箭头键的奇怪故障

Python 程序中有箭头键的奇怪故障,python,python-3.x,arrow-keys,Python,Python 3.x,Arrow Keys,因此,我的程序在这里从用户那里获取wasd或箭头键,否则它应该给出一个错误: import termios import tty, sys def getVal(): old = termios.tcgetattr(sys.stdin) tty.setcbreak(sys.stdin.fileno()) try: key = ord(sys.stdin.read(1)) while key not in [119, 97, 115, 100

因此,我的程序在这里从用户那里获取wasd或箭头键,否则它应该给出一个错误:

import termios
import tty, sys
def getVal():
    old = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    try:
        key = ord(sys.stdin.read(1))
        while key not in [119, 97, 115, 100, 65, 66, 67, 68]:
            print("Please enter w, a, s, or d OR arrow keys only.")
            key = ord(sys.stdin.read(1))

        if key == 119 or key == 65:
            print('up')
        elif key == 97 or key == 68:
            print('left')
        elif key == 115 or key == 66:
            print('down')
        elif key == 100 or key == 67:
            print('right')
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old)
while True:
    getVal()
wasd命令工作正常,但在本例中,当我尝试执行任何箭头键时,会出现向下键:

Please enter w, a, s, or d OR arrow keys only.
Please enter w, a, s, or d OR arrow keys only.
down

它给了我2个错误消息和一个down,尽管它应该只给出down消息。为什么会发生这种情况?

当按箭头键而不是文字键时,会生成三个值:27 escape,91,实际箭头键68。如果您读取的第一个值是27,那么您应该读取接下来的两个值,并仅解码最后一个值。您应该替换此行:

key = ord(sys.stdin.read(1))
与:


您可以在[119,97115,…]中输入键的同时编写代码,以使代码更具可读性。哦,感谢您想知道我能做些什么来修复这个问题。不必这样做,如果他们真的按了27或91中的任何一个键,就会出现错误。不,我的意思是,这两行中有两行做的事情完全相同,而且他们做错了。因此,将两者都替换。
key = ord(sys.stdin.read(1))
if key == 27:
    sys.stdin.read(1) # Skip the next character, must be 91
    key = ord(sys.stdin.read(1))