Click - Define default behavior for command group

22 views Asked by At

I am trying to build a CLI using the click package. The CLI will have several sub-commands, which will be implemented using click.Group.

When my command is run without a sub-command, I would like to fall back to a default "parent command." I am trying to do something like this:

import sys
import click


@click.group(sys.argv[0])
def cli():
    print("Root command") # Something to do when `myCommand.py` is run without any arguments


@click.command()
def sayhi():
    print("Hello.")


@click.command()
def saybye():
    print("Bye.")


cli.add_command(sayhi)
cli.add_command(saybye)


if __name__ == "__main__":
    cli()

The intended behavior is as follows:

$ python ./myCommand.py
Root command
$ python ./myCommand.py sayhi
Hello.
$ python ./myCommand.py saybye
Bye.

Instead, I am getting this:

$ python ./myCommand.py
Usage: myCommand.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  saybye
  sayhi
$ python ./myCommand.py sayhi
Root command
Hello.
$ python ./myCommand.py saybye
Root command
Bye.

Is it possible to achieve the desired behavior using click? If so, how?

0

There are 0 answers