Platform Engineering · Lesson 41

The Python Standard Library Toolbox

Python comes with a toolbox of about two hundred modules, and most automation needs nothing else: pathlib and shutil for files, zipfile and tarfile for archives, uuid, hashlib, and secrets for IDs and checksums, datetime with zoneinfo for time, textwrap and string.Template for text, traceback and logging for errors, concurrent.futures and signal for running work, and email with smtplib to send the result. This lesson builds a nightly operations report from those modules alone, and shows the two ways such jobs fail: installing packages on a server that cannot reach PyPI, and naive local times on the night the clocks change.

Difficulty: Intermediate · Know this first: Lesson 29, Lesson 40

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes for the nightly job. It is a worked example, not a measurement. The install and time hops are where it fails.

Try it: which module does that?

Pick a job and what you would reach for. See whether the standard library already has it.

uuidbuilt-in module
uuid.uuid4()the call

Built in: nothing to install

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Using the standard library well grows in four levels: knowing the drawers, using them correctly, combining them into jobs, and deciding when a package is worth it.

Basic — Know the drawers

At the basic level you know which module does what.

  • Files: pathlib, shutil, tempfile. Archives: zipfile, tarfile, gzip.
  • IDs: uuid, hashlib, secrets. Time: datetime, zoneinfo, time.
  • Text: textwrap, string, pprint, json, csv.

Where it breaks: installing a package for something a module already does.

Try it: Basic

You need to read a .gz log line by line. What do you use?

Now do it: Count ERROR lines in a .gz log with gzip.open.

Intermediate — Use them correctly

At the intermediate level you avoid the traps.

  • Aware datetimes in UTC; zoneinfo only for display; time.monotonic() for durations.
  • secrets, never random, for tokens; hmac.compare_digest to compare them.
  • tempfile.TemporaryDirectory() as a context manager; logging.exception in except blocks.

Try it: Intermediate

You compare an API token with ==. What is the risk, and the fix?

Now do it: Replace token comparisons in one service with hmac.compare_digest.

Advanced — Combine them into jobs

At the advanced level the modules become a reliable job.

  • concurrent.futures with a bounded pool and per-item error handling.
  • SIGTERM handling with signal; locks with fcntl.flock against overlapping runs.
  • Checksums with hashlib on everything you ship; email with attachments for the result.

Try it: Advanced

Two cron runs of the job overlap and corrupt the archive. What prevents it?

Now do it: Add an flock-based lock to one scheduled job.

Master — When a package is worth it

At the master level you add dependencies on purpose.

  • Standard library for the core; packages where they save real work (YAML, cloud SDKs, HTTP with connection pools).
  • An internal mirror for servers without internet; pinned, audited versions.
  • Vendoring or a zipapp (python3 -m zipapp) to ship a tool as one file.

Trade-off: packages make code shorter and add install, audit, and update work on every machine.

Try it: Master

Your tool must run on servers with no internet and no pip. How do you ship it?

Now do it: Package a small tool with python3 -m zipapp and run the .pyz.

Go deeper

The nightly report, condensed: standard library only, safe to run twice, correct on the night the clocks change.

import fcntl, hashlib, json, logging, shutil, signal, smtplib, sys, tarfile, tempfile, textwrap, uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime, timedelta
from email.message import EmailMessage
from pathlib import Path
from zoneinfo import ZoneInfo

log = logging.getLogger("nightly")
stop = False
signal.signal(signal.SIGTERM, lambda *_: globals().update(stop=True))   # finish the current step, then exit

lock = open("/run/lock/nightly-report.lock", "w")
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)                        # a second run fails here

end = datetime.now(UTC).replace(minute=0, second=0, microsecond=0)
start = end - timedelta(hours=24)                                       # always 24 hours, in UTC
run_id = uuid.uuid4()

def check(host):
    try:
        return host, "ok", ""                                           # the real check goes here
    except Exception as e:
        log.exception("check failed for %s", host)
        return host, "failed", str(e)

