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

BartC bc at freeuk.com
Tue Oct 25 06:02:31 EDT 2016


On 25/10/2016 07:39, Steven D'Aprano wrote:

>> I gather that non-blocking keyboard input functions aren't the easiest thing
>> to implement.  They seem to depend on the operating system.  Still, ease of
>> use is a primary goal of Python, and the need for this feature must be
>> common.
>
>
> Not really. I think that lots of people think they need it, but once they write
> a little utility, they often realise that it's not that useful.

> If you (generic you, not you specifically) are telling the user "press any key
> to continue", then you probably shouldn't. *Any* key may not do anything. E.g.
> if the user hits the Shift key. A much better interface is to specify a
> specific key, and ignore anything else... in which case, why not specify the
> Enter key?
>
> raw_input('Press the Enter key to continue... ')

Which doesn't work on Python 3. So even here, making it easy by using 
line-input, it's not so straightforward.

> If you are doing something more complex, waiting on different keys to do
> different things,

You mean, something as sophisticated as press Enter to continue, or 
Escape to quit? Or Page Up and Page Down?

  then you probably should use an existing text UI like Curses,
> or a GUI like wxPython etc, rather than trying to reinvent the wheel badly.

But why the need to have to use someone else's massive great wheel? Both 
Curses and wxPython are completely over the top IMO for something so 
fundamental.

I started coding in 1976 (Christ, 40 years ago!), using teletypes. 
Getting line input was easy (apparently easier than in Python now!). 
What was hard was:

(1) Reading a single key-press without the user having to press
     Enter (or Return as it was then)

(2) Reading that single key-press without the character being echoed to
     the output

It seems like little has changed!

You needed this to do what I considered cool things. A bit limited on a 
TTY but on a video display, a lot more was possible (editors, games, etc).

As for actually reading from the keyboard, the first board I made that 
actually had one (it was gorgeous, with all sorts of exotic keys you 
didn't find on typewriters like !, [], {}, + and Ctrl), involved this:

* Poll the byte at some specific port until the top bit changed
   from 0 to 1. Then a key had just been pressed.

* The lower 7 bits was the ASCII value of the character (I don't
   know what it did about cursor keys, but maybe it didn't have any.)

This gives you the ability to do (2) above. From that, you could do (1) 
(echoing) and go on to build full line-orientated input. But you had 
complete control.

So, why has it all become so difficult?

-- 
Bartc



More information about the Python-list mailing list