Categorize help output in Python Click

前端 未结 1 1612
猫巷女王i
猫巷女王i 2021-01-22 01:47

I am trying to figure out how to categorize commands in Click to resemble something close to the structure that kubectl uses in the way it separate commands out.

相关标签:
1条回答
  • 2021-01-22 02:05

    I've achieved this by creating my own 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()}')
    
    

    And created the cli group as such:

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

    Does this help?

    0 讨论(0)
提交回复
热议问题