with tempfile.TemporaryDirectory() as tmp:
    archive = Path(tmp) / f"logs-{end:%Y-%m-%d}.tar.gz"
    with tarfile.open(archive, "w:gz") as tar:
        for f in sorted(Path("/var/log/app").glob("*.log")):
            tar.add(f, arcname=f.name)
    digest = hashlib.sha256(archive.read_bytes()).hexdigest()
    with ThreadPoolExecutor(max_workers=8) as pool:
        results = list(pool.map(check, Path("hosts.txt").read_text().split()))
    local = ZoneInfo("Europe/London")
    body = textwrap.fill(f"Run {run_id}: {start.astimezone(local):%d %b %H:%M} to "
                         f"{end.astimezone(local):%d %b %H:%M} London time. "
                         f"{sum(r[1] == 'ok' for r in results)} of {len(results)} hosts ok.", 60)
    msg = EmailMessage()
    msg["Subject"], msg["From"], msg["To"] = "Nightly report", "ops@example.com", "oncall@example.com"
    msg.set_content(body + f"\n\nSHA-256 {digest}")
    msg.add_attachment(json.dumps(results, indent=2).encode(), maintype="application", subtype="json", filename="results.json")
    with smtplib.SMTP("mail.internal", 587, timeout=30) as smtp:
        smtp.starttls()
        smtp.send_message(msg)

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. A report job could not be installed where it ran.

Timeline

  • Month 0A nightly report job is written on a laptop with six helpful packages: a table printer, a retry helper, a mail wrapper, a time-zone library, a YAML reader, and a progress bar. It runs on a server with internet access.
  • Month 5The job moves to a new server in a restricted network. Its first run at 02:00 runs pip install, which cannot reach PyPI. No report is sent; nobody notices until the morning stand-up.
  • Month 5, +4 hFour of the six packages are replaced with textwrap, email, zoneinfo, and a ten-line retry loop; the YAML reader and SDK are mirrored internally and pinned.

What changed after

Jobs that run on servers are built and tested on an image with no internet access, and every third-party import needs a reason in the review.

Python, example by example

The modules automation uses most, one program each: IDs and hashes, archives, temporary folders, time zones, text, errors, threads and processes, signals, and email. Each example is a whole program: save it under the name in its first line, run it with python3, and you should see exactly the output below it.

Find it yourself

In everyday terms

The standard library is a toolbox with labelled drawers. Before buying a tool, check the drawer for the job: files, archives, IDs, time, text, running work, and mail.

Each drawer below is a group of built-in modules; the program checks that every one really comes with Python. Four questions find almost anything: is it built in (sys.stdlib_module_names), what is inside (dir()), how do I call it (inspect.signature()), and what does it do (the first line of __doc__, or help() for the whole page). The lesson Finding the Right Command, Library and Method covers this in full.

# find_it.py
import sys
DRAWERS = {
    "files": ["pathlib", "shutil", "tempfile", "glob"],
    "archives": ["zipfile", "tarfile", "gzip", "bz2", "lzma"],
    "ids and hashes": ["uuid", "hashlib", "secrets", "hmac"],
    "time": ["datetime", "zoneinfo", "time", "calendar"],
    "text": ["textwrap", "string", "pprint", "difflib"],
    "running work": ["concurrent", "multiprocessing", "threading", "signal"],
    "mail and web": ["email", "smtplib", "urllib", "http"],
}
for drawer, modules in DRAWERS.items():
    built_in = all(m in sys.stdlib_module_names for m in modules)
    print(f"{drawer:<15} built in: {built_in}   {', '.join(modules)}")
$ python3 find_it.py
files           built in: True   pathlib, shutil, tempfile, glob
archives        built in: True   zipfile, tarfile, gzip, bz2, lzma
ids and hashes  built in: True   uuid, hashlib, secrets, hmac
time            built in: True   datetime, zoneinfo, time, calendar
text            built in: True   textwrap, string, pprint, difflib
running work    built in: True   concurrent, multiprocessing, threading, signal
mail and web    built in: True   email, smtplib, urllib, http

