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.
Python code
20 linesimport 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
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
- Use `click` or `argparse` to build a CLI with more options for each target.
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.