要求输入时如何清除输入的字符串?

时间:2019-02-24 20:00:03

标签: python readline

我有水果清单。假设:

fruits = ['APPLE', 'BANANA', 'BERRY', 'BLUEBERRY']

我正在使用readline模块自动填充或输出前几个字符的匹配项。

我想要做的是显示匹配项,然后然后清除我在显示匹配项的输入中键入的字母。我想这样做,所以我只能按索引号获取水果。

> Input fruit: B <TAB>
[0] BANANA    [1] BERRY    [2] BLUEBERRY

> Input index of fruit: 0

> You selected BANANA.

我对sys.stdin或sys.stdout不太了解,但是我尝试了sys.stdin = "",但无济于事。我认为删除输入的最佳位置是display_matches

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.upper())]

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


    tpl = "{:<" + str(int(max(map(len, matches)) * 1.2)) + "}"
    buffer = ""
    for match in matches:
        match = tpl.format(match[:])
        if len(buffer + match) > columns:
            buffer = ""
        buffer += match
    if buffer:
        print('\n'+buffer)

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

def enter(fruits):
    fruits = [f.name.upper() for f in fruits]
    completer = MyCompleter(fruitrs)
    readline.set_completer_delims('\s\t\n;')
    readline.set_completer(completer.complete)
    readline.parse_and_bind("tab: complete")   
    i = input('Enter a fruit: ').upper()

0 个答案:

没有答案