Makefile Targets for lint, test, and build in Python

This Python script defines common Makefile targets (lint, test, build) as subprocess commands, printing each target's command and executing them with error checking.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 14 views 0 copies

Python code

20 lines
Python 3.9+
import subprocess

TARGETS = {
    "lint": ["ruff", "check", "."],
    "test": ["pytest", "-q"],
    "build": ["python", "-m", "build"],
}


def run(target: str) -> None:
    if target not in TARGETS:
        raise ValueError(f"Unknown target: {target}")
    print(f"Running {target}...")
    subprocess.run(TARGETS[target], check=True)
    print(f"{target} completed successfully")


if __name__ == "__main__":
    for name in TARGETS:
        print(f"{name}: {' '.join(TARGETS[name])}")

Output

stdout
lint: ruff check .
test: pytest -q
build: python -m build

How it works

This script maps logical targets to the exact commands that a Makefile would run, using subprocess.run with check=True to fail fast on any error. The TARGETS dictionary centralizes command definitions, making it easy to add or modify targets in one place. Running with __main__ prints the commands for inspection, while run(target) actually executes them. This pattern is useful for CI systems or local development commands that need consistency across environments.

Common mistakes

  • Forgetting to set `check=True` so errors propagate instead of being silently ignored.
  • Misspelling target names, causing a ValueError that may be hard to trace.
  • Hard-coding commands instead of using the dictionary, leading to duplicated logic.

Variations

  1. Use `click` or `argparse` to build a CLI with more options for each target.
  2. Invoke `make lint` directly via subprocess instead of redefining commands in Python.

Real-world use cases

  • Automating the same lint, test, and build steps in CI pipelines like GitHub Actions.
  • Creating a developer-facing CLI tool that standardizes project commands across a team.
  • Wiring up pre-commit hooks or deployment scripts that must run specific checks before shipping.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Modern tooling

Related tutorials and quizzes for this topic.