[Python] Regular usage output with Click command aliases

Discussão em 'Python' iniciado por Stack, Junho 16, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using this snippet for my custom group (from here) to allow prefixes.

    class AliasedGroup(click.Group):
    def get_command(self, ctx, cmd_name):
    rv = click.Group.get_command(self, ctx, cmd_name)
    if rv is not None:
    return rv
    matches = [x for x in self.list_commands(ctx)
    if x.startswith(cmd_name)]
    if not matches:
    return None
    elif len(matches) == 1:
    return click.Group.get_command(self, ctx, matches[0])
    ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))


    The usage output becomes really dumb however: it shows the prefixes of the commands instead of showing them fully:


    Usage: test_core a c [OPTIONS]
    ​

    I would like to see


    Usage: test_core add combined [OPTIONS]
    ​

    even when I call test_core a c -h.

    I've looked into it and it doesn't look like there is an obvious solution. Formatter logic doesn't know about their original names. Maybe MultiCommand.resolve_command could be overridden to handle an overridden version of MultiCommand/Group.get_command that returns the original command name as well. But that might break some things, maybe there's some easier way.

    Full code:

    import click

    class AliasedGroup(click.Group):
    def get_command(self, ctx, cmd_name):
    rv = click.Group.get_command(self, ctx, cmd_name)
    if rv is not None:
    return rv
    matches = [x for x in self.list_commands(ctx)
    if x.startswith(cmd_name)]
    if not matches:
    return None
    elif len(matches) == 1:
    return click.Group.get_command(self, ctx, matches[0])
    ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))

    @click.group(cls=AliasedGroup, context_settings={'help_option_names': ['-h', '--help']})
    def cli():
    pass

    @cli.group(cls=AliasedGroup)
    def add():
    pass

    @add.command()
    @click.option('--yarr')
    def combined():
    pass

    cli(['a', 'c', '-h'], prog_name='test_core')

    Continue reading...

Compartilhe esta Página