TExcelTAD
Home › Python Packaging: pip, venv, Poetry & uv › Entry Points & Console Scripts

Entry Points & Console Scripts

When you pip install pytest, a pytest command appears on your PATH. Nobody wrote a shell script for it: the package declared an entry point, and the installer generated a small launcher. The same mechanism powers plugin systems (pytest plugins, Flask extensions, Sphinx themes): one package advertises an object under a group name, and another discovers it at run time without importing everything.

Declaring a command

In pyproject.toml, [project.scripts] maps a command name to a module:function:

toml
[project.scripts]
greet = "greet.cli:main"          # a terminal command

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

[project.entry-points."greet.styles"]     # any other group: a plugin registry
plain = "greet.styles:plain"

The function is called with no arguments; it reads sys.argv itself (usually through argparse or click), and its return value becomes the exit code.

The whole round trip

bash · try it yourself
python3 -m venv .venv && . .venv/bin/activate
pip install -q build
mkdir -p greet/src/greet && cd greet
cat > pyproject.toml <<'TOML'
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "greet"
version = "0.1.0"
requires-python = ">=3.13"

[project.scripts]
greet = "greet.cli:main"
TOML
cat > src/greet/__init__.py <<'PY'
def hello(name: str) -> str:
    return f"Hello, {name}!"
PY
cat > src/greet/cli.py <<'PY'
import argparse
from greet import hello

def main() -> int:
    parser = argparse.ArgumentParser(prog="greet")
    parser.add_argument("name", nargs="?", default="world")
    args = parser.parse_args()
    print(hello(args.name))
    return 0
PY
cat > src/greet/__main__.py <<'PY'
from greet.cli import main
raise SystemExit(main())
PY
python -m build -q --wheel > /dev/null 2>&1
echo "--- entry_points.txt in the wheel"
unzip -p dist/*.whl greet-0.1.0.dist-info/entry_points.txt
pip install -q dist/*.whl
echo "--- run it three ways"
greet Ada
python -m greet Grace
../.venv/bin/greet; echo "exit code $?"
echo "--- the generated launcher"
cat "$(command -v greet)"
--- entry_points.txt in the wheel
[console_scripts]
greet = greet.cli:main
--- run it three ways
Hello, Ada!
Hello, Grace!
Hello, world!
exit code 0
--- the generated launcher
#!/home/learner/.venv/bin/python3
import sys
from greet.cli import main
if __name__ == '__main__':
    sys.argv[0] = sys.argv[0].removesuffix('.exe')
    sys.exit(main())

Things to notice:

  • The wheel doesn't contain the greet script itself, only entry_points.txt. The installer writes the launcher, with a shebang pointing at the environment's interpreter. That's why the same wheel works in any venv, and why launchers break when you move a venv.
  • On Windows the installer writes greet.exe instead, a small native launcher with the same job.
  • __main__.py makes python -m greet work too. That's worth adding: it works even when the environment's bin/ isn't on PATH, and python -m pip is exactly this trick.

Plugins: entry points as a registry

Any group name works, and importlib.metadata.entry_points() lists what every installed distribution registered. Here a host package greet looks up styles in the group greet.styles, and a separate distribution, greet-shout, adds one without greet knowing about it:

bash · try it yourself
python3 -m venv .venv && . .venv/bin/activate
mkdir -p host/src/greet plugin/src/greet_shout
cat > host/pyproject.toml <<'TOML'
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "greet"
version = "0.1.0"
[project.entry-points."greet.styles"]
plain = "greet:plain"
TOML
cat > host/src/greet/__init__.py <<'PY'
from importlib.metadata import entry_points

def plain(name): return f"Hello, {name}."

def styles():
    return {ep.name: ep for ep in entry_points(group="greet.styles")}

def hello(name, style="plain"):
    return styles()[style].load()(name)      # import happens only here
PY
cat > plugin/pyproject.toml <<'TOML'
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "greet-shout"
version = "1.0.0"
dependencies = ["greet"]
[project.entry-points."greet.styles"]
shout = "greet_shout:shout"
TOML
echo 'def shout(name): return f"HELLO, {name.upper()}!"' > plugin/src/greet_shout/__init__.py
pip install -q ./host
python -c 'import greet; print(sorted(greet.styles()))'
pip install -q ./plugin
python -c 'import greet; print(sorted(greet.styles())); print(greet.hello("Ada", "shout"))'
python -c 'from importlib.metadata import entry_points; print(entry_points(group="greet.styles")["shout"])'
['plain']
['plain', 'shout']
HELLO, ADA!
EntryPoint(name='shout', value='greet_shout:shout', group='greet.styles')

This is exactly how pytest finds plugins (group pytest11) and how pip install some-plugin can extend an app without changing it.

A runnable model: from entry_points.txt to a call

entry_points.txt is an INI file. Loading an entry point means: parse module:attr, import the module, walk the attribute path. This model uses a dictionary in place of real imports:

python · try it yourself
import configparser

entry_points_txt = """
[console_scripts]
greet = greet.cli:main

[greet.styles]
plain = greet:plain
shout = greet_shout:Styles.shout
"""
modules = {
    "greet": {"plain": lambda n: f"Hello, {n}."},
    "greet.cli": {"main": lambda: print("greet CLI called") or 0},
    "greet_shout": {"Styles": type("Styles", (), {"shout": staticmethod(lambda n: f"HELLO, {n.upper()}!")})},
}

def load(value):
    module, _, attr_path = value.partition(":")
    obj = modules[module]                       # stands in for importlib.import_module
    first, *rest = attr_path.split(".")
    obj = obj[first]
    for part in rest:
        obj = getattr(obj, part)
    return obj

cfg = configparser.ConfigParser()
cfg.read_string(entry_points_txt)
for group in cfg.sections():
    print(f"[{group}]", dict(cfg[group]))
print("exit code", load(cfg["console_scripts"]["greet"])())
for name in cfg["greet.styles"]:
    print(name, "->", load(cfg["greet.styles"][name])("Ada"))
[console_scripts] {'greet': 'greet.cli:main'}
[greet.styles] {'plain': 'greet:plain', 'shout': 'greet_shout:Styles.shout'}
greet CLI called
exit code 0
plain -> Hello, Ada.
shout -> HELLO, ADA!

Test yourself

Who creates the greet executable in .venv/bin?

  1. The build backend, inside the wheel
  2. The installer (pip/uv), from entry_points.txt, with a shebang for that environment's Python
  3. The user, by hand
  4. setuptools at import time

What does a console-script function receive as arguments?

  1. sys.argv
  2. Nothing: it reads sys.argv itself and its return value becomes the exit code
  3. An argparse Namespace
  4. The environment

How can a plugin package add a style to greet without greet being changed?

  1. By monkey-patching greet at import
  2. By registering an entry point in a group that greet queries with importlib.metadata.entry_points()
  3. By editing greet's pyproject.toml
  4. By installing into greet's folder