Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Click - name synonyms or abbreviations

I am using python click to implement a cli. Simplest example would allow me to say:

./mytest.py help

but also

./mytest.py h

In other words, the help command can be shortened to just h. This is the way many cli programs work, e.g. git.

From what I can tell the code snippet:

@click.command()
def help():
    click.echo("Help!)

Will allow me to have:

./mytest.py help

But I don't know how to allow the synonym. I can't find anything that explains this.

like image 412
pitosalas Avatar asked Mar 11 '26 11:03

pitosalas


1 Answers

In the Click documentation, this is known as "aliases".

The documentation at https://click.palletsprojects.com/en/8.x/advanced/ provides a code snippet for what you're looking for. Additionally, it links to sample code at https://github.com/pallets/click/tree/master/examples/aliases.

Here is a minimal implementation for the example given:

import click


class AliasedGroup(click.Group):
    def get_command(self, ctx, cmd_name):
        if cmd_name in ["help", "h"]:
            return click.Group.get_command(self, ctx, "help")
        return None


@click.command(cls=AliasedGroup)
def cli():
    pass


@cli.command()
def help():
    click.echo("Help!")


if __name__ == "__main__":
    cli()
like image 167
jrc Avatar answered Mar 14 '26 00:03

jrc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!