Search code examples
pythonlinuxarrow-keysgetch

Arrows keys for getch in python


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

Solution

  • 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