Skip to content

Lesson 3 of 9 · 22m

Scripts as Real Programs

argparse, logging, exit codes, configuration, dry-run mode, and small program structure that separates operators' tools from disposable snippets.

The difference between a script and a program is not length. It is whether the next operator can run it safely at 02:00 without reading every line. A real program validates inputs, explains what it is doing, fails loudly, supports a dry run, and exits with a meaningful status.

Structure for testability

import argparse
import logging

log = logging.getLogger('backupctl')

def parse_args(argv=None):
    parser = argparse.ArgumentParser(description='Rotate application backups')
    parser.add_argument('--backup-dir', type=Path, required=True)
    parser.add_argument('--keep', type=int, default=7)
    parser.add_argument('--dry-run', action='store_true')
    return parser.parse_args(argv)

def rotate_backups(backup_dir: Path, keep: int, dry_run: bool) -> int:
    return 0  # real work, independent of argv and sys.exit

def main(argv=None) -> int:
    args = parse_args(argv)
    logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
    return rotate_backups(args.backup_dir, args.keep, args.dry_run)

if __name__ == '__main__':
    raise SystemExit(main())

This layout matters. parse_args and the core operation can be unit tested. main owns process-facing behavior: logging setup and exit status. The import guard prevents execution when tests or other modules import the file.

Logging beats print

print is user-facing output. logging is operational telemetry. Use DEBUG for reproduction detail, INFO for major transitions, WARNING for degraded operation, and ERROR for failure:

log.info('pruning backups older than generation %d', keep)
log.warning('backup %s is missing checksum', path)
log.error('unable to prune %s: %s', path, exc)

Include identifiers and paths, not secrets. If a log line would be embarrassing in a ticket, it will eventually end up in one.

Exit codes and configuration are interfaces

Schedulers and wrappers do not read prose; they read exit status. Use 0 for success and a stable nonzero value for anticipated failure:

except RecoverableError as exc:
    log.error('%s', exc)
    return 2

Configuration should layer predictably: explicit CLI flag, environment variable, config file, then default. Flags are what the operator typed for this run and should win. For destructive operations, require --apply or --yes; ambiguity is not a safety control.

Field notes

  • Make --dry-run print intended actions from the same planning path as apply mode; separate fake logic drifts immediately.
  • Do not configure logging inside imported library modules; configure it in the application entry point.
  • Return machine-readable output (--json) when another program may consume the result.

Was this lesson helpful?

Sign in to rate