How to Parse Taskfile YAML in Python
Load a Taskfile.yaml with PyYAML and simulate task execution by returning each task's commands.
pip install pyyaml
Python code
36 linesimport yaml
from pathlib import Path
def load_taskfile(taskfile_path: str) -> dict:
"""Load and parse a Taskfile.yaml file into a dict."""
data = Path(taskfile_path).read_text()
return yaml.safe_load(data)
def run_task(taskfile: dict, task_name: str) -> dict:
"""Simulate running a task by returning its metadata."""
tasks = taskfile.get("tasks", {})
task = tasks.get(task_name)
if task is None:
raise KeyError(f"Task '{task_name}' not found")
return task
def execute_tasks(taskfile: dict, task_list: list[str]) -> list[str]:
"""Run a list of tasks and return their commands."""
results = []
for name in task_list:
task = run_task(taskfile, name)
cmd = task.get("cmds", task.get("command", "echo no-op"))
results.append(f"{name}: {cmd}")
return results
if __name__ == "__main__":
taskfile = {
"version": "3",
"tasks": {
"build": {"cmds": ["go build"], "desc": "Build app"},
"test": {"cmds": ["go test ./..."], "depends_on": ["build"]},
"lint": {"command": "golangci-lint run"},
},
}
output = execute_tasks(taskfile, ["test", "lint"])
print("\n".join(output))
Output
test: ['go test ./...']
lint: golangci-lint run
How it works
This code reads a YAML Taskfile and converts it into a Python dict using yaml.safe_load to avoid object deserialization risks. The run_task function looks up a task by name and returns its definition, or raises a helpful KeyError. execute_tasks iterates a list of task names, extracts either the cmds list or single command string, and formats the result. The output joins each result with newlines for a clean console display.
Common mistakes
- Forgetting to install PyYAML with pip install pyyaml
- Assuming the key is always 'cmds' when 'command' might be used
- Not checking for missing tasks before accessing their metadata
- Using yaml.load instead of yaml.safe_load for untrusted files
Variations
- Use `Path.read_text` with `yaml.safe_load` to read from a file path directly
- Add dependency execution by walking `depends_on` keys recursively
Real-world use cases
- Parsing your project's Taskfile to debug why a build or test command fails in CI.
- Building internal tooling that inspects task definitions before running them in a scheduler.
- Validating that expected tasks and commands exist before executing them in a monorepo.
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.