Question

I'm trying to use this nifty trick here to work with a csv file. I can't seem to get autocomplete working in python3 though. I don't know where to begin with readline. The documentation was a little dense. My guess is that I'm missing something without raw_input() from Python 2.

I've pasted my attempt below. When I'm in the shell and I hit tab, I just get big tabs and no autocomplete action. My intention is that the input statement below auto-completes on the strings ['10/10/2013', '10/13/2013', '10/14/2013', '10/15/2013'].

What am I missing?

import readline

class MyCompleter(object):  # Custom completer

    def __init__(self, options):
        self.options = sorted(options)

    def complete(self, text, state):
        if state == 0:  # on first trigger, build possible matches
            if text:  # cache matches (entries that start with entered text)
                self.matches = [s for s in self.options
                                    if s and s.startswith(text)]
            else:  # no text entered, all matches possible
                self.matches = self.options[:]

        # return match indexed by state
        try:
            return self.matches[state]
        except IndexError:
            return None


dates = [
    '10/10/2013 13:03:51',
    '10/10/2013 13:54:32',
    '10/10/2013 18:48:48',
    '10/10/2013 19:13:00',
    '10/13/2013 12:58:17',
    '10/13/2013 13:38:15',
    '10/13/2013 16:48:58',
    '10/13/2013 17:23:59',
    '10/13/2013 20:09:56',
    '10/13/2013 21:54:14',
    '10/13/2013 21:57:43',
    '10/13/2013 22:47:40',
    '10/14/2013 13:32:53',
    '10/14/2013 21:14:51',
    '10/15/2013 10:18:23'
    ]

dates = [x.split(' ')[0] for x in dates]

completer = MyCompleter(list(set(dates)))
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
date = input('Enter a date in m/d/yy format\n\t')

Update: Nice answer below, but still broken for me on OS X. I don't even know where to begin troubleshooting that. I get autocomplete with this on Ubuntu, but it's not binding to tab on my OS X system somehow.

Was it helpful?

Solution

Corrected version:

from __future__ import print_function

import sys
import readline
from os import environ


class MyCompleter(object):  # Custom completer

    def __init__(self, options):
        self.options = sorted(options)

    def complete(self, text, state):
        if state == 0:  # on first trigger, build possible matches
            if not text:
                self.matches = self.options[:]
            else:
                self.matches = [s for s in self.options
                                if s and s.startswith(text)]

        # return match indexed by state
        try:
            return self.matches[state]
        except IndexError:
            return None

    def display_matches(self, substitution, matches, longest_match_length):
        line_buffer = readline.get_line_buffer()
        columns = environ.get("COLUMNS", 80)

        print()

        tpl = "{:<" + str(int(max(map(len, matches)) * 1.2)) + "}"

        buffer = ""
        for match in matches:
            match = tpl.format(match[len(substitution):])
            if len(buffer + match) > columns:
                print(buffer)
                buffer = ""
            buffer += match

        if buffer:
            print(buffer)

        print("> ", end="")
        print(line_buffer, end="")
        sys.stdout.flush()


dates = [
    '10/10/2013 13:03:51',
    '10/10/2013 13:54:32',
    '10/10/2013 18:48:48',
    '10/10/2013 19:13:00',
    '10/13/2013 12:58:17',
    '10/13/2013 13:38:15',
    '10/13/2013 16:48:58',
    '10/13/2013 17:23:59',
    '10/13/2013 20:09:56',
    '10/13/2013 21:54:14',
    '10/13/2013 21:57:43',
    '10/13/2013 22:47:40',
    '10/14/2013 13:32:53',
    '10/14/2013 21:14:51',
    '10/15/2013 10:18:23'
    ]

dates = [x.split(' ')[0] for x in dates]

completer = MyCompleter(list(set(dates)))
readline.set_completer_delims(' \t\n;')
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
readline.set_completion_display_matches_hook(completer.display_matches)
print('Enter a date in m/d/yy format\n\t')
date = input("> ")

Note(s):

  • Added a custom display_matches() (may not be useful for you)
  • Added readline.set_completer_delims() call because we want to treat / as part of a word.

Tested on Python-3.3 on Mac OS X

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top