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.
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:
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:
| Code | Meaning |
|---|---|
0 | success |
1 | general failure (the default for an uncaught exception) |
2 | bad usage: wrong or missing arguments (what argparse uses) |
130 | stopped 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.
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.
The previous command's stdout becomes your stdin. Read sys.stdin line by line and you never hold the whole file in memory.
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 -cA 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:
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.
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:
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.
python3 sync.py --workers four, where workers was declared with type=int. What happens?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:
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.
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 raisesKeyErrorwhen 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.
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:
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 0atexit 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.
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.
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)Match each need to the standard-library tool.
subprocess.run(f"convert {name} out.png", shell=True) dangerous when name comes from a user?Put the safe way to update a config file in order.
- Tap the steps below in the right order.
- 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.