0

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.

  • Okay, can you paste your code? – cs95 Jun 24 '17 at 13:03
  • You may want to read [ask] and [mcve], and re-word your question accordingly. – boardrider Jun 24 '17 at 13:18
  • Use the `curses` module: https://stackoverflow.com/questions/10693256/how-to-accept-keypress-in-command-line-python. You don't need to be an admin to install packages - you can install them in your home directory, into a virtualenv or unpack the module into your source root – Alastair McCormack Jun 25 '17 at 18:23

0 Answers0