Day 27: Python scripting fundamentals for automation
Why Python is the automation glue
Bash (Phase 1) is great for chaining commands; it gets painful past ~50 lines — no real data structures, fragile string handling. Python fills that gap: readable, batteries-included (os, subprocess, json, pathlib), and it's the default choice when a script needs to parse structured data, call an API, or handle errors gracefully rather than just piping text.
import subprocess
import sys
def run(cmd: list[str]) -> str:
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
print(f'Command failed: {result.stderr}', file=sys.stderr)
sys.exit(1)
return result.stdout.strip()
pods = run(['kubectl', 'get', 'pods', '-o', 'name'])
for pod in pods.splitlines():
print(f'Checking {pod}...')Same exit-code discipline as Bash
Notice sys.exit(1) on failure — the exact same exit-code contract from Phase 1, Day 13. Whatever language you automate in, CI systems and shell pipelines only understand success (0) vs failure (non-zero).
Key terms
- subprocess
- Python's standard way to run external commands and capture their output.
- pathlib
- An object-oriented standard library module for filesystem paths.
What is the main reason to switch from a Bash script to Python as automation grows more complex?