How to Implement argparse CLI Command in Python
Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments, flags, and prints a customizable greeting.
Python code
18 linesimport argparse
def main():
parser = argparse.ArgumentParser(description="A simple CLI tool to greet users.")
parser.add_argument("name", help="Your name")
parser.add_argument("-g", "--greeting", default="Hello", help="Greeting word (default: Hello)")
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
$ python greet.py Alice
Hello, Alice!
$ python greet.py Alice -g Hi
Hi, Alice!
$ python greet.py Alice --uppercase
HELLO, ALICE!
$ python greet.py --help
usage: greet.py [-h] [-g GREETING] [--uppercase] name
A simple CLI tool to greet users.
positional arguments:
name Your name
options:
-h, --help show this help message and exit
-g GREETING, --greeting GREETING
Greeting word (default: Hello)
--uppercase Print greeting in uppercase
How it works
The argparse module is part of Python's standard library, so no third-party packages are required. add_argument defines each command-line interface element: name is a required positional argument, while -g/--greeting has a default value and --uppercase acts as a boolean flag. When you run the script, parse_args() collects the values from sys.argv and returns a namespace object whose attributes map directly to the argument names. The code then builds the message with an f-string and applies .upper() when the flag is present. Using if __name__ == "__main__" ensures the CLI logic only runs when the script is executed directly, not when imported.
Common mistakes
- Forgetting that `store_true` flags don't take a value — passing one raises an error
- Using `parser.parse_args` without assigning the result to a variable before accessing attributes
- Putting optional arguments before the positional argument and expecting them to be parsed correctly
- Forgetting the `if __name__ == "__main__"` guard, which breaks imports
Variations
- Add `type=int` to an argument to parse numeric inputs automatically
- Use `nargs='+'` to accept multiple positional values, e.g., multiple names
Real-world use cases
- Building a deployment script that accepts environment and region as CLI arguments.
- Creating a data-processing utility where users pass input and output file paths at the command line.
- Writing a test-runner script that accepts a feature flag and a target module name.
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.