Click CLI With Subcommands

Build a CLI tool with Click subcommands options and help for consistent command interfaces.

PythonCli Tooling

Code

pythonsnippet
19 lines
import click
@click.group()
def cli():
    pass

@cli.command()
@click.option('--name', required=True, help='User name')
@click.option('--verbose', is_flag=True)
def greet(name, verbose):
    msg = f'Hello, {name}!'
    if verbose:
        click.echo(msg)
    else:
        click.echo(msg)

@cli.command()
@click.argument('path', type=click.Path(exists=True))
def process(path):
    click.echo(f'Processing {path}')

How it works

Click CLI With Subcommands keeps everything in the functions cli, greet and process.

Watch out for

  • Plan for an install step: click is a real dependency, resolved by the package manager.

Putting it to use

The primary signature is def cli()

cli is the public entry point; everything else in the file exists to support it.

Core lines

def greet(name, verbose):
    msg = f'Hello, {name}!'
    if verbose:
        click.echo(msg)
    else:
        click.echo(msg)
def process(path):
    click.echo(f'Processing {path}')

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `click` must be present in the project or the import fails at load time.