Your first Click command

Click · Essentials · 8 min

Every Click CLI starts as a decorated function, and the generated help is the first thing users see.

Install with pip install click. A Click program is a Python function decorated with @click.command(). Calling the decorated object parses sys.argv, calls your function with the parsed values, and exits:

@click.command()
def hello():
    click.echo("Hello!")

if __name__ == "__main__":
    hello()

Running python hello.py prints Hello!, and python hello.py --help prints a generated help page. The function's docstring becomes the help text, and the first sentence is used as the short summary in command lists.

click.echo is Click's print. It behaves the same for normal text but works consistently across terminals and platforms, handles bytes, strips ANSI colour codes when output is not a terminal, and accepts err=True to write to stderr.

Some behaviour to know from the start:

  • The decorated object is no longer a plain function but a click.Command. Calling hello() runs the full CLI machinery and ends with sys.exit. To call it from Python without exiting, use hello.main(args, standalone_mode=False) or, in tests, CliRunner.
  • Unknown options produce a usage error with exit code 2 and a short message, so users get helpful feedback automatically.
  • The command name defaults to the function name, with underscores replaced by dashes (def sync_db becomes sync-db).

Example

import click

@click.command()
def hello():
    """Greet the world. Prints a friendly message."""
    click.echo("Hello!")
    click.echo("Warnings go to stderr", err=True)

if __name__ == "__main__":
    hello()

# $ python hello.py
# Hello!
# Warnings go to stderr
# $ python hello.py --help
# Usage: hello.py [OPTIONS]
#
#   Greet the world. Prints a friendly message.
#
# Options:
#   --help  Show this message and exit.

Remember

  • @click.command() turns a function into a CLI with --help
  • The docstring becomes the help text
  • Use click.echo (err=True for stderr) instead of print

Watch out for

  • Calling the command object from other Python code and being surprised when the process exits.

Check yourself

  1. Where does the text shown by --help under the usage line come from?

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

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