(我知道这并不是您所要的,但是)如果您对自动TAB
补全/建议(如许多shell中使用的)所出现的情况感到满意,则可以使用以下命令快速启动并运行在readline的模块。
这是一个基于Doug Hellmann在readline上的PyMOTW编写的快速示例。
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
completer = MyCompleter(["hello", "hi", "how are you", "goodbye", "great"])
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
input = raw_input("Input: ")
print "You entered", input
这将导致以下行为(<TAB>
表示按下了Tab键):
Input: <TAB><TAB>
goodbye great hello hi how are you
Input: h<TAB><TAB>
hello hi how are you
Input: ho<TAB>ow are you
在最后一行(H``O``TAB
输入的)中,只有一个可能的匹配项,并且整个句子“你好吗”是自动完成的。
“更好的情况是,它不仅可以从头开始完成单词,而且可以从字符串的任意部分完成单词。”
self.matches = [s for s in self.options
if s and s.startswith(text)]
像这样:
self.matches = [s for s in self.options
if text in s]
这将为您提供以下行为:
Input: <TAB><TAB>
goodbye great hello hi how are you
Input: o<TAB><TAB>
goodbye hello how are you