Как очистить набранную строку при запросе ввода? - PullRequest
0 голосов
/ 24 февраля 2019

У меня есть список фруктов.Допустим,

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