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.
Python code
16 linesimport 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
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
- Use `parser.add_argument("name")` to require a positional argument instead of an optional flag
- 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
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.