Click CLI With Subcommands
Build a CLI tool with Click subcommands options and help for consistent command interfaces.
Code
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:
clickis 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.