I need to read the key pressed by user without waiting for enter. I want to read both the characters and arrow keys. The solution that I'm using is the same of this topic.
import sys,tty,termios
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(3)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
while(1):
k=getch()
if k=='\x1b[A':
print "up"
elif k=='\x1b[B':
print "down"
elif k=='\x1b[C':
print "right"
elif k=='\x1b[D':
print "left"
If I want to read arrow keys I use ch = sys.stdin.read(3)
, and if I want to read individual characters I use ch = sys.stdin.read(1)
, but I need to read both types of keys.
The rest of the script is written in Python 2.7 and will run on a Linux system.
Because I'm not the system admistrator, please don't suggest installing a new package.