我正在尝试在Windows上为我编写的命令行用户界面实现任意自动完成。受到该问题第一个答案的启发,我试图直接运行那里写的脚本,后来才意识到我在 Windows 上需要使用 pyreadline
而不是 readline
。经过一些尝试,我最终得到了下面的脚本,基本上是复制粘贴,但是进行了 pyreader 初始化:
from pyreadline import Readline
readline = 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>
执行自动完成行为?最初我认为我搞砸了补全器设置和绑定初始化,这在
pyreadline
与readline
中是不同的,但从模块代码和pyreadline
文档中的示例来看,它们是相同的。如果有用的话,我正在尝试在Windows 10上使用2.7 Anaconda Python发行版来执行它。