Implementing C++'s getch() in Python

eryk sun eryksun at gmail.com
Sun May 26 11:17:44 EDT 2019


On 5/25/19, Paul Moore <p.f.moore at gmail.com> wrote:
>
> On Windows, the msvcrt module exposes getch:
> https://docs.python.org/3.7/library/msvcrt.html#msvcrt.getch

I suggest using msvcrt.getwch instead of msvcrt.getch. Both functions
are limited to the basic multilingual plane (BMP, i.e. U+0000 --
U+FFFF), but getch is additionally limited to the console input
codepage. In Windows, getpass.getpass is based on msvcrt.getwch and
msvcrt.putwch.

If you use getch and need the full BMP range, you can temporarily
change the console input codepage to UTF-8 (65001). It's a multibyte
encoding (i.e. 1-3 bytes per BMP code), so the initial getch call has
to be followed by a loop that calls it again while the sequence can't
be decoded and kbhit() is true.



More information about the Python-list mailing list