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.
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!"