覆盖Python的cmd modu中未记录的帮助区域

2024-05-18 18:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python的cmd模块来构建一个小的CLI工具。我不喜欢显示列出的未记录的命令。所以当我输入'help'时,我只想显示文档化的命令。在

当前键入的帮助显示:

Documented commands (type help <topic>):
========================================
exit  help  projects

Undocumented commands:
======================
EOF

这里有EOF位,因为我需要优雅地退出,正如cmd示例所记录的那样。但我不想把它列出来。如果我把它记录下来,那就没有意义了。如何覆盖而不显示“未记录的命令”?在

我的代码:

^{pr2}$

如果名称='main': Pt().cmdloop()


Tags: 模块工具文档命令cmdtopic键入cli
3条回答
class Pt(Cmd):
    __hiden_methods = ('do_EOF',)

def do_EOF(self, arg):
    return True

def get_names(self):
    return [n for n in dir(self.__class__) if n not in self.__hiden_methods]

这也会在完成时隐藏方法。在

你可以使用下面的黑客

在Pt类中,将undoc\u header设置为None,并重写打印主题如果header为None则不打印节的方法

undoc_header = None 

def print_topics(self, header, cmds, cmdlen, maxcol):                                                                                                                   
    if header is not None:                                                                                                                                              
        if cmds:                                                                                                                                                        
            self.stdout.write("%s\n"%str(header))                                                                                                                       
            if self.ruler:                                                                                                                                              
                self.stdout.write("%s\n"%str(self.ruler * len(header)))                                                                                                 
            self.columnize(cmds, maxcol-1)                                                                                                                              
            self.stdout.write("\n")    

改进@user933589的回答:

更好的方法是重写print_topics方法,但仍然调用Cmd类中定义的基方法,如下所示:

undoc_header = None

def print_topics(self, header, cmds, cmdlen, maxcol):
    if header is not None:
        Cmd.print_topics(self, header, cmds, cmdlen, maxcol)

相关问题 更多 >

    热门问题