Writing a CLIΒΆ
Here is an example of a simple CLI written using Click. Running this CLI will prompt the user for their name, before greeting them with "Hello {name}!". The number of greetings can be controlled with the count option.
Simple CLI
import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
help='The person to greet.')
def hello(count, name):
"""Simple program that greets NAME for a total of COUNT times."""
for x in range(count):
click.echo(f"Hello {name}!")
if __name__ == '__main__':
hello()
Below is a more complicated example of a CLI from the CHIME FRB Maestro repository. This time, the CLI contains multiple commands grouped together under one CLI. Each command has been written in their own file, hence the need to import each of them before adding them to the CLI group. The @click.group()
decorator and the add_command()
function add multiple commands to the cli()
function.
Example CLI from CHIMEFRB/maestro
"""MAESTRO COMMAND LINE INTERFACE."""
import click
from maestro import __version__ as version
from maestro.cli.build import build
from maestro.cli.configs import configs
from maestro.cli.defaults import defaults
from maestro.cli.deploy import deploy, remove
from maestro.cli.dev import dev, rethink, setup, teardown
from maestro.cli.start import start
# Main CLI Group
@click.group()
@click.version_option(
version=version, prog_name="maestro", message="%(prog)s %(version)s"
)
def cli():
"""Maestro :: Command Line Interface."""
pass # pragma: no cover
cli.add_command(deploy)
cli.add_command(remove)
cli.add_command(start)
cli.add_command(build)
cli.add_command(defaults)
cli.add_command(configs)
cli.add_command(dev)
cli.add_command(setup)
cli.add_command(teardown)
cli.add_command(rethink)
if __name__ == "__main__":
cli()