readchar - Read Single Characters and Key Strokes

4.2.2 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `readchar()` to get a single character and `readkey()` to capture individual key strokes, including special keys represented by the `Key` enum. It also shows how to differentiate between regular characters and special keys when using `readkey()`.

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.")

view raw JSON →