1. IDs and secrets

uuid4 is random; uuid5 is the same for the same name; secrets makes tokens; hmac.compare_digest compares them safely.

# example_01.py
import hmac, secrets, uuid
run = uuid.uuid4()
print("uuid4 version", run.version, "length", len(str(run)))
print("uuid5:", uuid.uuid5(uuid.NAMESPACE_DNS, "web-01.example.com"))
token = secrets.token_urlsafe(24)
print("token length", len(token))
print(hmac.compare_digest(token, token), hmac.compare_digest(token, token + "x"))
$ python3 example_01.py
uuid4 version 4 length 36
uuid5: 13481c8f-cfb7-5f18-8bf9-ccfd0de2f82e
token length 32
True False

2. Checksums

hashlib hashes bytes; hashlib.file_digest hashes a file in chunks without reading it all into memory.

# example_02.py
import hashlib, io
data = b"backup contents\n" * 1000
print(hashlib.sha256(data).hexdigest()[:16])
print(hashlib.file_digest(io.BytesIO(data), "sha256").hexdigest()[:16])
print(sorted(hashlib.algorithms_guaranteed)[:5])
$ python3 example_02.py
0d637ad54ae7fa77
0d637ad54ae7fa77
['blake2b', 'blake2s', 'md5', 'sha1', 'sha224']

3. Archives without touching the disk

zip, tar, and gzip in memory; the same calls work with file paths.

# example_03.py
import gzip, io, tarfile, zipfile
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
    z.writestr("app.log", "INFO start\nERROR timeout\n")
    z.writestr("db.log", "INFO start\n")
print("zip:", zipfile.ZipFile(buf).namelist())
tbuf = io.BytesIO()
with tarfile.open(fileobj=tbuf, mode="w:gz") as t:
    payload = b"port=8080\n"
    info = tarfile.TarInfo("conf/app.conf"); info.size = len(payload)
    t.addfile(info, io.BytesIO(payload))
tbuf.seek(0)
print("tar:", tarfile.open(fileobj=tbuf, mode="r:gz").getnames())
packed = gzip.compress(b"line one\nline two\n")
print("gzip lines:", gzip.decompress(packed).decode().splitlines())
$ python3 example_03.py
zip: ['app.log', 'db.log']
tar: ['conf/app.conf']
gzip lines: ['line one', 'line two']

4. A scratch folder that cleans itself up

tempfile.TemporaryDirectory is removed when the with block ends, even after an error.

# example_04.py
import shutil, tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
    src = Path(tmp, "release")
    (src / "bin").mkdir(parents=True)
    (src / "bin" / "start.sh").write_text("echo start\n")
    (src / "VERSION").write_text("1.4.2\n")
    shutil.copytree(src, Path(tmp, "backup"))
    print(sorted(str(p.relative_to(tmp)) for p in Path(tmp, "backup").rglob("*")))
    kept = Path(tmp)
print("still there after the block?", kept.exists())
$ python3 example_04.py
['backup/VERSION', 'backup/bin', 'backup/bin/start.sh']
still there after the block? False

5. Time zones done right

Make times aware, compute in UTC, and convert only to show them.

# example_05.py
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo
meeting = datetime(2026, 11, 3, 9, 0, tzinfo=ZoneInfo("Asia/Kolkata"))
print("UTC:     ", meeting.astimezone(UTC).strftime("%Y-%m-%d %H:%M %Z"))
print("New York:", meeting.astimezone(ZoneInfo("America/New_York")).strftime("%Y-%m-%d %H:%M %Z"))
deadline = meeting.astimezone(UTC) + timedelta(hours=36)
print("deadline in Kolkata:", deadline.astimezone(ZoneInfo("Asia/Kolkata")).strftime("%a %H:%M"))
$ python3 example_05.py
UTC:      2026-11-03 03:30 UTC
New York: 2026-11-02 22:30 EST
deadline in Kolkata: Wed 21:00

