How to Parse CLI Arguments in Python with argparse

Build a beginner-friendly CLI with argparse that accepts optional --name, --greeting, and --uppercase flags, then prints a customizable greeting.

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

Python code

16 lines
Python 3.9+
import argparse

def main():
    parser = argparse.ArgumentParser(description="Greet a user with optional customization.")
    parser.add_argument("--name", default="world", help="Name to greet")
    parser.add_argument("--greeting", default="Hello", help="Greeting word")
    parser.add_argument("--uppercase", action="store_true", help="Print greeting in uppercase")
    args = parser.parse_args()

    message = f"{args.greeting}, {args.name}!"
    if args.uppercase:
        message = message.upper()
    print(message)

if __name__ == "__main__":
    main()

Output

stdout
Default run (python script.py):
Hello, world!

With custom args (python script.py --name Ada --greeting Hi):
Hi, Ada!

With --uppercase (python script.py --name Ada --greeting Hi --uppercase):
HI, ADA!

How it works

argparse.ArgumentParser creates a parser object that automatically handles --help flag generation for users. parser.add_argument defines each CLI option, where default supplies a fallback value when the user omits the flag, and store_true creates a boolean switch that sets True if the flag is present. After parser.parse_args(), all values are accessible as attributes on the args object, making it easy to build a dynamic message with an f-string. The if __name__ == "__main__" guard ensures main() only runs when the script is executed directly, not when imported elsewhere.

Common mistakes

  • Forgetting that `args` is a namespace object, so you access values with `args.name` not `args['name']`
  • Confusing `store_true` with passing a value — the flag `--uppercase` takes no argument
  • Not setting a `default`, causing a `None` value when the user omits an optional flag
  • Forgetting the `--help` flag is auto-generated but requires a docstring or `help=` text to be useful

Variations

  1. Use `parser.add_argument("name")` to require a positional argument instead of an optional flag
  2. Add type hints like `type=int` for numeric CLI inputs to auto-validate and convert values

Real-world use cases

  • Building a deployment script that accepts environment, branch, and dry-run flags before executing a release job.
  • Creating a data pipeline CLI that takes input paths, output directory, and a logging verbosity switch.
  • Writing a backup automation tool that lets users pass file patterns and a --dry-run toggle to preview actions.

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.