Why doesn't Python include non-blocking keyboard input function?

Nobody nobody at nowhere.invalid
Tue Oct 25 15:57:46 EDT 2016


On Mon, 24 Oct 2016 11:14:05 -0700, jladasky wrote:

> I gather that non-blocking keyboard input functions aren't the easiest
> thing to implement.  They seem to depend on the operating system.

Indeed. It's somewhat harder to implement one on an OS which doesn't take
it for granted that the system actually *has* a keyboard (i.e. Unix).

If you're willing to compromise and accept the use of a terminal rather
than a keyboard, the next question is whether to use the process'
controlling terminal, or the terminal associated with stdin (if both
exist, they're probably the same terminal, but aren't required to be).

Other complications include the fact that, if the process isn't part of
the terminal's foreground process group, attempting to read from the
terminal (even a non-blocking read) will typically suspend the process
(unless you ignore SIGTTIN). And also the fact that the terminal itself
may be line buffered, so the computer has no idea of what's being typed on
it until Return/Enter (or Send, etc) is pressed.

Aside from that, receiving key presses as they are entered means disabling
canonical mode in the tty driver (which buffers input until Return or
Ctrl-D are pressed, so that you can edit the input line with Backspace or
Ctrl-U). That affects all processes using the terminal.

If the current process is in the foreground process group, then processes
in other groups probably won't be reading from the terminal ... at least
until you suspend the forground process group with Ctrl-Z. So you need to
install signal handlers for SIGTSTP and SIGCONT to restore the terminal
settings when the process is suspended. But what should you do about any
existing handlers for those signals?

All things considered, requiring the user to use one of the keys that
generates a signal might be simpler. Or at least not using Esc, which is
about the worst possible choice, given that its normal function is
as a prefix for, well, just about every control sequence (i.e. what is
sent when you press a key which doesn't correspond to a printable
character).

tl;dr: Unix is not MS-DOS.




More information about the Python-list mailing list