Python,通过它的readline绑定允许很好的命令行自动完成(如这里所述 )。
但是,完成似乎只是在string的开始工作。 如果要匹配stringreadline的中间或末尾不起作用。
我想自动完成string,在命令行python程序通过匹配我键入任何可用string列表中的string。
使用像curses这样的terminal模拟器会很好。 它只需要在Linux上运行,而不是在Mac或Windows上运行。
这里是一个例子:假设我在列表中有以下三个string
['Paul Eden <paul@domain.com>', 'Eden Jones <ejones@domain.com>', 'Somebody Else <somebody@domain.com>']
我想要一些代码,它会自动填充列表中的前两项,然后让我select其中的一个(全部通过命令行使用键盘)。
我不确定我是否理解这个问题。 您可以使用readline.clear_history和readline.add_history来设置所需的可执行字符串,然后使用control -r在历史记录中搜索后记(就像在shell提示符下一样)。 例如:
#!/usr/bin/env python import readline readline.clear_history() readline.add_history('foo') readline.add_history('bar') while 1: print raw_input('> ')
或者,您可以编写自己的完成者版本并将适当的密钥绑定到它。 如果您的匹配列表很大,此版本使用缓存:
#!/usr/bin/env python import readline values = ['Paul Eden <paul@domain.com>', 'Eden Jones <ejones@domain.com>', 'Somebody Else <somebody@domain.com>'] completions = {} def completer(text, state): try: matches = completions[text] except KeyError: matches = [value for value in values if text.upper() in value.upper()] completions[text] = matches try: return matches[state] except IndexError: return None readline.set_completer(completer) readline.parse_and_bind('tab: menu-complete') while 1: a = raw_input('> ') print 'said:', a