How to validate argparse CLI commands in Python
Build a beginner-friendly command-line argument parser with argparse, including required and optional arguments, plus simple validation for age.
Python code
25 linesimport argparse
def main():
parser = argparse.ArgumentParser(description="Validate CLI arguments for beginners.")
parser.add_argument("name", type=str, help="Your name.")
parser.add_argument("--age", type=int, default=None, help="Your age (optional).")
parser.add_argument("--verbose", action="store_true", help="Enable verbose output.")
args = parser.parse_args()
if args.verbose:
print(f"Verbose: Hello {args.name}!")
else:
print(f"Hello {args.name}!")
if args.age is not None and args.age < 0:
parser.error("Age must be non-negative.")
if args.age is not None:
print(f"Age: {args.age}")
if __name__ == "__main__":
main()
Output
> python script.py Alice
Hello Alice!
> python script.py Alice --age 25
Hello Alice!
Age: 25
> python script.py Alice --age -5
usage: script.py [-h] [--age AGE] [--verbose] name
script.py: error: Age must be non-negative.
> python script.py Alice --age 25 --verbose
Verbose: Hello Alice!
Age: 25
How it works
This script uses argparse.ArgumentParser to define CLI arguments: name is positional and required, --age is optional with an integer type, and --verbose is a boolean flag. The parse_args() call converts command-line input into a namespace with validated types. The parser.error() method exits with a usage message when validation fails, which is cleaner than raising a raw exception. Defaults like default=None for optional values let you check is not None to conditionally print only provided options.
Common mistakes
- Forgetting to import argparse before using ArgumentParser
- Using `parser.add_argument` for the positional `name` without `type=str` when you need validation
- Calling `parser.error()` after parsing but before using `args` — validation should happen before using the values
- Using `action="store_true"` for `--verbose` but checking `args.verbose is True` instead of just `if args.verbose:`
Variations
- Add `choices=["debug", "info", "error"]` to restrict string values
- Use `type=float` for a numeric argument that needs decimal precision
- Add `required=True` to make an optional argument mandatory
Real-world use cases
- A CLI tool that requires a file name and optionally accepts a log level for verbose output.
- A deployment script that takes a target environment and flags for dry-run or force modes.
- A data processing script that accepts a dataset path and an optional `--limit` for batch size.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.