gpt4 book ai didi

python - 在 Python 中查找箭头键的值 : Why are they triples?

转载 作者:IT老高 更新时间:2023-10-28 22:18:38 29 4
gpt4 key购买 nike

我正在尝试查找本地系统分配给箭头键的值,特别是在 Python 中。我正在使用以下脚本来执行此操作:

import sys,tty,termios
class _Getch:
def __call__(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch

def get():
inkey = _Getch()
while(1):
k=inkey()
if k!='':break
print 'you pressed', ord(k)

def main():
for i in range(0,25):
get()

if __name__=='__main__':
main()

然后我运行脚本,然后点击 UP DOWN RIGHT LEFT,这给了我这样的输出:

$ python getchar.py 
you pressed 27
you pressed 91
you pressed 65
you pressed 27
you pressed 91
you pressed 66
you pressed 27
you pressed 91
you pressed 67
you pressed 27
you pressed 91
you pressed 68

这是异常的,因为它表明箭头键在我的系统上注册为某种形式的三元组 (27-91-6x),因为每次按下箭头键都会占用三个 get() 实例。相比之下,按 a,b,c 和 CTRL-C 会得到:

you pressed 97
you pressed 98
you pressed 99
you pressed 3

谁能向我解释为什么我的箭头键的值似乎存储为三元组?为什么会这样?这在所有平台上都一样吗? (我使用的是 Debian Linux。)如果没有,我应该如何存储箭头键的值?

这里的最终目标是我正在尝试编写一个程序,该程序需要正确识别箭头键并根据按下的箭头键执行功能。

最佳答案

我想我明白了。

我从 here 学到的每个箭头键都由一个唯一的 ANSI 转义码表示。然后我了解到 ANSI 转义码因系统和应用程序而异:在我的终端中,点击 cat 并按向上箭头会得到 ^[[A,在 C 中似乎为 \033[A 等。后面的 [A 保持不变,但前面的 Escape 的代码可以可以是十六进制(以 x 开头)、八进制(以 0 开头)或十进制(数字中没有前导)。

然后我打开 python 控制台,插入我之前收到的三元组,试图找到它们的字符值。结果是,chr(27) 给了 \x1bchr(91) 给了 [,然后调用65,66,67,68 上的 chr 分别返回 A,B,C,D。然后很清楚: \x1b 是转义码!

然后我注意到一个箭头键,在 ANSI 中表示为三元组,当然表示为三个字符,所以我需要修改我的代码以便一次读取三个字符。结果如下:

import sys,tty,termios
class _Getch:
def __call__(self):
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(3)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch

def get():
inkey = _Getch()
while(1):
k=inkey()
if k!='':break
if k=='\x1b[A':
print "up"
elif k=='\x1b[B':
print "down"
elif k=='\x1b[C':
print "right"
elif k=='\x1b[D':
print "left"
else:
print "not an arrow key!"

def main():
for i in range(0,20):
get()

if __name__=='__main__':
main()

关于python - 在 Python 中查找箭头键的值 : Why are they triples?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22397289/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com