简体   繁体   English

Python cmd 自动完成:在单独的行上显示选项

[英]Python cmd autocomplete: display options on separate lines

I am writing a CLI in Python using the cmd module, which provides the autocomplete functionality using the readline module.我正在使用 cmd 模块在 Python 中编写 CLI,该模块使用 readline 模块提供自动完成功能。 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.自动完成在同一行上显示不同的选项,而我希望它们在不同的行上,而且我在 cmd 中没有找到任何允许我这样做的参数。

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 [s for s in params if s.startswith(text)]

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!谢谢您的帮助!

You need to take over readline's displaying function to do this.您需要接管 readline 的显示功能才能做到这一点。 To do that, import readline , add this to your __init__ :为此, import readline ,将其添加到您的__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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM