How to Add a Dry Run Flag to a Python CLI Command

Build a Python CLI command with a --dry-run flag that previews actions and exits before making real changes.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

22 lines
Python 3.9+
import argparse
import sys

def main():
    parser = argparse.ArgumentParser(description="Sample CLI command with dry-run flag")
    parser.add_argument("--name", required=True, help="Name to greet")
    parser.add_argument("--dry-run", action="store_true", dest="dry_run",
                        help="Show what would be done without executing")
    args = parser.parse_args()

    greeting = f"Hello, {args.name}!"

    if args.dry_run:
        print(f"[DRY RUN] Would output: {greeting}")
        print("[DRY RUN] Skipping actual execution")
        return

    print(greeting)
    print("Actual execution completed")

if __name__ == "__main__":
    main()

Output

stdout
Without flag:
$ python script.py --name Ada
Hello, Ada!
Actual execution completed

With dry run:
$ python script.py --name Ada --dry-run
[DRY RUN] Would output: Hello, Ada!
[DRY RUN] Skipping actual execution

How it works

The --dry-run flag uses store_true, which sets args.dry_run to True when present and False otherwise. The code then prints what would happen and calls return early to skip the real execution path. Using dest gives parser.add_argument('--dry-run') a Python-friendly attribute name without hyphens.

Common mistakes

  • Returning without printing the expected output in dry-run mode
  • Using a positional `--dry-run` value (like a string) instead of `action='store_true'`

Variations

  1. Add `--force` or `--yes` to override the dry-run guard when needed
  2. Extend with `argparse.BooleanOptionalAction` in Python 3.9+ for automatic `--no-dry-run`

Real-world use cases

  • Preview destructive database migrations or schema changes before running them in production.
  • Dry-run a deployment script to validate config and targets without touching live servers.
  • Stage batch file-reorganization scripts and confirm the file mapping before moving data.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.