6. Text for people

textwrap wraps and shortens, string.Template fills placeholders (safe_substitute leaves a missing one in place instead of failing), and pprint lays out nested data.

# example_06.py
import pprint, string, textwrap
note = "Disk usage on db-1 reached 91 percent at 02:14 UTC; the log volume grows by 4 GB a day."
print(textwrap.fill(note, 40, initial_indent="> ", subsequent_indent="> "))
print(textwrap.shorten(note, 40))
print(string.Template("$host is $state ($pct%)").safe_substitute(host="db-1", state="warning"))
pprint.pp({"db-1": {"disk": 91, "mounts": ["/", "/var/lib/postgresql"]}, "web-1": {"disk": 40}}, width=50)
$ python3 example_06.py
> Disk usage on db-1 reached 91 percent
> at 02:14 UTC; the log volume grows by
> 4 GB a day.
Disk usage on db-1 reached 91 [...]
db-1 is warning ($pct%)
{'db-1': {'disk': 91,
          'mounts': ['/', '/var/lib/postgresql']},
 'web-1': {'disk': 40}}

7. Errors that keep the report going

Log the full trace, put one line in the report, and carry on.

# example_07.py
import io, logging, traceback
stream = io.StringIO()
logging.basicConfig(stream=stream, level=logging.INFO, format="%(levelname)s %(message)s")
for host, value in [("web-1", "40"), ("db-3", "n/a"), ("web-2", "55")]:
    try:
        print(host, int(value))
    except ValueError as e:
        logging.exception("parse failed for %s", host)
        print(host, "FAILED:", traceback.format_exception_only(e)[-1].strip())
log = stream.getvalue().splitlines()
print("log:", log[0], "...", log[-1])
$ python3 example_07.py
web-1 40
db-3 FAILED: ValueError: invalid literal for int() with base 10: 'n/a'
web-2 55
log: ERROR parse failed for db-3 ... ValueError: invalid literal for int() with base 10: 'n/a'

8. Threads for waiting

Network checks spend their time waiting, so threads run them side by side; map returns the results in input order.

# example_08.py
import time
from concurrent.futures import ThreadPoolExecutor
def check(host):
    time.sleep(0.3)                     # stands in for a network call
    return f"{host} ok"
start = time.monotonic()
with ThreadPoolExecutor(max_workers=4) as pool:
    results = list(pool.map(check, ["web-1", "web-2", "db-1", "cache-1"]))
print(results)
print("four 0.3 s checks finished in under 0.6 s:", time.monotonic() - start < 0.6)
$ python3 example_08.py
['web-1 ok', 'web-2 ok', 'db-1 ok', 'cache-1 ok']
four 0.3 s checks finished in under 0.6 s: True

9. Processes for computing

CPU-heavy work runs in separate processes, one per core. The __main__ guard is required.

# example_09.py
from concurrent.futures import ProcessPoolExecutor
def count_primes(limit):
    return sum(all(n % d for d in range(2, int(n ** 0.5) + 1)) for n in range(2, limit))
if __name__ == "__main__":
    with ProcessPoolExecutor(max_workers=2) as pool:
        print(list(pool.map(count_primes, [1000, 10000, 20000])))
$ python3 example_09.py
[168, 1229, 2262]

10. Stopping cleanly on SIGTERM

systemd and Kubernetes send SIGTERM first. A handler sets a flag; the loop finishes its current step and exits.

# example_10.py
import os, signal
stop = False
def on_term(signum, frame):
    global stop
    stop = True
signal.signal(signal.SIGTERM, on_term)
for step in range(1, 6):
    print("step", step)
    if step == 2:
        os.kill(os.getpid(), signal.SIGTERM)   # what systemd would send
    if stop:
        print("SIGTERM received: finished step", step, "and stopping")
        break
