Processing a key pressed in Python 3.6

eryk sun eryksun at gmail.com
Tue Jan 23 20:09:23 EST 2018


On Tue, Jan 23, 2018 at 11:29 PM, Virgil Stokes <vs at it.uu.se> wrote:
>
> How would this code be modified to handle using the "Esc" key instead of the
> "Enter" key?

The input() function depends on the console or terminal to read a line
of input. If you're using the Windows console, it calls the high-level
ReadConsole (or ReadFile) function, which performs a 'cooked' read. In
this case some keys are reserved. Escape is consumed to clear/flush
the input buffer. Function keys and arrows are consumed for line
editing and history navigation. And for some reason line-feed (^J) is
always ignored. Additionally, normal operation requires the following
input modes to be enabled:

    ENABLE_PROCESSED_INPUT
        process Ctrl+C as CTRL_C_EVENT and carriage return (^M)
        as carriage return plus line feed (CRLF). consume
        backspace (^H) to delete the previous character.

    ENABLE_LINE_INPUT
        return only when a carriage return is read.

    ENABLE_ECHO_INPUT
        echo read characters to the active screen.

Reading the escape key from the console requires the low-level
ReadConsoleInput, GetNumberOfConsoleInputEvents, and
FlushConsoleInputBuffer functions. These access the console's raw
stream of input event records, which includes key events, mouse
events, and window/buffer resize events. It's a bit complicated to use
this API, but fortunately the C runtime wraps it with convenient
functions such as _kbhit, _getwch, and _getwche (w/ echo). On Windows
only, you'll find these functions in the msvcrt module, but named
without the leading underscore. Here's an example of reading the
escape character without echo:

    >>> msvcrt.getwch()
    '\x1b'

Simple, no?



More information about the Python-list mailing list