Python Readline Module
The readline module defines a number of functions to facilitate completion and reading/writing of history files from the Python interpreter. This module is based on the GNU Readline library, but it is not available on all platforms (specifically Windows, though pyreadline is a common alternative).
Importing the Module
import readline
Basic Usage
Simply importing readline will cause the input() function to use readline for line editing and history.
Auto-Completion
You can register a completer function to assist with tab-completion.
import readline
def completer(text, state):
options = [i for i in commands if i.startswith(text)]
if state < len(options):
return options[state]
else:
return None
commands = ['start', 'stop', 'list', 'print']
readline.parse_and_bind("tab: complete")
readline.set_completer(completer)
input('Enter command: ')
History
The module allows you to save and load command history.
Reading History
import readline
import os
histfile = os.path.join(os.path.expanduser("~"), ".python_history")
try:
readline.read_history_file(histfile)
# default history len is -1 (infinite), which may grow unruly
readline.set_history_length(1000)
except FileNotFoundError:
pass
Writing History
import atexit
import readline
import os
histfile = os.path.join(os.path.expanduser("~"), ".python_history")
atexit.register(readline.write_history_file, histfile)
Startup File
The readline module can execute an initialization file (like .inputrc).
readline.read_init_file()