Concept Explanation
A script that runs once on your laptop and a script that runs unattended against production are different kinds of program. The second one needs to be safe when it fails halfway, safe when it runs twice, and clear about what it is about to do.
pathlib, Not Strings
from pathlib import Path
# Cross-platform, readable, and it does the right thing
config = Path.home() / ".config" / "myapp" / "settings.toml"
config.parent.mkdir(parents=True, exist_ok=True) # no error if it exists
for log in Path("/var/log/myapp").glob("*.log"):
if log.stat().st_size > 100_000_000:
print(f"{log.name} is {log.stat().st_size / 1e6:.0f} MB")
os.path.join and string concatenation both work; pathlib is shorter, harder to get wrong, and handles Windows separators for free. exist_ok=True and missing_ok=True are the idempotency flags.
subprocess, Done Right
import subprocess
result = subprocess.run(
["git", "rev-parse", "HEAD"], # a LIST, never a string
capture_output=True,
text=True, # str, not bytes
check=True, # raise on non-zero exit
timeout=30, # never hang forever
)
print(result.stdout.strip())
Four rules, each preventing a specific failure:
| Rule | Prevents |
|---|---|
Pass a list, not shell=True | Shell injection |
check=True | Silently ignoring a failed command |
timeout= | A hung process blocking forever |
text=True | Byte/string confusion |
shell=True with any interpolated value is a shell-injection vulnerability. If a filename contains ; rm -rf /, the shell will do what it says. Pass a list and there is no shell to exploit.
Idempotency
An idempotent operation gives the same result whether it runs once or ten times. This matters because automation gets retried — by a human, by CI, by a scheduler.
| Not idempotent | Idempotent |
|---|---|
mkdir dir | mkdir -p dir / exist_ok=True |
useradd bob | create only if absent |
echo x >> file | check whether the line is present first |
INSERT | INSERT ... ON CONFLICT DO NOTHING |
Dry Run First
Any script that changes things should be able to describe what it would do without doing it:
parser.add_argument("--dry-run", action="store_true",
help="print actions without performing them")
This is the single most valuable feature in an operations script. It turns "I hope this is right" into something reviewable, and it belongs in the code from the first version — not bolted on after an incident.
Exit Codes
Exit 0 for success, non-zero for failure. Schedulers, CI, and shell && chains all read the exit code and nothing else. sys.exit(1) on failure is what makes your script composable.
Signals and Cleanup
A deploy script killed mid-run must not leave a half-written file or a stale lock. Handle SIGTERM, finish the current unit of work, and clean up:
import signal
shutting_down = False
def handle_term(signum, frame):
global shutting_down
shutting_down = True # let the loop exit cleanly
signal.signal(signal.SIGTERM, handle_term)
Write to a temporary file and rename it into place — os.replace is atomic on the same filesystem, so a reader never sees a partial file.
Locking
Two copies of a cron job running at once will corrupt something. A PID file plus a check, or a directory as a lock (mkdir is atomic), prevents overlap.
Logging, Not print
Unattended scripts need timestamps and levels in their output, because the only record of what happened is that output. Everything from the previous lesson applies.
Code Example #1 (Basic)
pathlib, safe subprocess, and atomic writes.
import subprocess
import sys
import tempfile
from pathlib import Path
# ==================== pathlib ====================
work = Path(tempfile.mkdtemp()) / "myapp"
work.mkdir(parents=True, exist_ok=True) # idempotent: no error if it exists
work.mkdir(parents=True, exist_ok=True) # safe to run again
print("=== pathlib ===")
print(f" created {work}")
print(f" parent: {work.parent.name}")
print(f" exists: {work.exists()}, is_dir: {work.is_dir()}")
# Write some files to inspect
for i in range(3):
(work / f"app-{i}.log").write_text("x" * (1000 * (i + 1)))
(work / "notes.txt").write_text("not a log")
print(" files over 1500 bytes:")
for path in sorted(work.glob("*.log")):
size = path.stat().st_size
if size > 1500:
print(f" {path.name:<12} {size:>6} bytes")
# Deleting idempotently
(work / "notes.txt").unlink(missing_ok=True)
(work / "notes.txt").unlink(missing_ok=True) # no error the second time
print(f" notes.txt removed twice without error\n")
# ==================== subprocess ====================
def run(cmd: list[str], timeout: int = 30) -> str:
"""The safe default: list args, no shell, check, timeout, text."""
try:
result = subprocess.run(cmd, capture_output=True, text=True,
check=True, timeout=timeout)
return result.stdout.strip()
except subprocess.CalledProcessError as exc:
print(f" command failed (exit {exc.returncode}): {' '.join(cmd)}")
print(f" stderr: {exc.stderr.strip()[:80]}")
raise
except subprocess.TimeoutExpired:
print(f" command timed out after {timeout}s: {' '.join(cmd)}")
raise
except FileNotFoundError:
print(f" command not found: {cmd[0]}")
raise
print("=== subprocess ===")
print(f" python version: {run([sys.executable, '--version'])}")
# check=True turns a failed command into an exception you cannot ignore
try:
run([sys.executable, "-c", "import sys; sys.exit(3)"])
except subprocess.CalledProcessError:
print(" a non-zero exit raised, as it should")
# Why shell=True is dangerous
untrusted_filename = "report.txt; echo INJECTED"
print(f"\n untrusted input: {untrusted_filename!r}")
print(" shell=True would execute the 'echo INJECTED' part.")
safe = subprocess.run([sys.executable, "-c", "import sys; print(len(sys.argv[1]))",
untrusted_filename], capture_output=True, text=True)
print(f" passing a list treats it as one argument of length {safe.stdout.strip()}\n")
# ==================== Atomic writes ====================
def write_atomic(path: Path, content: str) -> None:
"""A reader never sees a partial file: write to a temp, then rename."""
tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(content)
tmp.replace(path) # atomic on the same filesystem
target = work / "config.json"
print("=== Atomic write ===")
write_atomic(target, '{"version": 1}')
print(f" wrote {target.name}: {target.read_text()}")
write_atomic(target, '{"version": 2}')
print(f" replaced atomically: {target.read_text()}")
print(f" no .tmp left behind: {list(p.name for p in work.glob('*.tmp'))}")
The run helper is worth copying verbatim. Every one of its four arguments prevents a failure mode that has taken down real systems.
Code Example #2 (Intermediate)
A complete maintenance script: dry-run, locking, signal handling, and a proper exit code.
import argparse
import logging
import os
import signal
import sys
import tempfile
import time
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from pathlib import Path
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-7s %(message)s",
datefmt="%H:%M:%S",
stream=sys.stdout,
)
logger = logging.getLogger("cleanup")
# ==================== Cooperative shutdown ====================
class Shutdown:
"""Set a flag on SIGTERM/SIGINT so loops finish the current item and stop."""
def __init__(self):
self.requested = False
for sig in (signal.SIGTERM, signal.SIGINT):
try:
signal.signal(sig, self._handle)
except (ValueError, OSError):
pass # not the main thread, or unsupported
def _handle(self, signum, frame):
logger.warning("received signal %s -- finishing current item", signum)
self.requested = True
# ==================== A lock so two copies never overlap ====================
class DirLock:
"""mkdir is atomic, which makes it a portable lock."""
def __init__(self, path: Path):
self.path = path
def __enter__(self):
try:
self.path.mkdir() # fails if another run holds it
except FileExistsError:
owner = (self.path / "pid").read_text().strip() \
if (self.path / "pid").exists() else "unknown"
raise RuntimeError(f"another run is in progress (pid {owner})")
(self.path / "pid").write_text(str(os.getpid()))
return self
def __exit__(self, *exc):
(self.path / "pid").unlink(missing_ok=True)
self.path.rmdir()
return False
# ==================== The work, with a dry-run mode ====================
@dataclass
class Report:
scanned: int = 0
deleted: int = 0
bytes_freed: int = 0
skipped: list[str] = field(default_factory=list)
errors: list[str] = field(default_factory=list)
def summary(self, dry_run: bool) -> str:
verb = "would free" if dry_run else "freed"
return (f"scanned {self.scanned}, "
f"{'would delete' if dry_run else 'deleted'} {self.deleted}, "
f"{verb} {self.bytes_freed / 1e6:.2f} MB, "
f"{len(self.skipped)} skipped, {len(self.errors)} errors")
def prune_old_logs(root: Path, older_than_days: int, dry_run: bool,
shutdown: Shutdown) -> Report:
report = Report()
cutoff = datetime.now(timezone.utc) - timedelta(days=older_than_days)
for path in sorted(root.rglob("*.log")):
if shutdown.requested:
logger.warning("stopping early at %s", path.name)
break
report.scanned += 1
try:
modified = datetime.fromtimestamp(path.stat().st_mtime, timezone.utc)
if modified >= cutoff:
report.skipped.append(path.name)
continue
size = path.stat().st_size
age = (datetime.now(timezone.utc) - modified).days
if dry_run:
logger.info("[dry-run] would delete %s (%d days old, %.1f KB)",
path.name, age, size / 1024)
else:
path.unlink()
logger.info("deleted %s (%d days old, %.1f KB)",
path.name, age, size / 1024)
report.deleted += 1
report.bytes_freed += size
except OSError as exc:
logger.error("could not process %s: %s", path.name, exc)
report.errors.append(path.name)
return report
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Delete log files older than N days.")
parser.add_argument("root", type=Path, help="directory to scan")
parser.add_argument("--older-than", type=int, default=30, metavar="DAYS")
parser.add_argument("--dry-run", action="store_true",
help="report what would happen without deleting")
parser.add_argument("-v", "--verbose", action="store_true")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
if args.verbose:
logger.setLevel(logging.DEBUG)
if not args.root.is_dir():
logger.error("not a directory: %s", args.root)
return 2 # distinct code: bad usage
shutdown = Shutdown()
lock_path = args.root / ".cleanup.lock"
try:
with DirLock(lock_path):
logger.info("scanning %s for logs older than %d days%s",
args.root, args.older_than,
" (DRY RUN)" if args.dry_run else "")
report = prune_old_logs(args.root, args.older_than,
args.dry_run, shutdown)
logger.info("%s", report.summary(args.dry_run))
except RuntimeError as exc:
logger.error("%s", exc)
return 3 # distinct code: already running
except Exception:
logger.exception("unexpected failure")
return 1
if report.errors:
return 1 # partial failure
return 0
# ==================== Demonstration ====================
sandbox = Path(tempfile.mkdtemp()) / "logs"
(sandbox / "archive").mkdir(parents=True)
now = time.time()
for name, age_days in [("app.log", 0), ("app.1.log", 10), ("app.2.log", 45),
("archive/old.log", 400), ("archive/recent.log", 2)]:
path = sandbox / name
path.write_text("log data " * 200)
os.utime(path, (now - age_days * 86400, now - age_days * 86400))
print("=== Dry run first: nothing is deleted ===")
code = main([str(sandbox), "--older-than", "30", "--dry-run"])
print(f" exit code {code}; files still present: "
f"{len(list(sandbox.rglob('*.log')))}\n")
print("=== Now for real ===")
code = main([str(sandbox), "--older-than", "30"])
print(f" exit code {code}; files remaining: "
f"{sorted(p.name for p in sandbox.rglob('*.log'))}\n")
print("=== Idempotent: a second run finds nothing left to do ===")
code = main([str(sandbox), "--older-than", "30"])
print(f" exit code {code}\n")
print("=== The lock rejects a concurrent run ===")
(sandbox / ".cleanup.lock").mkdir()
(sandbox / ".cleanup.lock" / "pid").write_text("99999")
code = main([str(sandbox)])
print(f" exit code {code} (3 = already running)")
(sandbox / ".cleanup.lock" / "pid").unlink()
(sandbox / ".cleanup.lock").rmdir()
print("\nExit codes: 0 ok, 1 partial failure, 2 bad usage, 3 lock held.")
print("A scheduler reads that number and nothing else -- make it mean something.")
The dry-run output and the real output come from the same code path, differing only in whether path.unlink() is called. That is what makes the dry run trustworthy — a separate "preview" implementation would drift from the real one and lie to you.
Common Mistakes
shell=Truewith interpolated input: a filename containing;becomes command execution. Pass a list.- No
check=True: a failed command returns quietly and the script carries on as if it worked. - No
timeout=: a hunggit fetchorsshblocks the job forever and the scheduler never fires again. - No dry-run mode: the first real run is the test, in production.
- Always exiting 0: CI and schedulers see success no matter what happened.
- Non-idempotent operations: a retry duplicates rows, appends the line twice, or fails on "already exists".
- Non-atomic writes: a crash mid-write leaves a truncated config file that the next reader chokes on.
- No locking: two overlapping cron runs corrupt shared state.
- Ignoring
SIGTERM: the container is killed mid-operation and leaves inconsistent state behind. - String path arithmetic:
"/" + namebreaks on Windows and on names with separators. Usepathlib. print()instead of logging: no timestamps, so you cannot correlate the output with an incident.- Deleting based on a name pattern without checking mtime: today's file matches the glob too.
os.walkmutating what it iterates: deleting during a walk can skip entries. Collect first, then act.- No error summary: a script that logs fifty failures and exits 0 has told the scheduler nothing.
Best Practices
- Add
--dry-runfrom the first version, and make it share the real code path. - Always
subprocess.run(list, check=True, timeout=N, text=True)— nevershell=Truewith interpolation. - Make every operation idempotent:
exist_ok=True,missing_ok=True, check-then-create, upsert. - Write to a temp file and
replace()so readers never see a partial file. - Return meaningful exit codes — 0 success, 1 failure, and distinct codes for distinct problems.
- Take a lock if the script can be scheduled or triggered concurrently.
- Handle
SIGTERMcooperatively: finish the current item, clean up, exit. - Use
pathlibfor every path operation. - Log with timestamps and levels, never
print(), and log what you are about to do before doing it. - Report a summary at the end: counts scanned, changed, skipped, failed.
- Use
argparsewith help text so the script documents itself. - Validate inputs before acting — check the directory exists before walking it.
- Collect the work list first, then act on it, rather than mutating during iteration.
- Test against a temporary sandbox, as the demonstration above does, not against real infrastructure.
Practice Exercises
- The Safe Runner: Write a
run(cmd)helper usingsubprocess.runwith a list,check=True,timeout=30, andtext=True. Show it raising on a non-zero exit, on a timeout, and on a missing binary — with a clear message for each. - The Dry Run: Write a script that deletes files older than N days, with a
--dry-runflag that shares the same code path. Create a sandbox of files with backdated mtimes, run it dry, confirm nothing was deleted, then run it for real. - The Idempotent Script: Add a directory-based lock and a
SIGTERMhandler to the script above, then prove three things: a second concurrent run exits with a distinct code, a second sequential run is a no-op, and every path usespathlibrather than string concatenation.