我正在尝试弄清楚如何在单击中对命令进行分类,以类似于kubectl
在分离命令时使用的结构
。例如,在普通的点击帮助输出中,我们有:
Usage: cli.py [OPTIONS] COMMAND [ARGS]...
A CLI tool
Options:
-h, --help Show this message and exit.
Commands:
command1 This is command1
command2 This is command2
command3 This is command3
command4 This is command4
相反,对于我的用法来说,理想的做法是进行分离以更好地对命令结构进行分类。
例如:
Usage: cli.py [OPTIONS] COMMAND [ARGS]...
A CLI tool
Options:
-h, --help Show this message and exit.
Specific Commands for X:
command1 This is command1
command2 This is command2
Specific Commands for Y:
command3 This is command3
command4 This is command4
Global Commands:
version Shows version
我也为此使用了最新的 Python 和最新版本的 Click。
我尝试研究挂钩到各种 Click 类来改变这种行为,但这样做没有成功。 我最接近的是能够根据优先级构建命令,但我无法像上面的例子那样在逻辑上将它们分开。
任何帮助将不胜感激。
我通过创建自己的click.Group
来实现这一点:
class OrderedGroup(click.Group):
def __init__(self, name=None, commands=None, **attrs):
super(OrderedGroup, self).__init__(name, commands, **attrs)
self.commands = commands or collections.OrderedDict()
def list_commands(self, ctx):
return self.commands
def format_commands(self, ctx, formatter):
super().get_usage(ctx)
formatter.write_paragraph()
with formatter.section("Specific Commands for X:"):
formatter.write_text(
f'{self.commands.get("command1").name}tt{self.commands.get("command1").get_short_help_str()}')
formatter.write_text(
f"{self.commands.get('command2').name}tt{self.commands.get('command2').get_short_help_str()}")
with formatter.section("Specific Commands for Y:"):
formatter.write_text(
f'{self.commands.get("command3").name}tt{self.commands.get("command3").get_short_help_str()}')
formatter.write_text(
f'{self.commands.get("command4").name}tt{self.commands.get("command4").get_short_help_str()}')
with formatter.section("Global Commands"):
formatter.write_text(
f'{self.commands.get("version").name}tt{self.commands.get("version").get_short_help_str()}')
并创建了这样的cli
组:
@click.group(cls=OrderedGroup)
def cli():
pass
这有帮助吗?