How do arrow keys work with getch? (they register as 3 keys)
Question: I'm using the `getch` code [from this stack overflow
question](http://stackoverflow.com/questions/510357/python-read-a-single-
character-from-the-user), 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?


Answer: 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).

