GNU Readline for Python

8.3.3 · active · verified Tue Apr 14

gnureadline provides robust GNU Readline support for Python applications, particularly on platforms like macOS where the default `readline` module often links against `libedit` (NetBSD's Editline library), which is not fully GNU Readline compliant. It achieves this by bundling and statically linking the GNU Readline source code with Python's standard `readline` module. The library is actively maintained, with frequent updates to ensure compatibility with new Python versions and the underlying GNU Readline library; the current version is 8.3.3, released in January 2026.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to import and initialize `gnureadline` to provide enhanced command-line editing, history persistence, and tab completion for an interactive Python prompt. It shows how to use a `try-except` block to gracefully handle environments where `gnureadline` might not be installed, set up history file management, and register a custom completer function.

import atexit
import os

try:
    import gnureadline as readline
except ImportError:
    import readline

histfile = os.path.join(os.path.expanduser('~'), '.python_history')
try:
    readline.read_history_file(histfile)
    # Default history length is 500 lines. Adjust if needed.
    readline.set_history_length(1000)
except FileNotFoundError:
    pass

atexit.register(readline.write_history_file, histfile)

# Enable tab completion and other common bindings
readline.parse_and_bind('tab: complete')
readline.parse_and_bind('set editing-mode emacs') # or 'set editing-mode vi'

def completer(text, state):
    options = ['hello', 'world', 'apple', 'banana', 'orange', 'quit']
    matches = [s for s in options if s.startswith(text)]
    if state < len(matches):
        return matches[state]
    return None

readline.set_completer(completer)

print("Type 'quit' to exit. Use tab for completion.")
while True:
    try:
        line = input('Prompt> ')
        if line == 'quit':
            break
        print(f'You typed: {line}')
    except EOFError:
        break
    except KeyboardInterrupt:
        print(" (Press Ctrl-D or type 'quit' to exit)")

view raw JSON →