$ python3 example_10.py
step 1
step 2
SIGTERM received: finished step 2 and stopping

11. Build an email

email.message.EmailMessage builds subject, body, and attachments; send it with smtplib.SMTP and starttls().

# example_11.py
import json
from email.message import EmailMessage
msg = EmailMessage()
msg["Subject"], msg["From"], msg["To"] = "Nightly report", "ops@example.com", "oncall@example.com"
msg.set_content("3 hosts ok, 1 failed. Details attached.")
msg.add_attachment(json.dumps({"db-3": "failed"}).encode(), maintype="application", subtype="json", filename="results.json")
print(msg["Subject"], "|", msg["To"])
print([part.get_content_type() for part in msg.iter_parts()])
print(msg.get_body(preferencelist=("plain",)).get_content().strip())
$ python3 example_11.py
Nightly report | oncall@example.com
['text/plain', 'application/json']
3 hosts ok, 1 failed. Details attached.

12. Where am I running?

platform and os describe the machine, so one script can adapt to it.

# example_12.py
import os, platform
print("system:", platform.system())
print("python major version:", platform.python_version_tuple()[0])
print("at least one CPU:", (os.cpu_count() or 0) >= 1)
print("path separator:", repr(os.sep))
$ python3 example_12.py
system: Linux
python major version: 3
at least one CPU: True
path separator: '/'

Practice: write the program yourself

Write each one from scratch before you open the solution. The output under each solution is what it really prints.

  1. Put three small text files into a zip in memory and print the names and sizes inside it.

    Show a solution
    # task_1.py
    import io, zipfile
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w") as z:
        for name, text in [("a.txt", "one\n"), ("b.txt", "two two\n"), ("c.txt", "three\n")]:
            z.writestr(name, text)
    print([(i.filename, i.file_size) for i in zipfile.ZipFile(buf).infolist()])
    $ python3 task_1.py
    [('a.txt', 4), ('b.txt', 8), ('c.txt', 6)]
  2. Print 09:00 on 2026-07-01 in Asia/Kolkata as UTC and as America/New_York time.

    Show a solution
    # task_2.py
    from datetime import UTC, datetime
    from zoneinfo import ZoneInfo
    t = datetime(2026, 7, 1, 9, 0, tzinfo=ZoneInfo("Asia/Kolkata"))
    print(t.astimezone(UTC).strftime("%H:%M %Z"), t.astimezone(ZoneInfo("America/New_York")).strftime("%H:%M %Z"))
    $ python3 task_2.py
    03:30 UTC 23:30 EDT
  3. Make a 16-byte URL-safe token and print its length, then the uuid5 of db-1 in the DNS namespace.

    Show a solution
    # task_3.py
    import secrets, uuid
    print(len(secrets.token_urlsafe(16)))
    print(uuid.uuid5(uuid.NAMESPACE_DNS, "db-1"))
    $ python3 task_3.py
    22
    0dc3a83f-4e35-59f2-9add-b49a5058ba9f
  4. Wrap a long sentence at 30 characters with "> " in front of every line.

    Show a solution
    # task_4.py
    import textwrap
    text = "The certificate on api.example.com expires in 9 days; renew it before the freeze."
    print(textwrap.fill(text, 30, initial_indent="> ", subsequent_indent="> "))
    $ python3 task_4.py
    > The certificate on
    > api.example.com expires in 9
    > days; renew it before the
    > freeze.

Try it yourself, from scratch

You need Python 3 on Linux, macOS, or WSL on Windows (run wsl --install in PowerShell once); check with python3 --version. The terminal is only for setting Python up and running it and its tools: the Python itself goes in .py files, in part 2 and in "Python, example by example" above.

1. Terminal: set up and run

