completer.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import readline
  2. class SimpleCompleter:
  3. def __init__(self, options):
  4. self.options = sorted(options)
  5. def complete(self, text, state):
  6. response = None
  7. if state == 0:
  8. # 这是此文本的第一次,因此建立一个匹配列表。
  9. if text:
  10. self.matches = [
  11. s
  12. for s in self.options
  13. if s and s.startswith(text)
  14. ]
  15. else:
  16. self.matches = self.options[:]
  17. # 如果有那么多,从匹配列表中返回状态项。
  18. try:
  19. response = self.matches[state]
  20. except IndexError:
  21. response = None
  22. return response
  23. def input_loop():
  24. line = ''
  25. while line != 'stop':
  26. line = input('Prompt ("stop" to quit): ')
  27. print('Dispatch {}'.format(line))
  28. def start_completer(command_list:list):
  29. # 注册完成功能
  30. OPTIONS = command_list
  31. readline.set_completer(SimpleCompleter(OPTIONS).complete)
  32. # 使用 Tab 键完成
  33. readline.parse_and_bind('tab: complete')