Claude Code for PyInvoke: Python Task Runner — Claude Skills 360 Blog
Blog / AI / Claude Code for PyInvoke: Python Task Runner
AI

Claude Code for PyInvoke: Python Task Runner

Published: January 31, 2028
Read time: 5 min read
By: Claude Skills 360

PyInvoke is a Python task runner. pip install invoke. Task: from invoke import task. @task def test(c): c.run("pytest"). Run: invoke test. Context: c.run("cmd") — runs shell command. c.run("cmd", echo=True) — print command. c.run("cmd", warn=True) — don’t raise on non-zero exit. c.run("cmd", hide=True) — suppress output. c.run("cmd", pty=True) — allocate pseudo-terminal (color output). Result: result = c.run("cmd"). result.stdout, result.stderr, result.exited, result.ok. Dependencies: @task(pre=[clean]). @task(pre=[build], post=[notify]). @task(pre=[call(setup, env="prod")]) — pass args. Namespace: from invoke import task, Collection. ns = Collection("deploy"). ns.add_task(build). ns.add_task(push). Module: from invoke import Collection; ns = Collection.from_module(deploy_module). Help: @task(help={"env": "target environment (prod/staging)"}). Default task: @task(default=True). List tasks: invoke --list. Prompt: from invoke.watchers import Responder; responder = Responder(pattern=r"Password:", response="secret\n"). c.run("ssh-add", watchers=[responder]). Config: invoke.yaml or .invoke.yaml — set defaults. c.config.run.echo = True. Parallel: c.run("cmd &") or use concurrent.futures inside task. Claude Code generates invoke task files, pre/post dependency chains, and collection-based task modules.

CLAUDE.md for PyInvoke

## PyInvoke Stack
- Version: invoke >= 2.2 | pip install invoke
- Task: @task def name(c): c.run("shell command")
- Options: @task def fn(c, env="prod"): ... → invoke fn --env staging
- Deps: @task(pre=[clean, build]) — run clean, build before this task
- Namespace: Collection("group").add_task(fn) → invoke group.fn
- Result: result = c.run("cmd"); result.ok | result.stdout | result.exited
- Config: .invoke.yaml for project defaults | c.config.run.echo = True

PyInvoke Task Runner Pipeline

# tasks.py — PyInvoke task definitions for test, lint, build, and deploy
from __future__ import annotations

import os
import sys
from pathlib import Path

from invoke import Collection, task
from invoke.watchers import Responder


# ─────────────────────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────────────────────

PROJECT_ROOT = Path(__file__).parent
SRC_DIR      = PROJECT_ROOT / "src"
DIST_DIR     = PROJECT_ROOT / "dist"


def _python(c) -> str:
    """Return the Python binary path — respects virtual environments."""
    return sys.executable


# ─────────────────────────────────────────────────────────────────────────────
# 1. Setup and environment
# ─────────────────────────────────────────────────────────────────────────────

@task(
    help={"extras": "comma-separated pip extras (e.g. dev,test)"},
    default=True,
)
def install(c, extras="dev"):
    """Install project dependencies."""
    extras_flag = f"[{extras}]" if extras else ""
    c.run(f"{_python(c)} -m pip install -e '.{extras_flag}'", echo=True)


@task
def clean(c):
    """Remove build artefacts and cache directories."""
    dirs_to_clean = ["dist", "build", ".mypy_cache", ".pytest_cache", "htmlcov"]
    for d in dirs_to_clean:
        c.run(f"rm -rf {d}", warn=True, hide=True)
    c.run("find . -type d -name '__pycache__' -exec rm -rf {} + 2>/dev/null", warn=True, hide=True)
    c.run("find . -name '*.pyc' -delete 2>/dev/null", warn=True, hide=True)
    print("Clean: done")


# ─────────────────────────────────────────────────────────────────────────────
# 2. Code quality
# ─────────────────────────────────────────────────────────────────────────────

