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 likeless.click.progressbar(iterable, label=...)as a context manager draws a progress bar.click.confirmandclick.promptask questions (see the prompts lesson).
Shaping help:
- The docstring is the help body. Paragraphs are re-wrapped; a paragraph starting with
\bon its own line is kept as is, for lists or examples. @click.command(epilog="...")adds text at the end, andshort_help=overrides the summary used in group listings.metavar="FILE"changes how a value is shown in help;hidden=Truehides an option.context_settings={"help_option_names": ["-h", "--help"]}adds-h, andmax_content_widthwidens 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.