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.
Python code
22 linesimport 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
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
- Add `--force` or `--yes` to override the dry-run guard when needed
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.