在 Python 中查找箭头键的值:为什么它们是三元组? [英] Finding the Values of the Arrow Keys in Python: Why are they triples?
问题描述
我正在尝试查找本地系统分配给箭头键的值,特别是在 Python 中.我正在使用以下脚本来执行此操作:
I am trying to find the values that my local system assigns to the arrow keys, specifically in Python. I am using the following script to do this:
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,这给了我这个输出:
Then I ran the script, and hit UP DOWN RIGHT LEFT, which gave me this output:
$ 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 会给出:
This is anomalous because it suggests that the arrow keys are registered as some form of triple (27-91-6x) on my system, as each press of an arrow key takes up three instances of get(). By comparison, pressing a,b,c and CTRL-C gives:
you pressed 97
you pressed 98
you pressed 99
you pressed 3
谁能向我解释为什么我的箭头键的值似乎存储为三元组?为什么会这样?这在所有平台上都一样吗?(我使用的是 Debian Linux.)如果不是,我应该如何存储箭头键的值?
Can anyone explain to me why the values of my arrow-keys seem to be stored as triples? Why is this is so? Is this the same across all platforms? (I'm using Debian Linux.) If not, how should I go about storing the values of the arrow-keys?
这里的最终目标是我正在尝试编写一个程序,该程序需要正确识别箭头键并根据按下的箭头键执行功能.
The end goal here is in that I'm trying to write a program which needs to correctly recognize arrow-keys and perform a function depending on which arrow-key was pressed.
推荐答案
我想我明白了.
我从此处了解到每个箭头键都由一个唯一的 ANSI 转义码表示.然后我了解到 ANSI 转义码因系统和应用程序而异:在我的终端中,点击 cat
并按向上箭头给出 ^[[A
,在 C 中似乎为