2014-05-20 71 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] 

這也將隱藏完成方法。