Python CLI with Click

Build a command-line tool in Python using Click with subcommands, option parsing, colored output, progress bars, and configuration file loading. Includes.

PythonCli Tooling

Code

snippet
import click

@click.group()
def cli():
    pass

@cli.command()
@click.argument('name')
@click.option('--format', '-f', default='json', help='Output format')
def build(name, format):
    click.echo(click.style(f'Building {name} ({format})', fg='green'))

@cli.command()
@click.option('--verbose', is_flag=True)
def deploy(verbose):
    if verbose:
        click.echo('Deploying with verbose output...')
    click.echo('Done!')

if __name__ == '__main__':
    cli()

What the code does

Count the functions cli, build and deploy as the entire surface area of Python CLI with Click.

What to watch for

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

Applying it

Entry signature: def cli()

Statements that matter

def build(name, format):
    click.echo(click.style(f'Building {name} ({format})', fg='green'))
def deploy(verbose):
    if verbose:
        click.echo('Deploying with verbose output...')
    click.echo('Done!')

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `click`. Without it the snippet will not load.