Where to Place the `readkey()` Function in the Python Standard Library?

Topic: Consoles/Terminals

Where to Place the readkey() Function in the Python Standard Library?

While using Python, I noticed the absence of a built-in method to read keyboard key presses directly. Although I discovered a method for reading keyboard presses on Windows, I believe a standard approach should be included in the Python Standard Library to eliminate the need for redistributing such an essential function.

My question is: If I were to contribute and integrate this functionality, where in the Python Standard Library should it be placed? Specifically, which module or source file would be most suitable for a function like readkey() that reads keyboard input instead of the whole line like Python built-in input() function does?

Here is an example of a keyboard key reading function for Windows Operating Systems:

# Import the msvcrt module
import msvcrt

# Function to read characters without pressing enter
def read_chars():
    print("Press 'q' to exit.")
    while True:
        if msvcrt.kbhit():
            char = msvcrt.getch().decode('utf-8')
            if char == 'q':
            print(f'You pressed: {char}')

# Call the function

Notable references
For some time I’ve used the built-in input() function.

Use msvcrt.getwch() instead of msvcrt.getch().decode('utf-8'). The latter mistakenly assumes that the output encoding of the console is currently set to UTF-8 (i.e. Windows code page 65001). msvcrt.getwch() uses the console’s wide-character API to read the character as Unicode, and it’s always correct.

1 Like