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.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

25 lines
Python 3.9+
import 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

stdout
> 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

  1. Add `choices=["debug", "info", "error"]` to restrict string values
  2. Use `type=float` for a numeric argument that needs decimal precision
  3. 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

Run this sample

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

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.