readchar - Read Single Characters and Key Strokes
readchar is a Python library designed to easily read single characters and key strokes from the terminal, making it suitable for interactive command-line applications. It provides functions to capture individual key presses, including special keys like arrow keys and Enter. The current version is 4.2.2, and the library maintains an active release cadence, frequently incorporating fixes and new features.
Warnings
- breaking readchar dropped support for Python 3.6 in v4.0.4 and Python 3.7 in v4.0.6. If you are using these EOL Python versions, you must pin an older version of readchar.
- breaking Unicode support was significantly improved and implemented in v4.2.0. Prior versions might not correctly handle or display non-ASCII characters, leading to unexpected behavior or errors.
- gotcha `readchar()` and `readkey()` return different types of values. `readchar()` always returns a single-character string. `readkey()` returns a `Key` enum member for special keys (like `Key.UP`, `Key.ENTER`) and a string for regular characters. Mixing them up without type checking is a common mistake.
- gotcha Both `readchar()` and `readkey()` are blocking functions. They will pause program execution until a key is pressed. This might not be suitable for applications requiring non-blocking input without additional asynchronous programming or threading.
Install
-
pip install readchar
Imports
- readchar
from readchar import readchar
- readkey
from readchar import readkey
- Key
from readchar import Key
Quickstart
from readchar import readchar, readkey, Key
import sys
print("Press any key to read a char (e.g., 'a', 'b', '1'): ", end="", flush=True)
char_input = readchar()
print(f"\nYou pressed: '{char_input}'")
print("\nPress a key (e.g., 'Enter', 'Space', 'Arrow Up'): ", end="", flush=True)
key_input = readkey()
if isinstance(key_input, Key):
print(f"\nYou pressed a special key: {key_input.name}")
else:
print(f"\nYou pressed a regular key: '{key_input}'")
print("\nExiting.")