How to Create a Simple Python CLI with argparse
Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments to greet users flexibly.
Python code
32 linesimport argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
return message.upper() if uppercase else message
def main():
parser = argparse.ArgumentParser(
description="A simple CLI tool that greets users."
)
parser.add_argument(
"name",
type=str,
help="Name of the person to greet"
)
parser.add_argument(
"-g", "--greeting",
default="Hello",
help="Custom greeting word (default: Hello)"
)
parser.add_argument(
"-u", "--uppercase",
action="store_true",
help="Convert output to uppercase"
)
args = parser.parse_args()
result = greet(args.name, args.greeting, args.uppercase)
print(result)
if __name__ == "__main__":
main()
Output
$ python greet.py Alice
Hello, Alice!
$ python greet.py Bob --greeting Hi
Hi, Bob!
$ python greet.py Charlie -u
HELLO, CHARLIE!
How it works
The argparse module provides a clean interface for defining and parsing command-line arguments. By using add_argument, you specify both positional arguments like name and optional flags with short (-g) and long (--greeting) forms. The store_true action automatically sets a boolean flag to True when present, which makes the uppercase option easy to check later. The parse_args() method returns a Namespace object, giving you attribute-style access to each argument via args.name and args.greeting. Finally, the __name__ == "__main__" guard ensures main() only runs when the script is executed directly, not when imported as a module.
Common mistakes
- Forgetting that `args.greeting` has a default value, so the function gets called with 'Hello' if no flag is passed
- Using `action='store_false'` when you want a true-flag pattern, which can flip the logic upside down
- Omitting the `__name__ == "__main__"` guard and having side effects on import
Variations
- Add `type=int` to positional arguments for numeric values, and `choices=` to restrict valid inputs
- Use `nargs='+'` to accept multiple positional values, like a list of names
Real-world use cases
- Creating a deployment script that takes environment and service names as CLI arguments.
- Building a data-report generator where users pass in a date range and output format flags.
- Writing a log-analysis tool that accepts file paths and an optional verbose verbose mode.
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.