Python readline Module

In this guide, you'll explore Python's readline module, which enhances command-line input. Learn its features and examples for interactive input handling.

The readline module in Python provides an interface to the GNU Readline library, which allows for command-line text input, including features such as line editing, history substitution, and auto-completion. This module is commonly used to enhance the user experience in command-line applications by providing features typically found in interactive shells.

Table of Contents

  1. Introduction
  2. Enabling readline
  3. History Management
    • Adding Commands to History
    • Loading and Saving History
    • Accessing History Items
  4. Line Editing and Completion
    • Configuring Auto-Completion
  5. Examples
    • Basic Usage
    • Managing Command History
    • Custom Auto-Completion
  6. Real-World Use Case
  7. Conclusion
  8. References

Introduction

The readline module is designed to provide command-line editing and history capabilities in Python applications. It leverages the GNU Readline library, offering advanced features such as line editing, history tracking, and auto-completion, which can greatly improve the interactivity and usability of command-line programs.

Enabling readline

To enable the readline module, simply import it in your script:

import readline

Once imported, the module will automatically enhance the input functions (input() and raw_input()) with line editing and history capabilities.

History Management

The readline module provides several functions for managing command history.

Adding Commands to History

Commands entered in the input prompt can be added to the history list.

import readline

readline.add_history("first command")
readline.add_history("second command")

Loading and Saving History

You can save the command history to a file and load it back into a new session.

import readline

# Save history to a file
readline.write_history_file("history.txt")

# Load history from a file
readline.read_history_file("history.txt")

Accessing History Items

Retrieve items from the history list.

import readline

# Get the number of items in the history
history_length = readline.get_current_history_length()

# Access a specific history item
first_command = readline.get_history_item(1)
print(f"First command: {first_command}")

Line Editing and Completion

The readline module provides functions for configuring line editing and auto-completion.

Configuring Auto-Completion

Set up custom auto-completion for command-line inputs.

import readline

def completer(text, state):
    options = [cmd for cmd in ['start', 'stop', 'status', 'restart'] if cmd.startswith(text)]
    if state < len(options):
        return options[state]
    return None

readline.set_completer(completer)
readline.parse_and_bind("tab: complete")

Examples

Basic Usage

Enable readline in a simple input loop.

import readline

while True:
    try:
        line = input("Prompt> ")
        if line == "exit":
            break
        print(f"Input: {line}")
    except EOFError:
        break

Managing Command History

Demonstrate adding, saving, and loading command history.

import readline

readline.add_history("first command")
readline.add_history("second command")

# Save history to a file
readline.write_history_file("history.txt")

# Clear current history
readline.clear_history()

# Load history from a file
readline.read_history_file("history.txt")

# Access history items
history_length = readline.get_current_history_length()
for i in range(1, history_length + 1):
    print(f"History {i}: {readline.get_history_item(i)}")

Custom Auto-Completion

Set up custom auto-completion for a simple command-line interface.

import readline

def completer(text, state):
    options = [cmd for cmd in ['start', 'stop', 'status', 'restart'] if cmd.startswith(text)]
    if state < len(options):
        return options[state]
    return None

readline.set_completer(completer)
readline.parse_and_bind("tab: complete")

while True:
    try:
        line = input("Command> ")
        if line == "exit":
            break
        print(f"Command: {line}")
    except EOFError:
        break

Real-World Use Case

Enhancing a Command-Line Tool

Suppose you are developing a command-line tool for managing services. Using the readline module, you can add features like command history and auto-completion to improve the user experience.

import readline

def completer(text, state):
    options = [cmd for cmd in ['start', 'stop', 'status', 'restart'] if cmd.startswith(text)]
    if state < len(options):
        return options[state]
    return None

readline.set_completer(completer)
readline.parse_and_bind("tab: complete")

# Load command history from a file if it exists
try:
    readline.read_history_file("service_history.txt")
except FileNotFoundError:
    pass

while True:
    try:
        line = input("Service> ")
        if line == "exit":
            break
        print(f"Command: {line}")
        readline.add_history(line)
    except EOFError:
        break

# Save command history to a file
readline.write_history_file("service_history.txt")

Conclusion

The readline module in Python is used to enhance command-line applications with features such as line editing, command history, and auto-completion. By leveraging the GNU Readline library, it provides an improved user experience for interactive command-line programs.

References

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare