1

I want to capture arrow keys in 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")

When I run the code above and hit arrow keys, I get the following chars, what are they and how can I match one?

27

1
[
66
B
27

1
[
67
C
27

1
[
65
A
Ahmad
  • 8,811
  • 11
  • 76
  • 141
  • [Refer to this Stack Overflow Post](https://stackoverflow.com/questions/2876275/what-are-the-ascii-values-of-up-down-left-right) – Sai Vinay Palakodeti Aug 04 '20 at 06:07
  • 1
    @PalakodetiSaiVinay that is for C, it's for python. For every language and even the package the solution differ.... – Ahmad Aug 04 '20 at 06:35
  • @Ahmad A lot of Python API is just a wrapper for C API. If you are given a reference to C API it's best to check if Python wraps it. Check if python behaves the same. – Philip Couling Aug 04 '20 at 08:15
  • 1
    @PhilipCouling I searched for a solution with python and found no straightforward and workable one. I think this could be a common question and deserve such an answer! many can't read many technical things to figure out a solution for such a common question! – Ahmad Aug 04 '20 at 09:16
  • 1
    This question is not a duplicate of the linked question for C, and should not have been marked as such. – Jorge Aranda Dec 23 '21 at 00:27

1 Answers1

3

They are ANSI escape sequences.

When we execute the code below in a terminal:

import getch as gh

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

it prints the following when we hit the arrow up key once:

27
91
65

Referring 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 CSI is ESC [, so ESC[A == CSI A == CSI 1 A which means "Moves the cursor one cell in the up direction.")

In the same way, we can figure out the other arrow keys also.


If you want to match arrow keys by using the getch module, you can try the following code (get_key function below is originally from 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)

which prints the following when we press q

up
down
left
right
q
Gorisanson
  • 2,202
  • 1
  • 9
  • 25
  • Thanks, that's what I meant as straightforward workable solution, which has no duplicate! – Ahmad Aug 04 '20 at 09:20