On this page
  1. readline
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Persisting History Across CLI Sessions
  7. Gotchas & Boundaries
  8. Common Functions
  9. Constants & Attributes

readline

Prev: re | Up: stdlib_module | Next: reprlib
Rel: string, re, difflib, textwrap, unicodedata
Ref: docs.python.org — readline
Tags: #public #python3 #stdlib


Import

import readline

Overview

Python interface to the GNU Readline (or macOS libedit) line-editing library. Importing readline automatically equips input(), cmd, and the interactive Python REPL with arrow-key navigation, persistent command history, and programmable tab completion.

Quick Start

import readline

# Enable basic tab completion
COMMANDS = ["status", "start", "stop", "restart"]

def completer(text: str, state: int) -> str | None:
    matches = [c for c in COMMANDS if c.startswith(text)]
    return matches[state] if state < len(matches) else None

readline.set_completer(completer)
# Note: libedit (macOS) vs GNU readline use different bind syntax
if "libedit" in (readline.__doc__ or ""):
    readline.parse_and_bind("bind ^I rl_complete")
else:
    readline.parse_and_bind("tab: complete")

Implementation Walkthrough

1. Persisting History Across CLI Sessions

Pair read_history_file() with atexit and write_history_file() so users keep their history across runs:

import atexit
from pathlib import Path
import readline

def setup_history(history_path: Path, max_entries: int = 500) -> None:
    readline.set_history_length(max_entries)
    if history_path.exists():
        readline.read_history_file(str(history_path))
    atexit.register(readline.write_history_file, str(history_path))

Gotchas & Boundaries

Common Functions

Constants & Attributes

Linked from

Related notes