How to Build a Simple argparse CLI in Python
Build a beginner-friendly command-line tool with argparse that greets a user, with optional greeting text and uppercase output.
Python code
17 linesimport argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
if uppercase:
message = message.upper()
return message
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Simple CLI greeting tool")
parser.add_argument("name", help="Name of the person to greet")
parser.add_argument("-g", "--greeting", default="Hello", help="Greeting word")
parser.add_argument("-u", "--uppercase", action="store_true", help="Print in uppercase")
args = parser.parse_args()
result = greet(args.name, args.greeting, args.uppercase)
print(result)
Output
$ python cli.py Alice
Hello, Alice!
$ python cli.py Alice -g Hi
Hi, Alice!
$ python cli.py Alice -u
HELLO, ALICE!
$ python cli.py --help
usage: cli.py [-h] [-g GREETING] [-u] name
Simple CLI greeting tool
positional arguments:
name Name of the person to greet
options:
-h, --help show this help message and exit
-g GREETING, --greeting GREETING
Greeting word
-u, --uppercase Print in uppercase
How it works
The argparse module reads command-line arguments and validates them automatically. add_argument defines each expected input; store_true converts a flag into a boolean True when present. The if __name__ == "__main__" guard ensures parsing only runs when the script is executed directly, keeping it importable. parse_args() returns a Namespace, and the code accesses arguments as attributes. Printing inside __main__ keeps the function clean and testable.
Common mistakes
- Forgetting the `if __name__ == "__main__"` guard, which breaks imports.
- Using `action="store"` for boolean flags instead of `store_true`.
- Assuming `args.greeting` always exists without setting a default.
- Not including `help` text, making the CLI confusing for users.
Variations
- Use `choices=["hello", "hey"]` on the greeting argument to restrict inputs.
- Make `name` optional with `nargs="?"` and a default value.
- Add a `--version` action to print the script version.
Real-world use cases
- A devops script that greets users at login with configurable messages.
- A simple deployment tool that accepts environment and verbose flags.
- An internal reporting script that greets a team and formats output for logs.
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.