🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
- Introduction
- Enabling
readline - History Management
- Adding Commands to History
- Loading and Saving History
- Accessing History Items
- Line Editing and Completion
- Configuring Auto-Completion
- Examples
- Basic Usage
- Managing Command History
- Custom Auto-Completion
- Real-World Use Case
- Conclusion
- 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
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment