Alternative Python bindings for GNU Readline
The GNU Readline Library is the canonical implementation of command line editing, tab completion, and history for console-based applications. It is developed as part of Bash and available on virtually any platform.
While Python ships with readline bindings in its standard library, they only implement a subset of readline's features, just enough to perform identifier completion at the Python interpreter prompt.
The rl package aims to provide full implementations of GNU Readline's Custom Completer and History interfaces. It also contains high-level APIs to better organize the namespace and shield applications from low-level verbosity.
rl exports these components:
- Interface to the readline completer. Used to configure the completion aspects of readline.
- Interface to the active readline completion. Used to interact with readline when a completion is in progress.
- Interface to the readline history. Used to read and write history files and to manipulate history entries.
- The readline bindings module. Contains everything known from the standard library plus extensions specific to the rl package. The completer, completion, and history interfaces make use of this module, and you should rarely need to interact with it directly.
- A factory turning any callable into a completion entry function that can be handed to readline.
- A decorator printing exceptions to stderr. Useful when writing Python completions and hooks, as exceptions occurring there are usually swallowed by the in-between C code.
For further details please refer to the API Documentation.
The code below implements system command completion similar to Bash:
import os from rl import completer from rl import generator def complete_command(text): # Return executables matching 'text' for dir in os.environ.get('PATH').split(':'): dir = os.path.expanduser(dir) if os.path.isdir(dir): for name in os.listdir(dir): if name.startswith(text): if os.access(os.path.join(dir, name), os.R_OK|os.X_OK): yield name def main(): # Set the completion entry function completer.completer = generator(complete_command) # Enable TAB completion completer.parse_and_bind('TAB: complete') command = input('command> ') print('You typed:', command)
More examples are included in the package source.
rl requires Python 2.6 or higher. The installer builds GNU Readline 7.0.3 and a Python extension module.
On Mac OS X make sure you have Xcode Tools installed. On Linux and BSD systems you should already have a C compiler, but may need to verify the development environment is complete. For example, Ubuntu lacks the Python headers by default and base Fedora is missing some compiler configuration.
sudo apt install python-dev python3-dev sudo apt install libtinfo-dev
sudo dnf install redhat-rpm-config sudo dnf install ncurses-devel
pip install rl