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

John Pote johnpote at jptechnical.co.uk
Tue Oct 25 05:51:28 EDT 2016


If you are on a windows platform you could use kbhit() from the msvcrt 
module as Steven D does in his solution on the activestate site which 
also works for xNIX. Worth a look at his code to see how these sort of 
things are done on xNIX.

Alternatively you could use a couple of threads. One for your worker 
code and one for the keyboard entry code. Use a message queue to pass 
received lines from the keyboard thread to the worker thread. OK you 
still have to press Enter but you don't need the windows msvcrt library 
or xNIX termios modules.

Regards

John


On 25/10/2016 07:39, Steven D'Aprano wrote:
> On Tuesday 25 October 2016 05:14, jladasky at itu.edu wrote:
>
>> After reading this rather vague thread...
>>
>> https://groups.google.com/forum/#!topic/comp.lang.python/FVnTe2i0UTY
>>
>> ... I find myself asking why Python doesn't include a standard, non-blocking
>> keyboard input function.  I have often wanted one myself.  The only way that
>> I've ever achieved this behavior is:
>>
>> 1) by restricting the user to pressing Ctrl-C while the program is running,
>> and catching a KeyboardInterrupt; or
>>
>> 2) loading a heavyweight GUI like wxPython or PyQt, and using its event loop
>> to intercept keyboard events.
>>
>> 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. That's just my
> opinion, and I'm one of those guys who wrote one:
>
> http://code.activestate.com/recipes/577977-get-single-keypress/?in=user-4172944
>
> Me and ten thousand others.
>
> 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... ')
>
>
> If you are doing something more complex, waiting on different keys to do
> different things, 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.
>
>
>




More information about the Python-list mailing list