python 中 getch 的方向键

Arrows keys for getch in python

我想在 python linux:

中捕获方向键
   import getch as gh
   ch = ''
   while ch != 'q':
       print(ch)
       ch = gh.getch()
       k = ord(ch)
       print(k)
       # my question is:
       if k or ch = ???
          print("up")

当我 运行 上面的代码并按下箭头键时,我得到以下字符,它们是什么以及如何匹配一个?

27

1
[
66
B
27

1
[
67
C
27

1
[
65
A

他们是ANSI escape sequences

当我们在terminal中执行下面的代码时:

import getch as gh

ch = ''
while ch != 'q':
    ch = gh.getch()
    print(ord(ch))

当我们按下向上箭头 键一次时,它会打印以下内容:

27
91
65

引用 ASCII table, we can see that it corresponds to ESC[A. It is the code for "Cursor UP" in ANSI escape sequences. (The sequence for CSIESC [,所以 ESC[A == CSI A == CSI 1 A 意思是“将光标向上移动一个单元格.")

同理,我们也可以算出其他方向键。


如果您想使用 getch module, you can try the following code (get_key function below is originally from 来匹配方向键:

import getch as gh


# The function below is originally from: 
def get_key():
    first_char = gh.getch()
    if first_char == '\x1b':
        return {'[A': 'up', '[B': 'down', '[C': 'right', '[D': 'left'}[gh.getch() + gh.getch()]
    else:
        return first_char


key = ''
while key != 'q':
    key = get_key()
    print(key)

当我们按 时打印以下内容→q

up
down
left
right
q