Output, styling and help text

Click · Essentials · 9 min

A CLI's output and help are its user interface; small touches make tools pleasant and scriptable.

Click's output helpers:

  • click.echo(msg, err=False, nl=True): print to stdout or stderr. Colour codes are removed automatically when the stream is not a terminal, so piping to a file stays clean.
  • click.style(text, fg="green", bold=True) returns a styled string; click.secho(...) styles and echoes in one call. Since Click 8.5 colours are validated and Windows terminals support ANSI codes natively, no colorama needed.
  • click.echo_via_pager(text) shows long output in a pager like less.
  • click.progressbar(iterable, label=...) as a context manager draws a progress bar.
  • click.confirm and click.prompt ask questions (see the prompts lesson).

Shaping help:

  • The docstring is the help body. Paragraphs are re-wrapped; a paragraph starting with \b on its own line is kept as is, for lists or examples.
  • @click.command(epilog="...") adds text at the end, and short_help= overrides the summary used in group listings.
  • metavar="FILE" changes how a value is shown in help; hidden=True hides an option.
  • context_settings={"help_option_names": ["-h", "--help"]} adds -h, and max_content_width widens output.
  • @click.version_option(package_name="mytool") adds --version.

Good practice for scriptable tools: send data to stdout, and messages, warnings and progress to stderr (err=True). Then mytool | jq still works while users see feedback.

Example

import click

@click.command(epilog="See the docs for more examples.",
               context_settings={"help_option_names": ["-h", "--help"]})
@click.option("--out", metavar="FILE", help="Write the report to FILE.")
def report(out):
    """Build a status report.

    \b
    Examples:
      report --out today.txt
      report | less
    """
    click.secho("3 checks passed", fg="green", bold=True)
    click.echo(click.style("1 warning", fg="yellow"), err=True)

report.main(["-h"], prog_name="report", standalone_mode=False)
# Usage: report [OPTIONS]
#
#   Build a status report.
#
#   Examples:
#     report --out today.txt
#     report | less
# ...

Remember

  • echo/secho/style print and colour; colours are stripped when not a terminal
  • Docstrings, epilog, metavar and \b paragraphs shape --help
  • Data to stdout, messages to stderr

Watch out for

  • Printing progress messages to stdout, which corrupts output meant for pipes.

Check yourself

  1. Your tool's output is piped into a file. What happens to colours added with click.secho?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: click.palletsprojects.com/en/stable/utils/

Builds on

Unlocks

Nothing builds on this yet.