0

I am trying to read keypresses from sys.stdin (without pressing enter)

I wrote a function to try and do this (getkey below) which is based on the first answer from this answer and this answer:

def _read(*a):
    import sys
    n = a[0] if a else 1
    return ord(sys.stdin.read(n))

def getkey():
    try:
        from msvcrt import getch
        return getch()
    except ImportError:
        import sys, tty, termios, select
        fd = sys.stdin.fileno()
        old_settings = tty.tcgetattr(fd)
        try:
            tty.setraw(fd)
            key = [_read()]
            while select.select([sys.stdin], [], [], 0.0)[0]:
                key.append(_read())
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return key

What I want this function to do when called is wait for a key to be pressed and to return the character code(s) that the key generated. For example:

  • Calling the function and pressing the A key should return [65].
  • Calling the function and pressing the key should return [27, 91, 65] (since pressing that key generates the escape sequence ESC[A).

The function works fine for keys like A that generate one character, however it seems that the function is only getting the first character as keys like only return [27].

Does anyone know what I may be doing wrong here?

0 Answers0