Code of the Day
IntermediateClick and Subcommands

Click basics

Create a Click command with options and arguments, and let Click generate the --help text automatically.

UtilitiesIntermediate8 min read
Recommended first
By the end of this lesson you will be able to:
  • Create a Click command with @click.command()
  • Add options with @click.option() and arguments with @click.argument()
  • Understand the auto-generated --help output structure

The core of Click is one decorator per concept: @click.command() makes a function into a CLI command, @click.option() adds a named flag, and @click.argument() adds a positional argument. Python's function signature becomes the interface.

A command with options and arguments

import click

@click.command()
@click.argument("filename")
@click.option("--lines", "-n", default=10, help="Number of lines to show.")
@click.option("--verbose", is_flag=True, help="Print extra detail.")
def head(filename, lines, verbose):
    """Print the first N lines of a file."""
    if verbose:
        click.echo(f"Reading {filename}, showing {lines} lines")
    with open(filename) as f:
        for i, line in enumerate(f):
            if i >= lines:
                break
            click.echo(line, nl=False)

Running python head.py --help produces:

Usage: head.py [OPTIONS] FILENAME

  Print the first N lines of a file.

Options:
  -n, --lines INTEGER  Number of lines to show.
  --verbose            Print extra detail.
  --help               Show this message and exit.

Click builds this from the docstring ("""Print the first N lines..."""), the help= strings on each option, and the argument name. You write the interface in Python; Click writes the docs.

Key decorator patterns

GoalDecorator
Positional argument@click.argument("name")
Named option with value@click.option("--count", default=1)
Boolean flag@click.option("--verbose", is_flag=True)
Short alias@click.option("--lines", "-n", default=10)
Required option@click.option("--output", required=True)
Choice from a list@click.option("--format", type=click.Choice(["json", "table"]))

click.echo vs print

Click provides click.echo() rather than print() for two reasons: it handles Unicode safely on Windows, and it flushes the output buffer on exit. For simple scripts either works, but click.echo is the Click convention.

Try it

The demo below simulates invoking a Click command programmatically, which is how the CliRunner works in tests (and in this browser environment, which cannot run sys.argv):

Python — editable, runs in your browser

Decorators are applied bottom-up in Python, so the order of @click.option decorators is reversed relative to the function parameters: the decorator closest to def is processed first. In practice this does not matter — Click matches by parameter name, not position — but it is worth knowing so the decorator order does not surprise you.

Where to go next

Next: subcommands with groups — building git-style multi-level command hierarchies with @click.group().

Finished reading? Mark it complete to track your progress.

On this page