[Tutor] Single char input
Mats Wichmann
mats at wichmann.us
Thu Oct 24 20:06:16 EDT 2019
On 10/23/19 10:06 AM, Ed Connell wrote:
> Hi,
> How can I accept, evaluate, and act on a single keypress in python?
> Example:
>
> Press A, B, or C
>
> A. Do something
>
> B. Do other thing
>
> C. Skip to next section
As others have said, but maybe not in these words: this is highly
context-dependent.
Thousands of man-years have been spent on making this kind of stuff work
in graphical frameworks, where react-to-a-keypress behavior is common -
if you're not on a command-line, you don't need to wait for the Enter
(aka Return) key to be pressed unless the context indicates it: if a
single key entry will do, then make that work; if you need a word or
sentence (or indeed an entire complaint letter to the bank who has just
messed up your account) to be typed you need something to indicate the
input is done, an that will typically be a submit button, or maybe an
enter key as is often the model with a social media post. So if a GUI
is what you're after, the framework you choose will undoubtedly help
with this. If it doesn't, pick a different framework (seriously: Python
seems to have support for about 6 times as many GUI frameworks as makes
any rational sense).
And if you're on the command line, the _convention_ is to wait for the
user to press Enter, because that's the standard indication the input is
done - y<Enter> is really not much more work than just pressing y by
itself.
It's dirt-simple in Windows, but comes at a cost, something like:
from msvcrt import getch
while True:
key = getch()
# decide what to do with key: break or continue
that means if you're looking for a keypress and can't do anything else
until it happens, you've not given anything up, but it's effectively a
blocking read so if you expect to do something else in the meantime, you
have to build a whole framework to handle that - see the GUI discussion!
This is in the pykbhit link that was in another reply, but it's spread
out in the multi-platform support so it's not as clear what it's doing.
As you'll have seen by the other answers it's quite a bit harder on
non-Windows platforms.
More information about the Tutor
mailing list