Skip to content

Lesson 36 of 52Python power tools

Scripting and Automation

Write Python scripts that behave like real command-line tools: argparse, stdin and stdout, exit codes, subprocess, safe file operations and clean shutdown.

17 min read0/5 questions

Much of the Python written at work is not an app at all. It is the script that renames last quarter's exports, the one CI runs to check migrations, the one that pulls a report every night at 2 a.m. These scripts start as ten lines and quietly become infrastructure. The difference between a throwaway script and one a team can rely on is small but specific: clear arguments and --help, output that composes with other tools, exit codes that CI understands, no shell injection, and files that are never left half-written. This lesson covers each of those.

The shape of a script that lasts

A good script has a main() that takes its arguments as a list and returns an exit code. The bottom of the file hands that code to the operating system:

report.py
import sys
 
 
def main(argv: list[str] | None = None) -> int:
    ...                      # parse argv, do the work
    return 0                 # 0 means success
 
 
if __name__ == "__main__":
    sys.exit(main())

Three things make this shape worth copying. The if __name__ == "__main__" guard means importing the file (for a test, or from another script) does not run it. Passing argv in means a test can call main(["--dry-run", "data/"]) without touching sys.argv. And returning a number means the exit code is decided in one place.

Exit codes are the script's real answer

Shells, CI systems, cron and schedulers do not read your output. They read the exit code. 0 is success and anything else is failure, and a CI step fails the build on any non-zero code. The common conventions:

CodeMeaning
0success
1general failure (the default for an uncaught exception)
2bad usage: wrong or missing arguments (what argparse uses)
130stopped with Ctrl+C (128 + signal number 2)

sys.exit(code) works by raising SystemExit, so finally blocks and with statements still clean up. sys.exit("some message") prints the message to stderr and exits with code 1, which is a tidy way to fail with an explanation.

Python
import sys def main(argv): if not argv: print("error: no input files given", file=sys.stderr) return 2 for name in argv: print("processing", name) return 0 print("exit code:", main([]))print("exit code:", main(["a.csv", "b.csv"])) try: sys.exit("config file missing")except SystemExit as e: print("SystemExit carried:", repr(e.code))
Output
Press Run (⌘ Enter) to see what happens.

stdout, stderr and pipes

Every process starts with three streams: stdin (input), stdout (normal output) and stderr (diagnostics). Keeping them separate is what lets a script fit into a pipeline. Put the data on stdout and everything else, such as progress, warnings and errors, on stderr with print(..., file=sys.stderr) or the logging module, which writes to stderr by default (as you saw in The logging Module). Then a user can redirect the data to a file and still see the errors on screen.

A script in a pipeline
cat access.log: produces linescat access.logproduces linespython3 errors.py: filters linespython3 errors.pyfilters linessort | uniq -c: next toolsort | uniq -cnext toolTerminal: stderrTerminalstderrShell / CI: reads $?Shell / CIreads $?stdinstdoutstderrexit code

The previous command's stdout becomes your stdin. Read sys.stdin line by line and you never hold the whole file in memory.

1/4
python3 errors.py access.log > errors.txt   # data to a file, warnings still on screenecho $?                                     # the exit code of the last commandcat access.log | python3 errors.py | sort | uniq -c

A common convention: read from the files named as arguments, or from stdin if there are none (or if the name is -). Write the core as a function that takes the input and output streams as parameters, and it becomes trivial to test with io.StringIO:

Python
import ioimport sys def keep_errors(lines, out, err): bad = 0 for line in lines: parts = line.split() if len(parts) < 2: bad += 1 continue if parts[1] == "ERROR": out.write(line) if bad: print(f"skipped {bad} malformed lines", file=err) return 0 fake_stdin = io.StringIO( "10:01 INFO boot\n10:02 ERROR db timeout\ngarbage\n10:05 ERROR disk full\n")code = keep_errors(fake_stdin, sys.stdout, sys.stderr)print("exit code:", code)
Output
Press Run (⌘ Enter) to see what happens.