@task(
    help={
        "fix":  "auto-fix issues where possible (default: False)",
        "path": "path to lint (default: src/)",
    }
)
def lint(c, fix=False, path="src/"):
    """Run ruff linter. Pass --fix to auto-correct."""
    fix_flag = "--fix" if fix else ""
    c.run(f"ruff check {fix_flag} {path}", echo=True)


@task(help={"path": "path to format (default: .)"})
def fmt(c, path="."):
    """Format code with ruff formatter."""
    c.run(f"ruff format {path}", echo=True)


@task(help={"strict": "enable strict mode (default: False)"})
def typecheck(c, strict=False):
    """Run mypy type checker."""
    strict_flag = "--strict" if strict else ""
    c.run(f"mypy {strict_flag} {SRC_DIR}", echo=True)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Testing
# ─────────────────────────────────────────────────────────────────────────────

@task(
    help={
        "cov":     "enable coverage (default: True)",
        "verbose": "verbose output (default: False)",
        "k":       "pytest -k expression to filter tests",
        "fast":    "skip slow tests (default: False)",
    }
)
def test(c, cov=True, verbose=False, k="", fast=False):
    """Run pytest test suite with optional coverage."""
    flags: list[str] = []
    if cov:
        flags += ["--cov=src", "--cov-report=term-missing", "--cov-report=html"]
    if verbose:
        flags.append("-v")
    if k:
        flags.append(f"-k '{k}'")
    if fast:
        flags.append("-m 'not slow'")
    flags_str = " ".join(flags)
    c.run(f"{_python(c)} -m pytest {flags_str}", echo=True, pty=True)


@task(
    help={"module": "module to benchmark (default: all)"},
)
def bench(c, module=""):
    """Run pytest-benchmark benchmarks."""
    pattern = f"tests/test_{module}.py" if module else "tests/"
    c.run(
        f"{_python(c)} -m pytest {pattern} --benchmark-only --benchmark-sort=mean",
        echo=True,
        pty=True,
    )


# ─────────────────────────────────────────────────────────────────────────────
# 4. Build
# ─────────────────────────────────────────────────────────────────────────────

@task(pre=[clean])
def build(c):
    """Build source and wheel distributions."""
    c.run(f"{_python(c)} -m build", echo=True)
    DIST_DIR.mkdir(exist_ok=True)
    result = c.run("ls -lh dist/", hide=True)
    print(result.stdout.strip())


@task(pre=[lint, typecheck, test, build])
def release_check(c):
    """Run full quality gate before release: lint → typecheck → test → build."""
    print("Release check passed.")


# ─────────────────────────────────────────────────────────────────────────────
# 5. Docker
# ─────────────────────────────────────────────────────────────────────────────

@task(
    help={
        "tag":  "image tag (default: latest)",
        "push": "push to registry after build (default: False)",
    }
)
def docker_build(c, tag="latest", push=False):
    """Build Docker image."""
    image = f"myapp:{tag}"
    c.run(f"docker build -t {image} .", echo=True)
    if push:
        c.run(f"docker push {image}", echo=True)


@task(help={"env": "environment: dev or prod (default: dev)"})
def docker_up(c, env="dev"):
    """Start Docker Compose services."""
    file_flag = f"-f docker-compose.{env}.yml" if env != "dev" else ""
    c.run(f"docker compose {file_flag} up -d", echo=True, pty=True)


@task
def docker_down(c):
    """Stop Docker Compose services."""
    c.run("docker compose down", echo=True)


# ─────────────────────────────────────────────────────────────────────────────
# 6. Deployment
# ─────────────────────────────────────────────────────────────────────────────

