0

I'm using the getch code from this stack overflow question, and I've written the following script:

getch = _Getch()
while(1):
   test = getch()
   if test == 'm':
      break
   else:
      print ord(test)

as you can see, it prints the ascii value of each input. So a sample output looks like this, where >>> represents my input:

>>>a
97
>>>ctrl-c
3
>>>Esc
27

So far so good, but when I press an arrow key, it gives me:

>>>(Left arrow)
27
91
66
>>>(right arrow)
27
91
67

So I can see that 27 is the escape char, but what is 91? 66 and 67 must be sub values of this.

I'm looking for the values so that I can implement them to use the arrows to move a cursor. How would I use this in an if charvalue == scenario?

Community
  • 1
  • 1
jfa
  • 1,047
  • 3
  • 13
  • 39
  • 1
    To write complex text user interfaces it's simply better to use the `curses` library which allows you to do *much* fancier stuff. Also it's quite portable between terminals and OSes. – Bakuriu Apr 02 '14 at 17:14
  • Looks like someone else ran into [the same issue](http://stackoverflow.com/questions/22397289/finding-the-values-of-the-arrow-keys-in-python-why-are-they-triples?rq=1). – thegrinner Apr 02 '14 at 17:24
  • 1
    Possible duplicate of [Finding the Values of the Arrow Keys in Python: Why are they triples?](https://stackoverflow.com/q/22397289/608639) – jww Jun 02 '18 at 17:40

1 Answers1

0

You can also use a combination of select, tty and termios.

import sys, select, tty, termios

class NonBlockingConsole(object):
    def __enter__(self):
        self.old_settings = termios.tcgetattr(sys.stdin)
        tty.setcbreak(sys.stdin.fileno())
        return self

    def __exit__(self, type, value, traceback):
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)

    def get_data(self):
        try:
            if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
                return sys.stdin.read(1)
        except KeyboardInterrupt:
            return '[CTRL-C]'
        return False

with NonBlockingConsole() as nbc:
    while 1:
        c = nbc.get_data()
        if c:
            c = c.decode('latin-1', 'replace')
            if c == '\x1b': # x1b is ESC
                break
            elif c in ('\x7f', '\x08'): # backspace
                pass
            elif c == '[CTRL-C]':
                pass
            elif c == '\n': # it's RETURN
                pass
            else:
                print('Pushed:',c)
        sleep(0.025)

Havn't tested it in a while and i'm on a Windows machine at the moment, but it might be able to capture arrow-keys as well (it should).

Torxed
  • 22,866
  • 14
  • 82
  • 131