[Python-ideas] get(w)ch, non-letter keys, and cross-platform non-blocking input.

random832 at fastmail.us random832 at fastmail.us
Fri Aug 2 19:56:14 CEST 2013


The current behavior of getch and getwch on windows on receiving e.g.
the "up arrow" key is to return two values on subsequent calls: 0xE0
0x48. The problem, other than the obvious of being split across two
events, is that this cannot be distinguished between ordinary input of
the character 0xE0. For getwch, this is U+00E0 LATIN SMALL LETTER A WITH
GRAVE (followed by 0x48 'H'). For getch, ordinary values are returned in
the DOS character set (as defined with the chcp command), in which 0xE0
is various characters such as a greek alpha in cp437, a capital O with
acute in cp850, or a greek omega in cp737. This additionally makes getch
unusable as-is for non-ascii characters.

The obvious solution for windows is to write an entirely new function
that calls ReadConsoleInput and returns a "keypress event" object or
tuple instead of a single character.

On Unix, there's a different problem. The fact that text input is
byte-oriented means multiple bytes need to be read (necessitating
multiple read calls for unbuffered input) for a multibyte character, or
for an escape sequence for a non-graphical key. And if you're doing
non-blocking input, you would want a timeout in case the final byte of
the sequence never arrives. You may want a timeout anyway, to handle
manual input of ESC differently from the start of an escape sequence.
And handling escape sequences at all introduces a dependency on
terminfo. Or alternately, people may want a lighter solution like a
dictionary of escape sequences to meanings - or a heavier one like
parsing the sequences generated by xterm's modifyOtherKeys feature for
combinations not supported by terminfo [such as ctrl+shift+letter].


More information about the Python-ideas mailing list