(我知道这并不完全符合您的要求,但是如果您对TAB中出现的自动完成/建议感到满意(如许多shell中所使用的),则可以快速启动并运行使用
readline模块。
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:
goodbye great hello hi how are you
Input: h
hello hi how are you
Input: hoow are you
在最后一行(HOTAB输入)中,只有一个可能的匹配,整个句子“你好”是自动完成的。
查看链接的文章,了解更多关于readline的信息。
“And better yet would be if it would complete words not only from the beginning … completion from arbitrary part of the string.”
这可以通过简单地修改完成函数中的匹配标准来实现,即。从:
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:
goodbye great hello hi how are you
Input: o
goodbye hello how are you
更新:使用历史缓冲区(如注释中所述)
创建用于滚动/搜索的伪菜单的简单方法是将关键字加载到历史缓冲区中。然后,您可以使用向上/向下箭头键滚动条目,也可以使用Ctrl R执行反向搜索。
要尝试这一点,请进行以下更改:
keywords = ["hello", "hi", "how are you", "goodbye", "great"]
completer = MyCompleter(keywords)
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
for kw in keywords:
readline.add_history(kw)
input = raw_input("Input: ")
print "You entered", input
运行脚本时,尝试输入Ctrl r,后跟a。这将返回包含“a”的第一场比赛。再次输入Ctrl r进行下一场比赛。要选择一个条目,请按ENTER。
还可以使用UP / DOWN键滚动浏览关键字。