(我知道这并不是您所要的,但是)如果您对自动
TAB补全/建议(如许多shell中使用的)所出现的情况感到满意,则可以使用以下命令快速启动并运行在readline的模块。
这是一个基于Doug
Hellmann在readline上的PyMOTW编写的快速示例。
import readlineclass 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 Nonecompleter = 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 hihow are youInput: h<TAB><TAB>hello hihow are youInput: ho<TAB>ow are you
在最后一行(
H``O``TAB输入的)中,只有一个可能的匹配项,并且整个句子“你好吗”是自动完成的。
请查看链接的文章,以获取有关的更多信息
readline。
“更好的情况是,它不仅可以从头开始完成单词,而且可以从字符串的任意部分完成单词。”
这可以通过在完成函数中简单地修改匹配条件来实现。从:
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 hihow are youInput: o<TAB><TAB>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键在关键字中滚动。



