Archive

Posts Tagged ‘autocomplete’

How to make a python, command-line program autocomplete arbitrary things

June 4, 2013 2 comments

This entry is based on this SO post.

Problem
You have an interactive command-line Python script and you want to add autocompletion to it when hitting the TAB key.

Solution
Here is a working example (taken from here):

import readline

addrs = ['angela@domain.com', 'michael@domain.com', 'david@test.com']

def completer(text, state):
    options = [x for x in addrs if x.startswith(text)]
    try:
        return options[state]
    except IndexError:
        return None

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

while True:
    inp = raw_input("> ")
    print "You entered", inp
Categories: python Tags: , ,