Sub topic 7
Exposing a command-line tool with entry points
This chapter assumes you have a working pyproject.toml with a [project] table and a src layout, as in the earlier chapters. It also assumes you can create a virtual environment and run pip install. By the end you will know what the [project.scripts] table does, how pip turns it into a command on the user's PATH, and which mistakes make the command fail.
What an entry point is
An entry point is a name that your package publishes in its installed metadata. The name points to a Python object, written as module.path:attribute. Installers and other programs read these names and act on them.
The most common kind is the console script. You declare a command name and a function. When someone installs your package, pip writes a small executable file into the environment's bin directory (Scripts on Windows). That file imports your function and calls it.
Here is the declaration from the greeter project:
[project.scripts]
greeter = "greeter.cli:main"The key greeter is the command name the user types. The value greeter.cli:main means "import the module greeter.cli, then take the attribute main". The part before the colon is a dotted module path. The part after it is an attribute inside that module.
What happens at install time
The build backend does not create the executable. It only records the entry point in the wheel's entry_points.txt file. The installer (pip, uv, or similar) creates the executable when it installs the wheel.
flowchart LRThe diagram below shows the sequence.
On Linux and macOS the launcher is a short Python script. It looks roughly like this:
#!/tmp/verify/bin/python
import sys
from greeter.cli import main
if __name__ == "__main__":
sys.exit(main())Three consequences follow from this design:
- The launcher passes whatever
main()returns tosys.exit. ReturningNonegives exit status 0. Returning an integer gives that status. Returning a string prints it to stderr and exits with status 1. - The shebang points at the interpreter of the environment where the package was installed. The command always runs with the right dependencies.
- The command exists only after installation. Running
python -m builddoes not create it, and editingpyproject.tomldoes not change an environment that already has the package installed.
Writing a good target function
The spine example reads sys.argv directly. That works for one argument, but it is hard to test. A better pattern takes an optional argument list and returns an exit code:
# src/greeter/cli.py
import argparse
from greeter import greet
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="greeter",
description="Print a greeting.",
)
parser.add_argument("name", nargs="?", default="world")
args = parser.parse_args(argv)
print(greet(args.name))
return 0When the launcher calls main() with no arguments, argv is None. argparse then reads sys.argv[1:], as it normally does. In a test you can pass the arguments directly:
# tests/test_cli.py
from greeter.cli import main
def test_main_prints_greeting(capsys):
assert main(["Ada"]) == 0
assert capsys.readouterr().out == "Hello, Ada!\n"Note that list[str] | None in an annotation needs Python 3.10 or newer at runtime, unless the file starts with from __future__ import annotations. The spine sets requires-python = ">=3.9", so add that import at the top of cli.py, or write Optional[List[str]] from typing.
The function must be importable without side effects. Keep the work inside main() and not at module level. If importing greeter.cli parses arguments or prints output, the launcher and your tests will both break.
Running the command in a development environment
To try the script while you work, install the project in editable mode:
python -m venv .venv
.venv/bin/pip install -e ".[test]"
.venv/bin/greeter AdaEditable mode links the installed package to your source files, so code changes take effect immediately. The launcher and entry_points.txt are not refreshed automatically. If you rename the command or change the target, run pip install -e . again.
Also supporting `python -m`
Some users prefer python -m greeter, which works even when the scripts directory is not on PATH. To support it, add a __main__.py file next to __init__.py:
# src/greeter/__main__.py
import sys
from greeter.cli import main
sys.exit(main())This file needs no entry in pyproject.toml. Python runs it when the package is invoked with -m.
Other entry point tables
[project.scripts] is one of three tables defined by the packaging specification:
| Table | Purpose |
|---|---|
| `[project.scripts]` | Command-line launchers |
| `[project.gui-scripts]` | Launchers that do not open a console window on Windows. On other systems they behave like scripts. |
| `[project.entry-points."group.name"]` | Named hooks in a group that you or another project define |
The third table is how plugin systems work. For example, pytest plugins register under the group pytest11. You can define your own group the same way. This example lets other packages add greeting styles to greeter:
[project.entry-points."greeter.styles"]
shout = "greeter_extras.styles:shout"The host program discovers them at run time:
from importlib.metadata import entry_points
for ep in entry_points(group="greeter.styles"):
style = ep.load()
print(ep.name, style("Ada"))The group= keyword requires Python 3.10 or newer. On Python 3.9, entry_points() returns a dictionary, so use entry_points().get("greeter.styles", []). Alternatively, depend on the importlib_metadata backport. ep.load() imports the module and returns the attribute, so a broken plugin raises an error at that point. Wrap the call in try/except if you want one bad plugin not to stop the others.
Common errors
command not foundafter install. The scripts directory is not onPATH. This is common withpip install --userand with a virtual environment that was never activated. Call the full path, or usepython -m greeter.ModuleNotFoundErrorwhen the command runs. The target inpyproject.tomldoes not match the real layout. With a src layout, the module path starts at the package name (greeter.cli), never atsrc.AttributeErrororImportError: cannot import name 'main'. The part after the colon names a function that does not exist, or a circular import hides it.- Name collisions. Two installed packages that declare the same command name overwrite each other's launcher. Pick a distinctive name. Check PyPI and your system for existing commands before you choose.
- A stale launcher. If the old command still runs after you changed the entry point, reinstall the package. Launchers are created only at install time.
- Printing the return value. Writing
sys.exit(main())insidemainitself, or returning text you meant to print, produces confusing exit statuses. Print output yourself and return an integer.
Verifying the entry point in a built wheel
Check the wheel itself before you upload it. A wheel is a zip file, so Python's standard library can read it:
python -m zipfile -e dist/greeter-0.1.0-py3-none-any.whl /tmp/greeter-unpacked
cat /tmp/greeter-unpacked/greeter-0.1.0.dist-info/entry_points.txtThe output should show:
[console_scripts]
greeter = greeter.cli:mainThen install the wheel into a clean environment and run the command, as in the build chapter. This catches wrong targets before users do.
Exercise
You change greeter = "greeter.cli:main" to hello = "greeter.cli:main" in pyproject.toml. You have an editable install in your virtual environment. You run hello Ada and get "command not found", while greeter Ada still works. What happened, and what is the fix?
Show answer
The launcher files are created by the installer when the package is installed. Editing pyproject.toml does not update an existing environment, even in editable mode. The old greeter launcher is still there and no hello launcher exists. Run pip install -e . again so the installer reads the new metadata and writes the hello launcher.
Exercise
A user reports that greeter exits with status 0 even when the name argument is invalid, and your main() is declared as def main() -> None. How do you make failures visible to shell scripts that call your tool?
Show answer
The launcher calls sys.exit(main()), so the return value becomes the exit status. Change main to return an int, and return a non-zero value (for example 2) on invalid input. Alternatively, call parser.error(...), which prints a message and exits with status 2.