How to Parse Taskfile YAML in Python

Load a Taskfile.yaml with PyYAML and simulate task execution by returning each task's commands.

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

Requires third-party packages — install first
pip install pyyaml

Python code

36 lines
Python 3.9+
import 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

stdout
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

  1. Use `Path.read_text` with `yaml.safe_load` to read from a file path directly
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Modern tooling

Related tutorials and quizzes for this topic.