The rlcompleter Module

(Optional, Unix only) The rlcompleter module provides word completion for the readline module.

To enable word completion, just import this module. By default, the completion function is bound to the Esc key. Press Esc twice to finish the current word. To change the key, you can use something like:

import readline
readline.parse_and_bind("tab: complete")

The script in Example 14-10 shows how to use the completion functions from within a program.

Example 14-10. Using the rlcompleter Module to Expand Names

File: rlcompleter-example-1.py

import rlcompleter
import sys

completer = rlcompleter.Completer()

for phrase in "co", "sys.p", "is":
    print phrase, "=>",
    # emulate readline completion handler
    try:
        for index in xrange(sys.maxint):
            term = completer.complete(phrase, index)
            if term is None:
                break
            print term,
    except:
        pass
    print

co => continue compile complex coerce completer
sys.p => sys.path sys.platform sys.prefix
is => is isinstance issubclass

Get Python Standard Library now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.