0

Using Python 2.7, I'd like my program to accept Keyboard Arrow Keys – e.g. while inputting into MacOS Terminal.

Pressing in Terminal outputs ^[[A in it, so I've assumed this is the escape key sequence.

However, pressing the and RETURN at the raw_input() prompt doesn't seem to produce a string that can then be conditioned:

string = raw_input('Press ↑ Key: ')

if string == '^[[A':
    print '↑'         # This doesn't happen.

How can this be done?

Note that I'm not trying to input whatever the previous line was in the shell (I think this is was import readline manages). I just want to detect that an arrow key on the keyboard was entered somehow.

P A N
  • 5,642
  • 15
  • 52
  • 103
  • Obligatory notice that Python 2.7 [is officially no longer supported](https://www.python.org/doc/sunset-python-2/), and will no longer be receiving bug fixes, security updates, or changes of any kind. If at all possible, migrate to Python 3. – Brian61354270 Mar 08 '20 at 14:47

2 Answers2

1

I think you're looking for pynput.keyboard.Listener, which allows you to monitor the keyboard and to take different actions depending on the key that is pressed. It is available for Python 2.7.

This example is a good way to get started:

from pynput import keyboard

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

# ...or, in a non-blocking fashion:
listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
1

When I tried something like:

% cat test.py
char = raw_input()
print("\nInput char is [%s]." % char)
% python a.py
^[[A
           ].

It blanked out the "\Input char is [" part of the print statement. It appears that raw_input() does not receive escaped characters. The terminal program is catching the escaped keystrokes and using it to manipulate the screen. You will have to use a lower level program to catch these characters. Check out if Finding the Values of the Arrow Keys in Python: Why are they triples? help on how to get these keystrokes.

From the currently accepted answer:

    if k=='\x1b[A':
            print "up"
    elif k=='\x1b[B':
            print "down"
    elif k=='\x1b[C':
            print "right"
    elif k=='\x1b[D':
            print "left"
    else:
            print "not an arrow key!"
P A N
  • 5,642
  • 15
  • 52
  • 103
Perennial
  • 438
  • 3
  • 8
  • Thanks – the suggested escape code strings in the accepted answer works. E.g. `'\x1b[A'` is `↑`. – P A N Mar 08 '20 at 15:20