英文:
Python cmd autocomplete: display options on separate lines
问题
我正在使用 Python 中的 cmd 模块编写一个命令行界面,该模块使用 readline 模块提供自动补全功能。
自动补全会在同一行显示不同选项,但我希望它们显示在不同的行上,我没有在 cmd 中找到任何允许我这样做的参数。
这是一个示例程序:
import cmd
class mycmd(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
def do_quit(self, s):
return True
def do_add(self, s):
pass
def do_addition(self, s):
pass
def complete_add(self, text, line, begidx, endidx):
params = ['asd', 'asdasd', 'lol']
return 展开收缩
if __name__ == '__main__':
mycmd().cmdloop()
这是结果:
(Cmd) <tab> <tab>
add addition help quit <-- 我希望它们显示在不同的行上
(Cmd) add<tab> <tab>
add addition <--
(Cmd) add <tab> <tab>
asd asdasd lol <--
(Cmd) add asd<tab> <tab>
asd asdasd <--
如果我在每个自动补全选项的末尾添加一个换行符,我会得到这个结果:
(Cmd) add <tab> <tab>
asd^J asdasd^J lol^J
无论如何,这不会解决命令的自动补全,只会解决参数的自动补全。
有什么建议吗?
感谢帮助!
英文:
I am writing a CLI in Python using the cmd module, which provides the autocomplete functionality using the readline module.
Autocomplete shows the different options on the same line, while I want them on different lines, and I have not find any parameter in cmd that allows me to do that.
This is an example program:
import cmd
class mycmd(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
def do_quit(self, s):
return True
def do_add(self, s):
pass
def do_addition(self, s):
pass
def complete_add(self, text, line, begidx, endidx):
params = ['asd', 'asdasd', 'lol']
return 展开收缩
if __name__ == '__main__':
mycmd().cmdloop()
and this is the result:
(Cmd) <tab> <tab>
add addition help quit <-- I want these on different lines
(Cmd) add<tab> <tab>
add addition <--
(Cmd) add <tab> <tab>
asd asdasd lol <--
(Cmd) add asd<tab> <tab>
asd asdasd <--
If I add a line separator at the end of each autocomplete option, I get this:
(Cmd) add <tab> <tab>
asd^J asdasd^J lol^J
Anyway, this would not solve the autocomplete of the commands, only of the parameters.
Any suggestions?
Thanks for the help!
答案1
得分: 1
需要接管readline的显示功能来实现这一点。为此,请import readline
,将以下内容添加到您的__init__
中:
readline.set_completion_display_matches_hook(self.match_display_hook)
然后将以下内容添加到您的类中:
def match_display_hook(self, substitution, matches, longest_match_length):
print()
for match in matches:
print(match)
print(self.prompt, readline.get_line_buffer(), sep='', end='', flush=True)
英文:
You need to take over readline's displaying function to do this. To do that, import readline
, add this to your __init__
:
readline.set_completion_display_matches_hook(self.match_display_hook)
And add this to your class:
def match_display_hook(self, substitution, matches, longest_match_length):
print()
for match in matches:
print(match)
print(self.prompt, readline.get_line_buffer(), sep='', end='', flush=True)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论