Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 38 ยท Building and Publishing

Entry Points and Command-Line Tools

Turn functions into installed commands with project.scripts, support python -m, build plugin systems with entry point groups, and read them with importlib.metadata.

After pip install black you can type black in a terminal. After pip install pytest, pytest works. Neither package contains a hand-written shell script. They declare an entry point, and the installer creates a small launcher. Entry points also power plugin systems (pytest plugins, Flask extensions, flake8 checks). This lesson shows how to declare, create, discover and test them.

project.scripts: a command from a function

In pyproject.toml:

TOML
[project.scripts]
weather = "weather_cli.main:run"
weather-admin = "weather_cli.admin:main"

[project.gui-scripts]
weather-gui = "weather_cli.gui:main"      # no console window on Windows

The format is command = "package.module:function". On installation, pip writes an executable named weather into the environment's bin (or Scripts on Windows, as weather.exe). It does roughly this:

Python
#!/path/to/env/bin/python
import sys
from weather_cli.main import run
sys.exit(run())

The function takes no arguments and its return value becomes the exit code (None means 0). Read sys.argv or use argparse, click or typer inside it.

Python
# weather_cli/main.py
import argparse

def run(argv=None):
    parser = argparse.ArgumentParser(prog="weather")
    parser.add_argument("city")
    args = parser.parse_args(argv)        # argv=None means sys.argv[1:]
    print(f"Forecast for {args.city}: sunny")
    return 0

Accepting an optional argv parameter makes the function trivial to test without spawning a process.

python -m package: __main__.py

Add a __main__.py to your package so python -m weather_cli works, even before or without the script being on PATH:

Python
# weather_cli/__main__.py
from weather_cli.main import run
raise SystemExit(run())

This also gives you a safe way to call the right installation: python -m weather_cli uses whichever interpreter you named.

What the installer records

The entry points are written to entry_points.txt inside .dist-info, using INI-style sections. That file is the source of truth, and importlib.metadata reads it.

Python Build a wheel that declares a command, install it, run it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

On a real system, pip would additionally create the greet launcher file; here we only see the registry, and ep.load()() does what that launcher does.

Entry point groups: plugins

console_scripts is just one group ([project.scripts] is a shortcut for it). You can define your own groups for plugins, using [project.entry-points."group.name"]:

TOML
# In a plugin package "weather-cli-metric":
[project.entry-points."weather_cli.formatters"]
metric = "weather_cli_metric:MetricFormatter"

Your main program asks for everything registered under that group and loads each one. It does not need to import or even know the plugin packages. Installing a plugin is enough.

flowchart LR
    P1["weather-cli-metric<br/>entry point: metric"] --> R["entry_points.txt<br/>in site-packages"]
    P2["weather-cli-json<br/>entry point: json"] --> R
    A["weather-cli core"] -- "entry_points(group='weather_cli.formatters')" --> R
    R --> A

Plugins register themselves at install time; the host discovers them at run time.

Real systems built this way: pytest (pytest11 group), Flask CLI commands, Sphinx extensions, Pygments lexers, Airflow providers, and flake8 plugins.

Python A tiny plugin system using entry_points

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Testing a command-line tool

Because you wrote run(argv=None), tests call it directly with a list and capture output, with no subprocess needed:

Python
def test_prints_forecast(capsys):
    assert run(["Oslo"]) == 0
    assert "Oslo" in capsys.readouterr().out

Add one end-to-end test in CI that installs the built wheel in a clean environment and runs the real command (weather --help), to confirm the entry point itself is wired correctly.

Making CLIs pleasant

  • Use argparse (standard library), or a library like click or typer for subcommands and completion.
  • Return exit codes: 0 success, non-zero on failure. SystemExit("message") prints to stderr and exits with 1.
  • Provide --version, reading importlib.metadata.version("weather-cli") so the number never drifts from the package metadata.
  • Do not read the config or write files at import time. The entry-point module is imported on every launch, so slow imports make every command feel slow. Import heavy libraries inside the functions that need them.
Python --version without duplicating the version number

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

On Windows the launcher is an .exe; on macOS and Linux it is a script with a #! line pointing at the environment's Python. Because it hard-codes the interpreter, scripts break if you move the environment: another reason to recreate rather than relocate.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does weather = "weather_cli.main:run" under [project.scripts] create?

    The value is module:function. The installer writes an executable that imports and calls it, using the return value as the exit code.
  2. 2. Where are entry points stored after installation?

    importlib.metadata.entry_points() reads those files from all installed distributions.
  3. 3. How can a host program load plugins it has never heard of?

    Plugins register a name under an agreed group; the host discovers and loads them.
  4. 4. Why should a CLI function accept an optional argv parameter?

    parse_args(None) reads sys.argv, while tests can pass a list.

Summary

  • [project.scripts] maps command names to module:function; installers generate launchers.
  • Add __main__.py to support python -m package.
  • Entry points live in entry_points.txt in .dist-info and are read with importlib.metadata.entry_points.
  • Custom groups under [project.entry-points."group"] form a plugin system with no hard imports.
  • Accept an optional argv, return exit codes, and import lazily for fast startup.
  • Read --version from package metadata so it never drifts.

Next: Versioning and Changelogs