Python - getch() and kbhit()

Python - getch() and kbhit()

Shlomo Solomon shlomo.solomon at gmail.com
Wed Jan 10 10:46:47 IST 2018


Hi Steve,

It seems something was wrong with your attachment - all I see is:
./netneut_right.svg

In reply to what you wrote, I was not looking for speed, efficiency or
a way to eliminate a bottleneck, but to get as close to possible to a
"drop in solution" to reproduce kbhit() and getch(). 
Why? 
Because as part of my teaching job I have to grade student submissions.
The task my students had this week was a chat program and in order not
to interfere with the actual sending of data over a socket, they need
to use a non-blocking solution to get user input. Since they all used
kbhit() and getch() under Windows, I needed to be able to make minimal
changes to their submitted code. I cannot penalize them for using
Windows, but on the other hand, re-writing their code would defeat the
purpose of checking their homework.



On Tue, 9 Jan 2018 18:37:38 -0500
Steve Litt <slitt at troubleshooters.com> wrote:

> On Tue, 9 Jan 2018 10:36:51 +0200
> Shlomo Solomon <shlomo.solomon at gmail.com> wrote:
> 
> > Since import msvcrt in Python is Windows specific, I adapted some
> > code I found to provide kbhit() and getch() in Python under Linux.
> > 
> > I'm attaching KBHIT.py which replaces msvcrt and a small program to
> > demonstrate how to use it - KBHIT-test.py.
> > 
> > The KBHIT.py documentation includes usage instructions and also a
> > link to the code I borrowed and (I hope) improved. 
> > 
> > 
> 
> I've been using the attached code in my UMENU2 program so menu choices
> can be selected with a single keystroke and no Enter key necessary.
> What you've added is kbhit() so you can do non-blocking keyboard
> reads, and of course the ability to handle both Posix and Windows
> transparently.
> 
> If I were to rewrite your KBHIT.py program, I'd rewrite it to carry a
> lot less state. I'd get rid of _init_(), and I'd make getch(), kbhit()
> and set_normal_term() class functions so the only reason for making
> it a class is namespacing. The world's fastest typist is what,  200
> wpm which is about 3.1/second: There's plenty of time to go raw and
> then go cooked for each character retrieved. It doesn't seem as
> efficient, but the bottleneck is the typist and going raw then cooked
> on each keystroke makes your code simpler, eliminates state, and
> probably decreases the need for set_norm_term().
>  
> SteveT
> 
> Steve Litt 
> December 2017 featured book: Thriving in Tough Times
> http://www.troubleshooters.com/thrive



-- 
Shlomo Solomon
http://the-solomons.net
Claws Mail 3.11.1 - KDE 4.14.30 - Dolphin 4.14.3 - LINUX Mageia 5



More information about the Linux-il mailing list