Skip to content

Lesson 6 of 9 · 21m

Long-Running Commands: Progress, Cancellation, and Safe Writes

Commands that run for minutes need honest progress, clean Ctrl+C behavior, resumable boundaries, and output files that never appear half-written.

The difference between a script and a professional tool appears at minute four. A script sits silently while the operator wonders whether it hung. A tool says what it is doing, stops cleanly when interrupted, and never leaves a corrupt artifact that looks valid. These are design requirements, not polish.

Progress should answer three questions

What is happening? How much is done? Can I leave?

Scanning logs: 1,842/5,000 files (37%), current=/var/log/auth.log.3

Write progress to stderr so stdout remains machine-consumable. Update at a coarse interval — once or twice per second is enough. A spinner proves the process is alive but says nothing about completion; use one only when total work is unknowable.

Ctrl+C is part of the interface

try:
    run_scan(queue)
except KeyboardInterrupt:
    print("interrupted; partial results not written", file=sys.stderr)
    return 130

Exit status 130 conventionally means terminated by SIGINT. More importantly, cancellation should close network connections, remove temporary locks when safe, and avoid printing a traceback. If cleanup itself can take time, say so; otherwise users hit Ctrl+C twice and corrupt the thing you were trying to protect.

Design resumability around checkpoints

If a command processes thousands of items, store a small checkpoint file or make operations idempotent. Idempotency is better: running sync twice should converge to the same final state rather than duplicate records. When that is impossible, record completed units in a state directory such as ~/.local/state/toolname/.

Never expose half-written output files

Write to a temporary sibling and atomically rename:

from pathlib import Path
import os
import tempfile


def write_atomically(path: Path, content: str):
    fd, tmp = tempfile.mkstemp(prefix=path.name, dir=path.parent)
    with os.fdopen(fd, "w", encoding="utf-8") as handle:
        handle.write(content)
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(tmp, path)

os.replace is atomic on the same filesystem. This matters for reports, state files, lock-free caches, and generated configuration. A crash after partial write should leave the old file or nothing — never invalid JSON that downstream automation ingests.

Timeouts are kindness to automation

Network operations need explicit connect/read timeouts. The default in many libraries is effectively “wait forever,” which turns a minor outage into a stuck cron job and then a pile of overlapping processes. Surface timeout values as config and flags where operators need control.

Field notes

  • Progress bars that redraw in log files produce escape-code garbage; disable live rendering when stderr is not a TTY.
  • Do not treat KeyboardInterrupt as a generic Exception; in Python it inherits from BaseException for a reason.
  • Atomic rename does not fsync the directory entry. For truly critical files, fsync the containing directory too.
  • If parallelism is optional, say what ordering guarantees remain. Out-of-order progress output can confuse otherwise correct logic.

Was this lesson helpful?

Sign in to rate