In the real script you would call keep_errors(sys.stdin, sys.stdout, sys.stderr). One more detail for pipelines: when the next command exits early (as head does), your next write raises BrokenPipeError. Long-running filters often catch it and exit quietly.

Arguments with argparse

sys.argv is the raw list of words after the interpreter: sys.argv[0] is the script name and the rest are strings. Parsing it by hand works for one argument and turns ugly at three. argparse, in the standard library, gives you types, defaults, validation, error messages and --help for free.

Python
import argparse parser = argparse.ArgumentParser(prog="export", description="Export orders to CSV.")parser.add_argument("output", help="file to write") # positionalparser.add_argument("--since", help="start date, YYYY-MM-DD")parser.add_argument("--limit", type=int, default=1000)parser.add_argument("--format", choices=["csv", "jsonl"], default="csv")parser.add_argument("-v", "--verbose", action="store_true")parser.add_argument("--tag", action="append", default=[], help="repeatable") args = parser.parse_args(["out.csv", "--limit", "50", "--tag", "eu", "--tag", "vip", "-v"])print(args)print(args.limit + 1, args.verbose, args.tag) try: parser.parse_args(["out.csv", "--format", "xml"])except SystemExit as e: print("argparse exited with code", e.code)
Output
Press Run (⌘ Enter) to see what happens.

Normally you call parser.parse_args() with no list and it reads sys.argv[1:]. Passing a list, as here, is how you test it. Notice what you got for free: --limit arrived as an int, a bad --format was rejected with a clear message on stderr and exit code 2, and dashes in option names become underscores on args.

Tools with several actions use subcommands, like git commit and git push. Each one gets its own parser and options:

Python
import argparse parser = argparse.ArgumentParser(prog="ops")sub = parser.add_subparsers(dest="command", required=True) backup = sub.add_parser("backup", help="copy the database to storage")backup.add_argument("--target", default="s3://backups") restore = sub.add_parser("restore", help="restore from a backup")restore.add_argument("backup_id")restore.add_argument("--dry-run", action="store_true") args = parser.parse_args(["restore", "2026-10-21", "--dry-run"])print(args.command, args.backup_id, args.dry_run) print(parser.format_help())
Output
Press Run (⌘ Enter) to see what happens.

When a tool grows past a few subcommands, or you want rich output and shell completion, Typer builds the same thing from type hints. argparse remains the right choice when the script must run with no dependencies at all.

Quick check
A script is run as python3 sync.py --workers four, where workers was declared with type=int. What happens?
Need a nudge? A hint rules out a wrong answer.

Running other programs: subprocess

Scripts often glue other tools together: git, pg_dump, ffmpeg. Use subprocess.run with the command as a list of arguments:

release.py
import subprocess
 
result = subprocess.run(
    ["git", "log", "-1", "--format=%H"],
    check=True,              # raise CalledProcessError on a non-zero exit code
    capture_output=True,     # collect stdout and stderr instead of printing them
    text=True,               # decode bytes to str
    timeout=30,              # raise TimeoutExpired instead of hanging forever
)
commit = result.stdout.strip()
 
try:
    subprocess.run(["pg_dump", "--file", "backup.sql", "shop"], check=True, timeout=600)
except subprocess.CalledProcessError as e:
    print(f"pg_dump failed with exit code {e.returncode}")
    raise SystemExit(1)

Each keyword fixes a real failure. Without check=True, a failed command is silently ignored and your script carries on as if it worked. Without timeout, a command waiting for a password prompt hangs your nightly job forever. shutil.which("pg_dump") tells you up front whether a tool is installed.

Never build a command string with user input and shell=True. With a list, each element is passed to the program as one argument and no shell ever sees it. With shell=True, the string goes through /bin/sh, so a filename like report.csv; rm -rf ~ runs the second command. If you truly need shell features such as pipes, build the pipeline in Python or pass a fixed string with no outside input. For long-running commands whose output you want line by line as it arrives, use subprocess.Popen with stdout=subprocess.PIPE and iterate over proc.stdout.

Files at scale: pathlib, shutil and tempfile

