Python - getch() and kbhit()
Steve Litt
slitt at troubleshooters.com
Wed Jan 10 01:37:38 IST 2018
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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: getch_unix.py
Type: application/octet-stream
Size: 20 bytes
Desc: not available
URL: <http://mailman.cs.huji.ac.il/pipermail/linux-il/attachments/20180109/fd81b604/getch_unix.py>
More information about the Linux-il
mailing list