(我知道这并不完全符合您的要求,但是)如果您对出现在 TAB 上的自动完成/建议感到满意(在许多 shell 中使用),然后您可以使用readline 模块快速启动并运行。
这是一个基于Doug Hellmann's PyMOTW writeup on 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: <TAB><TAB>
goodbye great hello hi how are you
Input: h<TAB><TAB>
hello hi how are you
Input: ho<TAB>ow are you
在最后一行(HOTAB输入),只有一个可能的匹配和整个句子“你好吗”自动完成。
查看链接文章以获取有关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 hi how are you
Input: o<TAB><TAB>
goodbye hello how are you
更新:使用历史缓冲区(如 cmets 中所述)
创建用于滚动/搜索的伪菜单的一种简单方法是将关键字加载到历史缓冲区中。然后,您将能够使用向上/向下箭头键滚动条目以及使用 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。
还可以尝试使用向上/向下键滚动浏览关键字。