Back to Blog

Python Packaging with pyproject.toml - Wheels, pip install, CLI Entry Points Tutorial #40

Sandy LaneSandy Lane

Video: Python Packaging with pyproject.toml - Wheels, pip install, CLI Entry Points Tutorial #40 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Python Packaging with pyproject.toml - Wheels, pip install, CLI Entry Points Tutorial

Packaging Python projects using the modern pyproject.toml standard simplifies distribution and installation. This tutorial covers creating a source-layout package, configuring metadata, building wheel and source distributions, installing locally, and adding CLI entry points with argparse.

Code

# Directory structure:
# mypackage/
# ├── src/
# │   └── mypackage/
# │       ├── __init__.py
# │       └── cli.py
# └── pyproject.toml

# src/mypackage/__init__.py
def greet(name):
  return f"Hello, {name}!"

# src/mypackage/cli.py
import argparse
from mypackage import greet

def main():
  parser = argparse.ArgumentParser(description="Greet someone.")
  parser.add_argument("name", help="Name of the person to greet")
  args = parser.parse_args()
  print(greet(args.name))

if __name__ == "__main__":
  main()

# pyproject.toml
"""
[build-system]
requires = ["setuptools>=61.0", "wheel"]
build-backend = "setuptools.build_meta"

[project]
name = "mypackage"
version = "0.1.0"
description = "A simple greeting package"
authors = [{name = "Your Name", email = "you@example.com"}]
readme = "README.md"
license = {text = "MIT"}
requires-python = ">=3.7"
dependencies = []

[tool.setuptools.packages.find]
where = ["src"]

[project.scripts]
greet = "mypackage.cli:main"
"""

# Build distributions (run in terminal):
# python -m build

# Install the built wheel locally:
# pip install --force-reinstall dist/mypackage-0.1.0-py3-none-any.whl

# Verify installation:
# pip show mypackage
# pip list

# Now you can run the CLI command:
# greet Alice
# Output: Hello, Alice!

Key Points

  • The src layout keeps source code separate from config and build files, improving clarity.
  • pyproject.toml defines build system requirements, project metadata, package discovery, and CLI entry points.
  • Use python -m build to create wheel and source distributions for easy sharing and installation.
  • Install packages locally with pip install pointing to the wheel file and verify with pip show and pip list.
  • Define CLI entry points under [project.scripts] to expose command-line commands linked to Python functions.