You met pathlib in Files and JSON. For automation, a few more tools matter. Path.rglob("*.csv") walks a tree. shutil does whole-tree work: copytree, rmtree, move, make_archive. tempfile.TemporaryDirectory() gives you a scratch folder that is deleted when the with block ends, even after an error.

The most important habit is the atomic write from Files and JSON: write to a temporary file in the same directory, then swap it into place with os.replace. The version below adds fsync, so the bytes survive a power cut and not just a crash.

Python
import jsonimport osimport shutilimport tempfilefrom pathlib import Path def write_atomic(path: Path, text: str) -> None: fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name, suffix=".tmp") try: with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(text) f.flush() os.fsync(f.fileno()) # make sure the bytes reached the disk os.replace(tmp, path) # atomic swap on the same filesystem except BaseException: os.unlink(tmp) raise with tempfile.TemporaryDirectory() as root: base = Path(root) for month in ["2026-08", "2026-09"]: (base / "exports" / month).mkdir(parents=True) (base / "exports" / month / "orders.csv").write_text("id,total\n1,9.99\n", encoding="utf-8") found = sorted(p.relative_to(base) for p in base.rglob("*.csv")) print("found:", [str(p) for p in found]) shutil.copytree(base / "exports", base / "backup") archive = shutil.make_archive(str(base / "exports-2026"), "zip", base / "exports") print("archive:", Path(archive).name) state = base / "state.json" write_atomic(state, json.dumps({"last_run": "2026-10-22"})) print(json.loads(state.read_text(encoding="utf-8"))) print("leftover temp files:", list(base.glob("*.tmp"))) print("scratch folder deleted:", not Path(root).exists())
Output
Press Run (⌘ Enter) to see what happens.

os.replace is only atomic within one filesystem, which is why the temporary file goes in the same directory as the target and not in /tmp.

Environment variables

Configuration that changes between machines (a database URL, an API token, a region) comes from environment variables, not hard-coded values. The two ways to read them say different things:

  • os.environ.get("REGION", "eu-west-1") means "optional, with a default".
  • os.environ["DATABASE_URL"] means "required". It raises KeyError when missing, so the script fails at the start rather than an hour in.

Check required settings up front and exit with a message that names the missing variable. A traceback ending in KeyError: 'DATABASE_URL' is correct but unkind.

Python
def load_settings(env): missing = [name for name in ["DATABASE_URL", "API_TOKEN"] if name not in env] if missing: return None, f"missing required environment variables: {', '.join(missing)}" return { "database_url": env["DATABASE_URL"], "region": env.get("REGION", "eu-west-1"), "batch_size": int(env.get("BATCH_SIZE", "500")), }, None print(load_settings({"DATABASE_URL": "postgresql://localhost/shop"}))print(load_settings({"DATABASE_URL": "postgresql://localhost/shop", "API_TOKEN": "t0k", "BATCH_SIZE": "50"}))
Output
Press Run (⌘ Enter) to see what happens.

Note that the function takes the environment as a parameter, for the same reason main takes argv: tests can pass a plain dict.

Signals and clean shutdown

When you press Ctrl+C, Python raises KeyboardInterrupt wherever the program is, so finally blocks run. Catch it at the top of main to print one line instead of a traceback, and return 130.

Schedulers and containers stop programs differently. Docker, Kubernetes and systemd send SIGTERM first and wait a grace period before a forced kill. Python's default reaction to SIGTERM is to die immediately without running finally blocks or atexit functions. Install a handler that turns it into a normal exit:

worker.py
import atexit
import signal
import sys
 
 
def on_sigterm(signum, frame):
    raise SystemExit(143)            # 128 + 15; unwinds the stack so finally blocks run
 
 
signal.signal(signal.SIGTERM, on_sigterm)
atexit.register(lambda: print("flushed metrics", file=sys.stderr))
 
 
def main() -> int:
    try:
        process_queue()
    except KeyboardInterrupt:
        print("interrupted", file=sys.stderr)
        return 130
    finally:
        release_lock()
    return 0

