How do you implement a proper `--dry-run`?
IntermediateConceptOS, filesystem, subprocess & CLIs
Answer
Compute the full plan first, print it, and only execute when not in dry-run mode, so dry-run exercises the same code path up to the side effect.
plan = [s for s in snapshots if is_expired(s)]
for s in plan:
log.info("%s delete %s", "[dry-run] would" if dry_run else "will", s["SnapshotId"])
if not dry_run:
for s in plan:
ec2.delete_snapshot(SnapshotId=s["SnapshotId"])
Many AWS APIs also accept DryRun=True, which validates IAM permissions server-side and returns DryRunOperation on success; that is a stronger test than a local flag.
More on OS, filesystem, subprocess & CLIs
`os.path` vs `pathlib`: which do you use and why?BeginnerHow do you read environment variables safely?BeginnerHow do you walk a directory tree and find files?BeginnerWhat does `shutil` give you that `os` does not?BeginnerHow do you run an external command correctly with `subprocess`?BeginnerWhy is `shell=True` dangerous, and when is it acceptable?Intermediate