如何在CMD2 CLI中创建首命令含连字符的自定义命令?
在CMD2中创建首命令含连字符的自定义命令
CMD2默认会将do_前缀的方法名里的下划线转换为空格,作为命令名(比如do_command_something对应command something)。要实现command-something这类带连字符的命令,有两种直接可行的方式:
方法1:使用@cmd2.with_command装饰器
直接给目标方法添加装饰器,指定自定义的命令名,代码示例:
from cmd2 import Cmd, with_command class MyCLI(Cmd): @with_command("command-something") def do_command_something(self, _): self.poutput("触发了command-something命令")
启动CLI后输入command-something,就能执行对应方法的逻辑。
方法2:手动修改命令映射
在CLI类的初始化方法中,直接向self.commands字典添加自定义命令与方法的映射:
from cmd2 import Cmd class MyCLI(Cmd): def __init__(self): super().__init__() # 绑定自定义命令到目标方法 self.commands["command-something"] = self.do_command_something def do_command_something(self, _): self.poutput("触发了command-something命令")
额外优化:移除默认生成的空格命令
如果不想保留do_command_something默认生成的command something命令,可以搭配@cmd2.with_default_command(False)装饰器:
from cmd2 import Cmd, with_command, with_default_command class MyCLI(Cmd): @with_command("command-something") @with_default_command(False) def do_command_something(self, _): self.poutput("仅响应command-something命令")
内容的提问来源于stack exchange,提问作者MoMan
相关产品推荐
相关产品推荐

