对 Python Click 中的帮助输出进行分类

Ric*_*ich 2 python python-click python-3.8

我试图弄清楚如何对 Click 中的命令进行分类,以类似于kubectl其分隔命令的方式所使用的结构。

例如,在普通的 Click 帮助输出中,我们有:

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
Run Code Online (Sandbox Code Playgroud)

相反,对我的使用来说最理想的是进行分离以更好地对命令结构进行分类。

例如:

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
Run Code Online (Sandbox Code Playgroud)

为此,我也使用最新的 Python 和最新版本的 Click。

我尝试过挂钩各种 Click 类来改变这种行为,但没有成功。我最接近的是能够根据优先级构建命令,但我无法像上面的示例一样在逻辑上将它们分开。

任何帮助将不胜感激。

aft*_*ner 5

我通过创建自己的实现来实现这一目标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}\t\t{self.commands.get("command1").get_short_help_str()}')
            formatter.write_text(
                f"{self.commands.get('command2').name}\t\t{self.commands.get('command2').get_short_help_str()}")

        with formatter.section("Specific Commands for Y:"):
            formatter.write_text(
                f'{self.commands.get("command3").name}\t\t{self.commands.get("command3").get_short_help_str()}')
            formatter.write_text(
                f'{self.commands.get("command4").name}\t\t{self.commands.get("command4").get_short_help_str()}')

        with formatter.section("Global Commands"):
            formatter.write_text(
                f'{self.commands.get("version").name}\t\t{self.commands.get("version").get_short_help_str()}')

Run Code Online (Sandbox Code Playgroud)

并创建了cli这样的组:

@click.group(cls=OrderedGroup)
def cli():
    pass
Run Code Online (Sandbox Code Playgroud)

这有帮助吗?