首页 > 解决方案 > 在 Python Click 中对帮助输出进行分类

问题描述

我试图弄清楚如何对 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

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

例如:

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 类以改变这种行为,但没有成功。我得到的最接近的是能够根据优先级构造命令,但我无法像上面的示例那样在逻辑上将它们分开。

任何帮助将不胜感激。

标签: pythonpython-3.8python-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}\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()}')

并创建了cli这样的组:

@click.group(cls=OrderedGroup)
def cli():
    pass

这有帮助吗?


推荐阅读