or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-readchar

Library to easily read single chars and key strokes

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/readchar@4.2.x

To install, run

npx @tessl/cli install tessl/pypi-readchar@4.2.0

index.mddocs/

Readchar

A cross-platform Python library for reading single characters and keystrokes from stdin without requiring the user to press Enter. It provides immediate character response without buffering, making it ideal for building interactive command-line applications, terminal user interfaces, and console-based input systems.

Package Information

  • Package Name: readchar
  • Language: Python
  • Installation: pip install readchar
  • Python Versions: 3.8+
  • Platforms: Linux, Windows, macOS, FreeBSD, OpenBSD

Core Imports

import readchar

Import specific functions:

from readchar import readchar, readkey, key, config

Basic Usage

import readchar
from readchar import key

# Read a single character
char = readchar.readchar()
print(f"You pressed: {char}")

# Read a complete keystroke (including special keys)
keystroke = readchar.readkey()
if keystroke == key.UP:
    print("Up arrow pressed")
elif keystroke == key.ENTER:
    print("Enter pressed")
elif keystroke == "q":
    print("Q pressed")

Interactive example:

from readchar import readkey, key

print("Press arrow keys to move, 'q' to quit:")
while True:
    k = readkey()
    if k == "q":
        break
    elif k == key.UP:
        print("Moving up")
    elif k == key.DOWN:
        print("Moving down") 
    elif k == key.LEFT:
        print("Moving left")
    elif k == key.RIGHT:
        print("Moving right")
    elif k == key.ENTER:
        print("Action!")

Capabilities

Character Reading

Reads single characters from stdin with immediate response, without waiting for Enter key.

def readchar() -> str:
    """
    Reads a single character from stdin, returning it as a string with length 1.
    Blocks until a character is available.
    
    Returns:
        str: Single character string
        
    Note:
        Only returns single ASCII characters. For complete keystrokes including
        multi-character escape sequences, use readkey().
    """

Keystroke Reading

Reads complete keystrokes including multi-character escape sequences for special keys like arrows, function keys, and key combinations.

def readkey() -> str:
    """
    Reads the next keystroke from stdin, returning it as a string.
    Blocks until a keystroke is available.
    
    Returns:
        str: Complete keystroke string, either:
            - Single character for normal keys (a, Z, 9, space, etc.)
            - Multi-character escape sequence for special keys (arrows, F1-F12, etc.)
            - Control combinations (Ctrl+A, Alt+A, etc.)
    
    Raises:
        KeyboardInterrupt: When interrupt keys are pressed (default: Ctrl+C)
        
    Note:
        Multi-character sequences are platform-specific but abstracted through
        the key module constants for cross-platform compatibility.
    """

Key Constants

Platform-specific key constants for comparing against readkey() results. The constants are defined based on the operating system for full portability.

# Access pattern
from readchar import key

# Common constants available on all platforms:
key.LF          # Line feed (\n)
key.CR          # Carriage return (\r) 
key.SPACE       # Space character
key.ESC         # Escape key
key.TAB         # Tab key
key.ENTER       # Enter key (platform-specific alias)
key.BACKSPACE   # Backspace key (platform-specific)

# Control key combinations - all available
key.CTRL_A      # Ctrl+A
key.CTRL_B      # Ctrl+B
key.CTRL_C      # Ctrl+C (default interrupt key)
key.CTRL_D      # Ctrl+D
key.CTRL_E      # Ctrl+E
key.CTRL_F      # Ctrl+F
key.CTRL_G      # Ctrl+G
key.CTRL_H      # Ctrl+H
key.CTRL_I      # Ctrl+I (alias for TAB)
key.CTRL_J      # Ctrl+J (alias for LF)
key.CTRL_K      # Ctrl+K
key.CTRL_L      # Ctrl+L
key.CTRL_M      # Ctrl+M (alias for CR)
key.CTRL_N      # Ctrl+N
key.CTRL_O      # Ctrl+O
key.CTRL_P      # Ctrl+P
key.CTRL_Q      # Ctrl+Q
key.CTRL_R      # Ctrl+R
key.CTRL_S      # Ctrl+S
key.CTRL_T      # Ctrl+T
key.CTRL_U      # Ctrl+U
key.CTRL_V      # Ctrl+V
key.CTRL_W      # Ctrl+W
key.CTRL_X      # Ctrl+X
key.CTRL_Y      # Ctrl+Y
key.CTRL_Z      # Ctrl+Z

# Arrow keys
key.UP          # Up arrow
key.DOWN        # Down arrow  
key.LEFT        # Left arrow
key.RIGHT       # Right arrow

# Navigation keys
key.INSERT      # Insert key
key.DELETE      # Delete key (alias for SUPR)
key.SUPR        # Delete key
key.HOME        # Home key
key.END         # End key
key.PAGE_UP     # Page Up
key.PAGE_DOWN   # Page Down

# Function keys - all available
key.F1          # F1 key
key.F2          # F2 key
key.F3          # F3 key
key.F4          # F4 key
key.F5          # F5 key
key.F6          # F6 key
key.F7          # F7 key
key.F8          # F8 key
key.F9          # F9 key
key.F10         # F10 key
key.F11         # F11 key
key.F12         # F12 key

# Platform-specific additional keys may be available
# POSIX systems (Linux/macOS/BSD):
key.SHIFT_TAB   # Shift+Tab
key.ALT_A       # Alt+A
key.CTRL_ALT_A  # Ctrl+Alt+A
key.CTRL_ALT_SUPR  # Ctrl+Alt+Delete

# Windows systems:
key.ESC_2       # Alternative escape sequence
key.ENTER_2     # Alternative enter sequence

Configuration

Static configuration class for customizing library behavior, particularly interrupt key handling.

class config:
    """
    Static configuration class containing constants used throughout the library.
    Cannot be instantiated - use class attributes directly.
    
    Attributes:
        INTERRUPT_KEYS (List[str]): List of keys that will cause readkey() 
                                   to raise KeyboardInterrupt.
                                   Default: [key.CTRL_C]
    """
    
    INTERRUPT_KEYS: List[str]  # Keys that trigger KeyboardInterrupt
    
    def __new__(cls):
        """Raises SyntaxError - instances cannot be created."""
        raise SyntaxError("you can't create instances of this class")

Usage example:

from readchar import readkey, key, config

# Customize interrupt keys
config.INTERRUPT_KEYS = [key.CTRL_C, key.ESC]

# Now both Ctrl+C and Esc will raise KeyboardInterrupt
try:
    k = readkey()
except KeyboardInterrupt:
    print("Interrupted!")

Platform Behavior

The library automatically detects the platform and uses appropriate low-level system calls:

  • POSIX systems (Linux, macOS, FreeBSD, OpenBSD): Uses termios for raw terminal input
  • Windows systems (win32, cygwin): Uses msvcrt.getwch() for console input
  • Unsupported platforms: Raises NotImplementedError

Key constants are defined differently per platform but provide consistent names for cross-platform compatibility. The same code works across all supported platforms without modification.

Error Handling

  • KeyboardInterrupt: Raised by readkey() when keys in config.INTERRUPT_KEYS are pressed (default: Ctrl+C)
  • NotImplementedError: Raised on unsupported platforms
  • SyntaxError: Raised when attempting to instantiate the config class

Types

from typing import List

# Module exports
__all__ = ["readchar", "readkey", "key", "config"]

# Type hints are included - functions return str
def readchar() -> str: ...
def readkey() -> str: ...

# Config attribute type
config.INTERRUPT_KEYS: List[str]