2014-05-20 68 views
4

我使用Python的cmd模块来构建一个小的CLI工具。我不是展示列出的无证命令的粉丝。所以当我输入'help'时,我想只显示记录的命令。覆盖Python的cmd模块中的无证帮助区域

目前键入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 ''' 

如果 == '主要': 铂()cmdloop()

回答

3

您可以使用下面

黑客在铂class undoc_header为无并覆盖print_topic方法不打印部分,如果头是无

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")  
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) 
2
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] 

这也将隐藏完成方法。