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

5 投票
3 回答
1583 浏览
提问于 2025-04-18 07:03

我正在使用Python的cmd模块来创建一个小的命令行工具。我不太喜欢显示那些没有文档说明的命令。所以当我输入'help'时,我希望只显示那些有文档说明的命令。

目前,输入help会显示以下内容:

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

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

我在这里加了EOF这个选项,因为我需要优雅地退出,这在cmd的示例中有说明。但我不想让它出现在列表里。如果我把它记录下来,那就没有意义了。我该怎么做才能不显示'没有文档的命令'呢?

我的代码:

from cmd import Cmd
from ptcli import Ptcli
from termcolor import colored

class Pt(Cmd):

  Cmd.intro = colored("Welcome to pt CLI","yellow")
  Cmd.prompt = colored(">> ","cyan")

  def do_projects(self,line):
    'Choose current project from a list'
    pt =  Ptcli()
    result = pt.get_projects()
    for i in result:
        print i['name']

def do_exit(self,line):
    'Exit pt cli'
    return True

def do_EOF(self, line):
    return True

def default(self, arg):
    ''' Print a command not recognized error message '''

if name == 'main': Pt().cmdloop()

3 个回答

0

对@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)
3

你可以使用下面的技巧

在Pt类中,把undoc_header设置为None,然后重写print_topic方法,这样当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")    
5
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]

这样做会让这个方法在自动补全中也消失。

撰写回答