| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- import readline
- class SimpleCompleter:
- def __init__(self, options):
- self.options = sorted(options)
- def complete(self, text, state):
- response = None
- if state == 0:
- # 这是此文本的第一次,因此建立一个匹配列表。
- if text:
- self.matches = [
- s
- for s in self.options
- if s and s.startswith(text)
- ]
- else:
- self.matches = self.options[:]
- # 如果有那么多,从匹配列表中返回状态项。
- try:
- response = self.matches[state]
- except IndexError:
- response = None
- return response
- def input_loop():
- line = ''
- while line != 'stop':
- line = input('Prompt ("stop" to quit): ')
- print('Dispatch {}'.format(line))
- def start_completer(command_list:list):
- # 注册完成功能
- OPTIONS = command_list
- readline.set_completer(SimpleCompleter(OPTIONS).complete)
- # 使用 Tab 键完成
- readline.parse_and_bind('tab: complete')
|