Python by Contrast
Stdlib scripting glue
Lesson 5 of 5
What you'll learn
- Reach for pathlib, subprocess and json before any third-party package
- Build a real CLI with argparse
- See why Python owns the ops and glue-script niche
The reason Python is preinstalled in every ops runbook is its standard library: file paths, process control, JSON, CLI parsing, and HTTP all ship in the box. A useful script is one file that runs anywhere Python does — no npm install, no lockfile, no build.
pathlib treats paths as objects, folding in what Node splits across path and fs:
import json
from pathlib import Path
for f in sorted(Path("/var/log").glob("*.log")):
print(f.name, f.stat().st_size)
config = json.loads(Path("config.json").read_text())
json.loads / json.dumps are JSON.parse / JSON.stringify — same mental model, different casing.
subprocess — shelling out, safely
subprocess.run takes the command as a list (no shell-injection string splicing), captures output, and can raise on a non-zero exit:
import subprocess
result = subprocess.run(
["git", "status", "--short"], capture_output=True, text=True, check=True
)
print(result.stdout)
argparse — a CLI in five lines
Where a Node script reaches for commander or util.parseArgs, argparse is built in and generates --help for free:
import argparse
parser = argparse.ArgumentParser(description="Tail a log file")
parser.add_argument("path")
parser.add_argument("--lines", type=int, default=10)
args = parser.parse_args()
For quick HTTP, urllib.request is in the box too; scripts that graduate into services usually step up to httpx. Node's builtins have caught up a lot, but the cultural default differs: Python glue stays stdlib-only, which is why a single .py file travels so well between machines and CI images.
Single-file scripts with dependencies
When a script does need a package, uv reads inline script metadata — a small # /// script header listing dependencies — so uv run script.py fetches them into a cached environment. The script is still one portable file.
The challenge is a JS model of a glue script end to end: an argparse-style parser, a JSON transform, and a faked subprocess.run.
Run it. This models a Python ops script: parse CLI args, run a subprocess, and emit JSON — all stdlib moves.
Why is Python such a common choice for ops and glue scripts?
That's the contrast tour: indentation and gradual types, uv-driven tooling, the container-and-dunder data model, an explicit event loop, and a stdlib built for glue. You can now read — and write — the everyday Python you'll meet in real codebases.
Saved on this device. Sign in to sync your progress everywhere.