Reputation: 5922
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.
Upvotes: 0
Views: 986
Reputation: 436
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!"
Upvotes: 1
Reputation: 36604
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()
Upvotes: 1