Does one have to use curses to read single characters from keyboard?

Oscar Benjamin oscar.j.benjamin at gmail.com
Sun Dec 11 12:19:53 EST 2022


On Sun, 11 Dec 2022 at 15:55, Chris Green <cl at isbd.net> wrote:
>
> Is the only way to read single characters from the keyboard to use
> curses.cbreak() or curses.raw()?  If so how do I then read characters,
> it's not at all obvious from the curses documentation as that seems to
> think I'm using a GUI in some shape or form.
>
> All I actually want to do is get 'Y' or 'N' answers to questions on
> the command line.
>
> Searching for ways to do this produces what seem to me rather clumsy
> ways of doing it.

What you are asking for is known as getch. On Windows Python's msvcrt
module provides precisely this function. There are ways to do it on
non-Windows platforms but nothing as simple as the getch function is
in the stdlib. Some modules and recipes are available which I guess it
what you've already seen:

https://pypi.org/project/getch/
https://github.com/joeyespo/py-getch
https://stackoverflow.com/questions/510357/how-to-read-a-single-character-from-the-user

This seems to be the most well maintained option:
https://pypi.org/project/readchar/

I've often thought that getch was a good candidate for the stdlib.
There are plenty of recipes around but it would ideally just be
available as a cross platform function. Using curses would have been
overkill in any of my use cases where I really just wanted getch to
make a more efficient interface for a terminal program having some
limited interactivity. Actually slightly more than getch is readchar's
readkey which also works for pressing non-character keys. There were
times in the past where I might have used that if I'd known about it.

--
Oscar


More information about the Python-list mailing list