@task(
    help={
        "env":    "target: staging or production (default: staging)",
        "branch": "git branch to deploy (default: HEAD)",
    }
)
def deploy(c, env="staging", branch="HEAD"):
    """Deploy application to target environment."""
    if env == "production":
        # Confirm before production deploy
        answer = input("Deploy to PRODUCTION? [y/N] ").strip().lower()
        if answer != "y":
            print("Aborted.")
            return

    sha = c.run(f"git rev-parse --short {branch}", hide=True).stdout.strip()
    print(f"Deploying {sha} to {env}…")

    steps = [
        f"./scripts/deploy.sh {env} {sha}",
        f"./scripts/smoke_test.sh {env}",
    ]
    for step in steps:
        result = c.run(step, echo=True, warn=True)
        if not result.ok:
            raise SystemExit(f"Deploy step failed: {step}")

    print(f"Deployed {sha} to {env} successfully.")


# ─────────────────────────────────────────────────────────────────────────────
# 7. Database
# ─────────────────────────────────────────────────────────────────────────────

@task(help={"env": "environment (default: development)"})
def migrate(c, env="development"):
    """Run database migrations."""
    c.run(f"APP_ENV={env} alembic upgrade head", echo=True)


@task
def db_shell(c):
    """Open an interactive psql session (allocates a PTY for the REPL)."""
    db_url = os.environ.get("DATABASE_URL", "postgresql://localhost/myapp_dev")
    c.run(f"psql {db_url}", pty=True)   # pty=True needed for interactive apps


# ─────────────────────────────────────────────────────────────────────────────
# 8. Watchers — auto-respond to interactive prompts
# ─────────────────────────────────────────────────────────────────────────────

@task
def add_ssh_key(c):
    """Add SSH key to agent — auto-responds to passphrase prompt."""
    passphrase = os.environ.get("SSH_PASSPHRASE", "")
    responder = Responder(
        pattern=r"Enter passphrase",
        response=f"{passphrase}\n",
    )
    c.run("ssh-add ~/.ssh/id_ed25519", watchers=[responder], hide=True)
    print("SSH key added.")


# ─────────────────────────────────────────────────────────────────────────────
# 9. Collection — organize tasks into namespaces
# ─────────────────────────────────────────────────────────────────────────────

# Top-level namespace groups
ci_ns = Collection("ci")
ci_ns.add_task(lint)
ci_ns.add_task(typecheck)
ci_ns.add_task(test)
ci_ns.add_task(bench)

docker_ns = Collection("docker")
docker_ns.add_task(docker_build, name="build")
docker_ns.add_task(docker_up,    name="up")
docker_ns.add_task(docker_down,  name="down")

db_ns = Collection("db")
db_ns.add_task(migrate)
db_ns.add_task(db_shell, name="shell")

# Root namespace
ns = Collection()
ns.add_task(install)
ns.add_task(clean)
ns.add_task(fmt)
ns.add_task(build)
ns.add_task(release_check)
ns.add_task(deploy)
ns.add_task(add_ssh_key, name="ssh-key")
ns.add_collection(ci_ns)
ns.add_collection(docker_ns)
ns.add_collection(db_ns)

For the Makefile alternative — a Makefile runs shell commands directly without Python’s import system, cannot easily pass typed arguments (everything is a string), requires GNU Make to be installed, mixes shell syntax with build rules in a single non-Python file, and calls Python scripts as subprocesses rather than importing them, while PyInvoke tasks are plain Python functions that can import your application code directly, receive typed CLI arguments with invoke test --k auth, show rich --help including argument descriptions, and compose with pre=[clean, build] dependency chains without shell variable escaping. For the nox / tox alternative — nox and tox are optimized for running test suites in isolated virtual environments with matrix-parametrized Python versions, while PyInvoke is a general task runner for the full dev lifecycle: linting, building, Docker, deployment, database migrations, and interactive prompts via Responder watchers — use nox for multi-Python CI test matrices and invoke for everything else in your project workflow. The Claude Skills 360 bundle includes PyInvoke skill sets covering @task with help strings and typed CLI options, c.run echo/warn/hide/pty flags, result.ok and result.stdout assertion, pre/post dependency chains, Collection namespace grouping, add_collection for modular task libraries, Responder watchers for interactive prompt automation, pty=True for REPL and colored output, invoke —list discovery, and compose tasks into a full lint-test-build-deploy pipeline. Start with the free tier to try Python task runner code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free