python - 在 python3 中使用 readline 自动完成

标签 python python-3.x autocomplete readline

我正在尝试使用这个巧妙的技巧 here使用 csv 文件。不过,我似乎无法在 python3 中使用自动完成功能。我不知道从哪里开始阅读线。文档有点密集。我的猜测是,如果没有来自 Python 2 的 raw_input(),我会遗漏一些东西。

我在下面粘贴了我的尝试。当我在 shell 中并点击制表符时,我只会得到大制表符而没有自动完成操作。我的意图是下面的输入语句自动完成字符串 ['10/10/2013', '10/13/2013', '10/14/2013', '10/15/2013']

我错过了什么?

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')

更新:下面的答案很好,但在 OS X 上对我来说仍然很糟糕。我什至不知道从哪里开始解决这个问题。我在 Ubuntu 上自动完成了这个,但它没有以某种方式绑定(bind)到我的 OS X 系统上的 tab

最佳答案

更正版本:

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("> ")

注释:

  • 添加了自定义 display_matches()(可能对您没用)
  • 添加了 readline.set_completer_delims() 调用,因为我们希望将 / 视为单词的一部分。

在 Mac OS X 上的 Python-3.3 上测试

关于python - 在 python3 中使用 readline 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20625642/

相关文章:

python - py2exe:错误:libzmq.pyd:没有那个文件或目录

python - pandas 中的 set_value 和 = 有什么区别

python - 为什么我需要导入 tkinter.messagebox 但导入 tkinter 后不需要导入 tkinter.Tk()?

python - python 从s3存储桶中读取所有文件,按时间排序

python - 通过 MySQL 连接器 Python 与 CGI 的数据库连接无法正常工作

autocomplete - 自动完成对代码有影响吗?

python - 如何安全地重写 django.contrib.admin.utils quote() 方法?

python-3.x - python-docx插入点

jquery - Rails 中的动态自动完成,使用 jQuery TokenInput 插件

javascript - 如何检测是否在 Google Maps API 自动完成列表中选择了项目?