TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Python Automation Scripts

Python Automation Scripts

Bash is perfect until the script needs a dictionary, a JSON API, a retry policy or a unit test. At that point most teams switch to Python: it is installed on nearly every Linux server and CI runner, its standard library covers files, processes, HTTP, JSON and logging, and the code stays readable as it grows. This lesson sets out the skeleton every automation script in this section follows. The Python course covers the language itself.

The skeleton

python
#!/usr/bin/env python3
"""disk-report: list directories over a size limit.

Exit status: 0 = all under the limit, 1 = at least one over, 2 = usage error.
"""
from __future__ import annotations

import argparse
import logging
import sys

log = logging.getLogger("disk-report")


def parse_args(argv: list[str] | None) -> argparse.Namespace:
    p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    p.add_argument("paths", nargs="+")
    p.add_argument("--limit-mb", type=int, default=500)
    return p.parse_args(argv)


def main(argv: list[str] | None = None) -> int:
    args = parse_args(argv)
    ...                      # the real work, returning 0, 1 or 2
    return 0


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
    sys.exit(main())

The parts and their reasons:

Part Why
#!/usr/bin/env python3 + chmod +x runs as ./disk-report with whichever python3 is first on PATH (a venv's, if one is active)
module docstring the help text and the documentation of the exit statuses
main(argv=None) -> int testable: a test calls main(["--limit-mb", "1", "/tmp"]) and checks the return value
sys.exit(main()) turns the return value into the process exit status
if __name__ == "__main__": importing the file (from a test, or another script) does not run it
logging configured only under __main__ libraries and tests decide their own logging setup

Exit statuses from exceptions

An uncaught exception prints a traceback and exits with status 1. That is fine for bugs, but expected failures deserve a clear one-line message and a status the caller can act on. Map them in one place:

python · try it yourself
import sys

class ConfigError(Exception):
    """The input is wrong: exit status 2."""

class CheckFailed(Exception):
    """The work ran but found a problem: exit status 1."""

def work(limit_mb, sizes):
    if limit_mb <= 0:
        raise ConfigError(f"--limit-mb must be positive, got {limit_mb}")
    over = {path: mb for path, mb in sizes.items() if mb > limit_mb}
    for path, mb in sorted(over.items()):
        print(f"{path}: {mb} MB (limit {limit_mb} MB)")
    if over:
        raise CheckFailed(f"{len(over)} path(s) over the limit")
    print("all paths under the limit")

def main(limit_mb, sizes):
    try:
        work(limit_mb, sizes)
    except ConfigError as e:
        print(f"disk-report: error: {e}", file=sys.stdout)   # stderr in a real script
        return 2
    except CheckFailed as e:
        print(f"disk-report: {e}")
        return 1
    except KeyboardInterrupt:
        return 130                                           # 128 + SIGINT, like a shell
    return 0

sizes = {"/var/log": 812, "/var/lib/docker": 4096, "/home": 120}
print("-> exit", main(1000, sizes))
print("-> exit", main(5000, sizes))
print("-> exit", main(0, sizes))
/var/lib/docker: 4096 MB (limit 1000 MB)
disk-report: 1 path(s) over the limit
-> exit 1
all paths under the limit
-> exit 0
disk-report: error: --limit-mb must be positive, got 0
-> exit 2

The browser examples print everything to stdout so the order is easy to follow; in a real script, messages go to sys.stderr (or through logging, which writes to stderr by default).

The real thing: running a script

In the browser you call main() directly. Here is the same pattern as a real file, run by python3 in a Linux container, so you can see real exit statuses, stderr and a traceback:

bash · try it yourself
cat > disk-report <<'PY'
#!/usr/bin/env python3
"""disk-report: list directories over a size limit."""
import os
import sys
from pathlib import Path

def size_mb(path: Path) -> float:
    total = sum(f.stat().st_size for f in path.rglob("*") if f.is_file())
    return total / 1_000_000

def main(argv: list[str]) -> int:
    if len(argv) < 2:
        print("usage: disk-report LIMIT_MB PATH...", file=sys.stderr)
        return 2
    limit = float(argv[0])
    over = 0
    for name in argv[1:]:
        mb = size_mb(Path(name))
        flag = "OVER" if mb > limit else "ok"
        print(f"{flag:4} {mb:8.2f} MB  {name}")
        over += mb > limit
    return 1 if over else 0

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
PY
chmod +x disk-report
mkdir -p data/logs data/cache
head -c 3000000 /dev/zero > data/logs/app.log
head -c 200000 /dev/zero > data/cache/blob
./disk-report 1 data/logs data/cache; echo "-> status $?"
./disk-report 5 data/logs data/cache; echo "-> status $?"
./disk-report;                          echo "-> status $?"
./disk-report one data 2>&1 | tail -n 1; echo "-> status ${PIPESTATUS[0]}"
OVER     3.00 MB  data/logs
ok       0.20 MB  data/cache
-> status 1
ok       3.00 MB  data/logs
ok       0.20 MB  data/cache
-> status 0
usage: disk-report LIMIT_MB PATH...
-> status 2
ValueError: could not convert string to float: 'one'
-> status 1

The last call shows the default for an unexpected error: a traceback (only its last line is shown here) and status

  1. float("one") deserved a usage message instead; CLIs with argparse gets that for free.

Which Python, which libraries?

  • Write for the oldest Python you have to support: check python3 --version on the oldest server or base image. Ubuntu 24.04 ships 3.12, Debian 13 ships 3.13.
  • Prefer the standard library for scripts that are copied to servers: json, pathlib, subprocess, urllib.request, logging, argparse, shutil, tempfile, hashlib. Every third-party import is something to install on every machine.
  • When you do need packages (requests, PyYAML, boto3), do not pip install into the system Python (Debian and Ubuntu block it, PEP 668). Use a virtual environment, or declare the dependencies inline (PEP 723) and let uv run or pipx run build a throwaway environment:
python
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = ["requests>=2.32", "pyyaml>=6"]
# ///
import requests, yaml
...

./tool.py then installs (and caches) exactly those dependencies on first run. The Python packaging course covers virtual environments and uv in depth.

Test yourself

Why write def main(argv=None) -> int and call sys.exit(main())?

  1. It is required by Python
  2. main becomes testable with any argument list, and its return value becomes the exit status
  3. It makes the script faster
  4. It disables tracebacks

What exit status does a Python script have when an exception is not caught?

  1. 0
  2. 1
  3. 2
  4. 130

What does the PEP 723 block (# /// script … dependencies = [...]) allow?

  1. Compiling Python to a binary
  2. Declaring a single-file script's dependencies so tools like uv run can create an environment for it
  3. Disabling the GIL
  4. Running the script without Python