Mre*_*der 5 python command-line-interface
我正在使用 Python 的 cmd 模块构建一个小型 CLI 工具。我不喜欢显示列出的未记录的命令。因此,当我输入“帮助”时,我只想显示记录的命令。
当前输入帮助显示:
Documented commands (type help <topic>):
========================================
exit help projects
Undocumented commands:
======================
EOF
Run Code Online (Sandbox Code Playgroud)
我在那里有 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 '''
Run Code Online (Sandbox Code Playgroud)
if name == ' main ': Pt().cmdloop()
小智 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]
Run Code Online (Sandbox Code Playgroud)
这也会隐藏该方法的完成。
您可以使用下面的技巧
在 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")
Run Code Online (Sandbox Code Playgroud)