Type each one, read what it prints, and compare it with the note above it.

  1. Make a folder for this lesson with its own virtual environment. Every command after this runs inside it; deactivate leaves it, and source .venv/bin/activate brings it back.

    mkdir -p ~/labs/python-standard-library-toolbox && cd ~/labs/python-standard-library-toolbox
    python3 -m venv .venv || echo "No venv module: on Debian or Ubuntu run  sudo apt install -y python3-venv  and try again"
    source .venv/bin/activate && python --version
  2. Count the modules that come with Python.

    python3 -c "import sys; print(len(sys.stdlib_module_names), 'modules')"
  3. Many modules are command-line tools too: make and list a zip with no zip program installed.

    printf "a\nb\n" > notes.txt
    python3 -m zipfile -c notes.zip notes.txt && python3 -m zipfile -l notes.zip
  4. A calendar, a UUID, and sorted, indented JSON, straight from the standard library.

    python3 -m calendar 2026 11
    python3 -m uuid
    echo '{"b": 1, "a": [1, 2]}' | python3 -m json.tool --sort-keys
  5. Time a snippet properly: timeit runs it many times and reports the best.

    python3 -m timeit -s "import hashlib" "hashlib.sha256(b'x' * 1024).hexdigest()"
  6. Serve this folder over HTTP for a quick file transfer, fetch the listing, and let it stop by itself.

    timeout 3 python3 -m http.server 8901 --bind 127.0.0.1 >/dev/null 2>&1 & sleep 1
    curl -s http://127.0.0.1:8901/ | grep -c notes
    wait

2. Python: nightly_report.py

This program builds a small nightly report from the standard library alone: counts from log lines, a zip archive in memory, a checksum, a repeatable run ID, wrapped text, and the length of "last night" on the night the clocks go back, computed naively and correctly. Save it as nightly_report.py in the lesson folder, then run it.

# nightly_report.py
import hashlib, io, textwrap, uuid, zipfile
from collections import Counter
from datetime import UTC, datetime
from zoneinfo import ZoneInfo

logs = {
    "web-1.log": "INFO start\nERROR db timeout\nINFO ok\nERROR db timeout\n",
    "web-2.log": "INFO start\nWARN slow request\nINFO ok\n",
    "db-1.log": "INFO start\nERROR disk 91% full\n",
}
levels = Counter(line.split()[0] for text in logs.values() for line in text.splitlines())
print("levels:", dict(sorted(levels.items())))

buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
    for name, text in sorted(logs.items()):
        z.writestr(zipfile.ZipInfo(name, date_time=(2026, 10, 25, 2, 0, 0)), text)
with zipfile.ZipFile(buf) as z:
    print("archive:", [(i.filename, i.file_size) for i in z.infolist()])
content = "".join(text for _, text in sorted(logs.items())).encode()
print("sha256 of the logs:", hashlib.sha256(content).hexdigest()[:16])
print("run id:", uuid.uuid5(uuid.NAMESPACE_URL, "nightly-report/2026-10-25"))

london = ZoneInfo("Europe/London")
start = datetime(2026, 10, 25, tzinfo=london)          # the night the clocks go back
end = datetime(2026, 10, 26, tzinfo=london)
print("naive local subtraction:", (end - start).total_seconds() / 3600, "hours")
print("real time, through UTC: ", (end.astimezone(UTC) - start.astimezone(UTC)).total_seconds() / 3600, "hours")

summary = (f"{sum(levels.values())} log lines from {len(logs)} hosts (errors: {levels['ERROR']}, "
           f"warnings: {levels['WARN']}). The window was 25 hours long because the clocks went back.")
print(textwrap.fill(summary, 56))

Run it, and you should see this output:

$ python3 nightly_report.py
levels: {'ERROR': 3, 'INFO': 5, 'WARN': 1}
archive: [('db-1.log', 31), ('web-1.log', 53), ('web-2.log', 37)]
sha256 of the logs: 4d923dc6f1bbfdfd
run id: e20acf0e-d7d8-5e36-a0d6-50bdc1e90858
naive local subtraction: 24.0 hours
real time, through UTC:  25.0 hours
9 log lines from 3 hosts (errors: 3, warnings: 1). The
window was 25 hours long because the clocks went back.