atexit functions run on a normal exit and on sys.exit, but not after os._exit() or a SIGKILL. Nothing runs after SIGKILL, so design long jobs to be safe to restart: write progress atomically and make each step idempotent.

One-file scripts with dependencies

A script that needs one third-party package does not need a whole project. Python's inline script metadata standard (PEP 723) lets you list dependencies in a comment block at the top of the file, and uv run script.py builds a cached environment and runs it. uv for projects covers the details. For anything shared across a team, the block is better than a "please pip install these first" note in a README, because the requirements travel with the file.

Worked example: a bulk renamer with --dry-run

Here is everything together. Phone and camera exports are full of names like IMG_20260412_101500.jpg. The tool renames them to 2026-04-12_10-15-00.jpg from the date in the name. It has a --dry-run flag, which every script that changes or deletes files should have: run it, read what it would do, then run it for real.

Pythonrename_photos.py
import argparseimport reimport sysimport tempfilefrom datetime import datetimefrom pathlib import Path PATTERN = re.compile(r"(?:IMG|VID|PXL)_(\d{8})_(\d{6})") def build_parser(): p = argparse.ArgumentParser(prog="rename_photos") p.add_argument("folder", type=Path) p.add_argument("--dry-run", action="store_true", help="show changes, touch nothing") return p def plan(folder): for path in sorted(folder.iterdir()): m = PATTERN.search(path.stem) if not m: continue taken = datetime.strptime(m.group(1) + m.group(2), "%Y%m%d%H%M%S") yield path, path.with_name(f"{taken:%Y-%m-%d_%H-%M-%S}{path.suffix.lower()}") def main(argv=None): args = build_parser().parse_args(argv) if not args.folder.is_dir(): print(f"error: {args.folder} is not a folder", file=sys.stderr) return 2 clashes = 0 for old, new in plan(args.folder): if new.exists(): print(f"skip {old.name}: {new.name} already exists", file=sys.stderr) clashes += 1 continue print(f"{'would rename' if args.dry_run else 'renamed'} {old.name} -> {new.name}") if not args.dry_run: old.rename(new) return 1 if clashes else 0 with tempfile.TemporaryDirectory() as root: for name in ["IMG_20260412_101500.JPG", "PXL_20260930_221503.mp4", "notes.txt"]: (Path(root) / name).touch() print("exit:", main([root, "--dry-run"])) print("exit:", main([root])) print(sorted(p.name for p in Path(root).iterdir())) print("exit:", main(["/no/such/folder"]))
Output
Press Run (⌘ Enter) to see what happens.

Look at the decisions. It never overwrites: an existing target is skipped and reported, and the exit code says something went wrong. Data goes to stdout, problems to stderr. The planning step is a generator that changes nothing, so dry run and real run share exactly the same logic. A dry-run path that computes things differently from the real path is how "it said it would only touch three files" incidents happen.

Predict the outputPython

What does this print?

import sys

def main():
  try:
      sys.exit(3)
  finally:
      print("cleanup")

try:
  main()
except SystemExit as e:
  print("code", e.code)
Need a nudge? Hints walk you through it.
Match the pairs0/5 matched

Match each need to the standard-library tool.

Choose an item, then its match on the other side.
Quick check
Why is subprocess.run(f"convert {name} out.png", shell=True) dangerous when name comes from a user?
Need a nudge? A hint rules out a wrong answer.
Put it in order4 steps

Put the safe way to update a config file in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
exit code
The number a process returns when it ends. 0 means success; anything else is a failure that shells and CI act on.
stderr
The output stream for diagnostics, kept separate from stdout so data can be piped or redirected cleanly.
argparse
The standard-library parser for command-line arguments, with types, choices, subcommands and automatic --help.
shell injection
Running unintended commands because outside input reached a shell, typically through shell=True.
atomic write
Writing to a temporary file and renaming it over the target, so readers never see a partial file.
dry run
A mode that reports what a command would change without changing anything.
SIGTERM
The polite stop signal schedulers and containers send before a forced kill. Handle it so cleanup runs.