在Python中对帮助输出进行分类单击

2024-06-23 20:02:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图弄清楚如何在Click中对命令进行分类,以类似于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

我曾经尝试过通过各种点击类来改变这种行为,但没有成功。 我得到的最接近的结果是能够基于优先级构造命令,但我不能像上面的示例那样从逻辑上将它们分开

任何帮助都将不胜感激


Tags: py命令cliis分类usagethis结构
1条回答
网友
1楼 · 发布于 2024-06-23 20:02:00

我通过创建自己的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

这有用吗

相关问题 更多 >

    热门问题