3. What to notice

4. Advanced: a test that keeps the program honest

A program you keep needs a test, so you know at once when a change alters what it does. This one uses unittest, which comes with Python: it runs nightly_report.py and checks that it exits cleanly and prints exactly the output above. Save it as test_nightly_report.py next to the program.

# test_nightly_report.py: checks that nightly_report.py still prints exactly what this lesson shows.
# Run it with:  python3 -m unittest -v test_nightly_report
import subprocess
import sys
import unittest
from pathlib import Path

HERE = Path(__file__).resolve().parent
EXPECTED = r"""
levels: {'ERROR': 3, 'INFO': 5, 'WARN': 1}
archive: [('db-1.log', 31), ('web-1.log', 53), ('web-2.log', 37)]
sha256 of the logs: 4d923dc6f1bbfdfd
run id: e20acf0e-d7d8-5e36-a0d6-50bdc1e90858
naive local subtraction: 24.0 hours
real time, through UTC:  25.0 hours
9 log lines from 3 hosts (errors: 3, warnings: 1). The
window was 25 hours long because the clocks went back.
""".strip("\n")


class TestNightlyReport(unittest.TestCase):
    def run_program(self):
        return subprocess.run([sys.executable, str(HERE / "nightly_report.py")], cwd=HERE,
                              capture_output=True, text=True, timeout=60)

    def test_exits_cleanly(self):
        result = self.run_program()
        self.assertEqual(result.returncode, 0, result.stderr)

    def test_prints_the_expected_output(self):
        result = self.run_program()
        self.assertEqual(result.stdout.rstrip(), EXPECTED)


if __name__ == "__main__":
    unittest.main()

Run it: you should see both tests end in ok, then OK. Then change one value in the program, run it again, and read how the failure shows you the difference. pytest runs the same file unchanged, if you prefer it.

python3 -m unittest -v test_nightly_report

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Write a weekly job that collects the last 7 days of audit logs from /var/log/audit, archives them with a checksum, and emails a summary of failed logins per user, using only the standard library.

Clarifying questions to ask

Which module finds the files, which reads the compressed ones, and which counts? How is the 7-day window computed so it is right across a clock change? What stops two runs overlapping? How is the archive verified by the receiver?

Rough sizing

Say 7 daily logs of 200 MB each, compressed, and a 20-minute budget for the job.

Shape of the answer

pathlib.glob for the files; gzip.open to read .gz logs line by line; re and collections.Counter to count failed logins per user; a window of now minus 7 days in UTC; tarfile with gz and hashlib.sha256 on the archive; fcntl.flock for the lock; email.message with the summary in the body and the checksum; smtplib with STARTTLS and a timeout.

Trade-offs to name

Reading compressed logs line by line uses little memory and more CPU; unpacking first is faster and needs disk space. Emailing the archive is simple and limited by attachment size; uploading it and emailing a link scales better.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Six packages, installed on the nightHop 8: No installsBreaksThe job imports six packages (a table printer, a retry helper, a mail wrapper, a time-zone library, a YAML reader, a progress bar). The new server is in a network with no route to PyPI; pip fails at 02:00 and no report is sent.
Naive local timesHop 4: Time zonesBreaksThe window is built from naive local times: midnight to midnight, local. On the night the clocks go back it is 25 hours long, and 01:00 to 02:00 is read twice, so an hour of errors is counted twice.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Files → Archives → IDs and hashes → Time zones → Text → Errors → Parallel work → No installs → Send it. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 42
Python for APIs: HTTP, Cloud SDKs, Retries, and Concurrency

Modern automation talks to APIs: cloud providers, Git hosts, monitoring, ticketing. Doing it well is a small checklist: authenticate from the environment, set timeouts, check the status code, follow pagination to the last page…

Go to Lesson 42 →

Or browse the full course from the Lessons index.