【问题标题】:Arrows keys for getch in python [duplicate]python中getch的箭头键[重复]
【发布时间】:2020-08-04 06:01:06
【问题描述】:

我想在 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

【问题讨论】:

  • @PalakodetiSaiVinay 用于 C,它用于 python。对于每种语言甚至软件包,解决方案都不同......
  • @Ahmad 很多 Python API 只是 C API 的包装器。如果您获得了对 C API 的引用,最好检查 Python 是否包装了它。检查 python 的行为是否相同。
  • @PhilipCouling 我用 python 搜索了一个解决方案,但没有找到简单可行的解决方案。我认为这可能是一个常见问题,应该得到这样的答案!许多人无法阅读很多技术知识来找出解决此类常见问题的方法!
  • 这个问题不是 C 的链接问题的重复,不应该这样标记。

标签: python linux arrow-keys getch


【解决方案1】:

他们是ANSI escape sequences

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

import getch as gh

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

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

27
91
65

引用ASCII table,可以看到对应ESC[A。它是 ANSI 转义序列中“Cursor UP”的代码。 (CSI 的顺序是ESC [,所以ESC[A == CSI A == CSI 1 A 表示“将光标向上移动一个单元格。”)

同样的方法,我们也可以找出其他方向键。


如果你想通过getch module来匹配方向键,你可以试试下面的代码(下面的get_key函数原来来自this answer):

import getch as gh


# The function below is originally from: https://stackoverflow.com/a/47378376/8581025
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

【讨论】:

  • 谢谢,我的意思是直接可行的解决方案,没有重复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-14
  • 2012-10-21
  • 2019-10-27
  • 1970-01-01
  • 2019-02-12
  • 2021-09-17
  • 1970-01-01
相关资源
最近更新 更多