Automation runs when nobody is watching, so it must say clearly what it did and fail loudly when it could not. Python gives you the pieces: argparse for a real command-line interface, exceptions with specific except clauses, the logging module with levels, and exit codes that cron, CI, and shell scripts understand. This lesson turns a cleanup script into a tool with --dry-run, and shows the two habits that make automation lie: except: pass, and logs printed to stdout where the data goes.
Difficulty: Intermediate · Know this first: Lesson 35, Lesson 25
This bar adds up minutes to run the tool and trust what it says. It is a worked example, not a measurement. The exceptions and streams hops are where a tool starts to lie.
Set how many deletes fail and how the code handles errors. See what the logs and the exit code say.
Lying: nothing was removed, nothing was logged, and it exits 0
Three questions. No score is saved anywhere — this is just you against the material.
Reliable command-line tools grow in four levels: exceptions, interfaces, observable runs, and tools other teams depend on.
At the basic level you handle expected errors.
try/except SpecificError as e/else/finally.raise ValueError("clear message"); built-in errors: ValueError, KeyError, FileNotFoundError, PermissionError, TimeoutError.sys.exit(code).Where it breaks: catching Exception around a whole function, so a typo becomes "it did nothing".
Try it: Basic
Which except clause also catches Ctrl+C (KeyboardInterrupt)?
Now do it: Search your scripts for bare except: and replace each with a specific exception.
At the intermediate level tools are pleasant and safe to use.
store_true flags, -v counts, and subcommands.--dry-run for anything destructive; validation before the first change.Try it: Intermediate
How should a tool react to --older-than -5?
Now do it: Add a type function to argparse that rejects non-positive integers.
At the advanced level every run can be audited.
logging configured once: levels, format with timestamps, stderr or the journal.finally or context managers; signal handling for SIGTERM.Try it: Advanced
Where should logging.basicConfig be called?
Now do it: Move logging configuration in one tool into main() only.
At the master level a tool is a product.
Trade-off: strict failure on any error keeps data correct and makes runs fail more often; tolerant runs finish more and must report partial failure clearly.
Try it: Master
Another team parses your tool's output in their pipeline. What protects them when you change it?
Now do it: Add a --json flag with a version field to one tool.
The cleanup tool, complete. It deletes files older than N days under an allowed root, with a dry run, logging, and honest exit codes.
#!/usr/bin/env python3
import argparse, json, logging, sys, time
from pathlib import Path
ALLOWED_ROOT = Path("/srv")
log = logging.getLogger("cleanup")
def positive(v):
n = int(v)
if n <= 0:
raise argparse.ArgumentTypeError("must be a positive number of days")
return n
def main(argv=None):
p = argparse.ArgumentParser(description="Delete files older than N days.")
p.add_argument("path", type=Path)
p.add_argument("--older-than", type=positive, default=30, metavar="DAYS")
p.add_argument("--dry-run", action="store_true")
p.add_argument("--json", action="store_true", help="print a JSON summary on stdout")
p.add_argument("-v", "--verbose", action="count", default=0)
a = p.parse_args(argv)
logging.basicConfig(level=logging.DEBUG if a.verbose else logging.INFO,
format="%(asctime)s %(levelname)s %(message)s") # stderr
root = a.path.resolve()
if not root.is_dir() or ALLOWED_ROOT not in root.parents:
p.error(f"{root} is not a directory under {ALLOWED_ROOT}")
cutoff = time.time() - a.older_than * 86400
removed = failed = 0
for f in root.rglob("*"):
try:
if not f.is_file() or f.stat().st_mtime >= cutoff:
continue
if a.dry_run:
log.debug("would delete %s", f)
else:
f.unlink()
removed += 1
except FileNotFoundError:
continue # gone already: fine
except PermissionError as e:
failed += 1
log.error("cannot delete %s: %s", f, e)
summary = {"removed": removed, "failed": failed, "dry_run": a.dry_run}
log.info("removed=%d failed=%d dry_run=%s", removed, failed, a.dry_run)
if a.json:
print(json.dumps(summary)) # data on stdout only
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
This is a composite of a failure pattern that keeps repeating; the details are illustrative. A cleanup job succeeded every night while doing nothing.
The job catches PermissionError specifically, logs each failure, prints counts, exits 1 on any failure, and its systemd unit alerts on failure. A lint rule rejects bare except in the automation repository.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Type each one, read what it prints, and compare it with the note above it.
argparse gives --help and usage errors (exit 2) for free.
python3 -c "import argparse; p = argparse.ArgumentParser(prog='cleanup'); p.add_argument('--older-than', type=int, required=True); p.parse_args(['--older-than', 'abc'])"; echo "exit $?"stdout is data, stderr is for people: pipe only the data.
python3 -c "import sys, json; print('working...', file=sys.stderr); print(json.dumps({'removed': 3}))" | python3 -m json.toolMixing logs into stdout breaks the next tool in the pipe.
python3 -c "import json; print('working...'); print(json.dumps({'removed': 3}))" | python3 -m json.tool 2>&1 | tail -1A bare except swallows even Ctrl+C; test it with a timeout signal.
timeout -s INT 1 python3 -c "import time
while True:
try:
time.sleep(0.2)
except:
pass"; echo "exit $? (124 means timeout had to stop it)"honest_tool.pyThis program runs the same delete loop with three styles of error handling and prints what each one reports: what was removed, what was logged, and the exit code. Save it as honest_tool.py, then run it.
# honest_tool.py
import logging, sys
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s", stream=sys.stdout)
log = logging.getLogger("cleanup")
files = {f"/srv/tmp/f{i}": ("ok" if i % 4 else "denied") for i in range(1, 9)}
def delete(path):
if files[path] == "denied":
raise PermissionError(f"Permission denied: {path!r}")
def run(style):
removed = failed = 0
for path in files:
if style == "bare except: pass":
try:
delete(path); removed += 1
except: # hides everything
pass
else:
try:
delete(path); removed += 1
except PermissionError as e:
failed += 1
log.error("%s", e)
code = 1 if failed else 0
return removed, failed, code
for style in ["bare except: pass", "except PermissionError: log and count"]:
print(f"== {style}")
removed, failed, code = run(style)
print(f"removed={removed} failed={failed} exit={code}")
Run it, and you should see this output:
$ python3 honest_tool.py == bare except: pass removed=6 failed=0 exit=0 == except PermissionError: log and count ERROR Permission denied: '/srv/tmp/f4' ERROR Permission denied: '/srv/tmp/f8' removed=6 failed=2 exit=1
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/python-errors-logging-and-command-line-tools && cd ~/labs/python-errors-logging-and-command-line-tools) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Python Errors, Logging, and Command-Line Tools", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'argparse gives --help and usage errors (exit 2) for free.'
'stdout is data, stderr is for people: pipe only the data.'
'Mixing logs into stdout breaks the next tool in the pipe.'
'A bare except swallows even Ctrl+C; test it with a timeout signal.'
)
step_1() {
python3 -c "import argparse; p = argparse.ArgumentParser(prog='cleanup'); p.add_argument('--older-than', type=int, required=True); p.parse_args(['--older-than', 'abc'])"; echo "exit $?"
}
step_2() {
python3 -c "import sys, json; print('working...', file=sys.stderr); print(json.dumps({'removed': 3}))" | python3 -m json.tool
}
step_3() {
python3 -c "import json; print('working...'); print(json.dumps({'removed': 3}))" | python3 -m json.tool 2>&1 | tail -1
}
step_4() {
timeout -s INT 1 python3 -c "import time
while True:
try:
time.sleep(0.2)
except:
pass"; echo "exit $? (124 means timeout had to stop it)"
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
tail, echo, Pipes, Redirection, Exit codes.Build a certificate-expiry checker that other teams will run in their pipelines and from cron.
What arguments does it take? Which errors are expected (DNS failure, timeout, bad certificate) and how is each reported? What goes to stdout and what to stderr? Which exit codes mean what?
Say 300 hostnames, a 5-second timeout each, warnings at 21 days and failure at 7 days.
argparse with a hosts file, --warn-days, --fail-days, --json, and -v; one function per host catching socket.timeout, socket.gaierror, and ssl.SSLError, each logged with the host; a JSON summary on stdout with a version field; logs on stderr; exit 0 all good, 1 something expires within fail-days or a host failed, 2 usage.
Treating an unreachable host as a failure is safe and noisy; treating it as a warning is quiet and can hide an expired certificate behind a DNS problem. Document the choice and let callers override it with a flag.