我知道如何在python解释器中设置python对象的自动完成(在unix上)。
this.
我需要知道如何在用python编写的命令行程序中启用、tab/自动完成任意项目。
我的特定用例是一个需要发送电子邮件的命令行python程序。我希望当用户键入部分电子邮件地址(并可选择按TAB键)时,能够自动完成电子邮件地址(我在磁盘上有地址)。
我不需要它在windows或mac上工作,只需要linux。
发布于 2008-10-09 15:01:39
使用Python的readline绑定。例如,
import readline
def completer(text, state):
options = [i for i in commands if i.startswith(text)]
if state < len(options):
return options[state]
else:
return None
readline.parse_and_bind("tab: complete")
readline.set_completer(completer)官方的module docs没有更多的详细信息,请参阅readline docs了解更多信息。
发布于 2008-10-09 15:08:19
跟着cmd documentation走,你就会好起来
import cmd
addresses = [
'here@blubb.com',
'foo@bar.com',
'whatever@wherever.org',
]
class MyCmd(cmd.Cmd):
def do_send(self, line):
pass
def complete_send(self, text, line, start_index, end_index):
if text:
return [
address for address in addresses
if address.startswith(text)
]
else:
return addresses
if __name__ == '__main__':
my_cmd = MyCmd()
my_cmd.cmdloop()输出为选项卡->选项卡-> send ->选项卡->选项卡-> f ->选项卡
(Cmd)
help send
(Cmd) send
foo@bar.com here@blubb.com whatever@wherever.org
(Cmd) send foo@bar.com
(Cmd)发布于 2008-10-13 09:59:24
既然你在问题中说“不是解释器”,我猜你不想要涉及python readline之类的答案。(__:事后看来,显然不是这样的。哈哈。我认为这些信息很有趣,所以我就把它留在这里。)
我觉得你可能是在找this
它是关于向任意命令添加shell级别的完成,扩展bash自己的制表符完成。
简而言之,您将创建一个包含将生成可能的补全的外壳函数的文件,将其保存到/etc/bash_completion.d/中,并使用命令complete注册它。以下是链接页面中的一段代码:
_foo()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="--help --verbose --version"
if [[ ${cur} == -* ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
fi
}
complete -F _foo foo在本例中,键入foo --[TAB]将给出变量opts中的值,即--help、--verbose和--version。出于您的目的,您实际上需要定制放入opts中的值。
一定要看一下链接页面上的示例,一切都非常简单。
https://stackoverflow.com/questions/187621
复制相似问题