How to Build a Python argparse CLI for Beginners
Build a beginner-friendly command-line interface using Python's argparse module with positional and optional arguments.
Python code
20 linesimport argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
if uppercase:
message = message.upper()
return message
def main():
parser = argparse.ArgumentParser(description="A simple CLI greet tool for beginners.")
parser.add_argument("name", help="Name of the person to greet")
parser.add_argument("-g", "--greeting", default="Hello", help="Greeting word (default: Hello)")
parser.add_argument("-u", "--uppercase", action="store_true", help="Print greeting in uppercase")
args = parser.parse_args()
result = greet(args.name, args.greeting, args.uppercase)
print(result)
if __name__ == "__main__":
main()
Output
Hello, Alice!
$ python script.py Bob -g Hi
Hi, Bob!
$ python script.py Charlie -u
HELLO, CHARLIE!
$ python script.py --help
usage: script.py [-h] [-g GREETING] [-u] name
A simple CLI greet tool for beginners.
positional arguments:
name Name of the person to greet
options:
-h, --help show this help message and exit
-g GREETING, --greeting GREETING
Greeting word (default: Hello)
-u, --uppercase Print greeting in uppercase
How it works
The argparse.ArgumentParser creates a parser object that automatically handles command-line argument parsing, help text, and error messages. Positional arguments (like name) are required, while optional arguments (like -g and -u) start with dashes and have defaults or store boolean flags. The action="store_true" parameter makes -u a flag that sets uppercase to True when present. Using parser.parse_args() converts command-line input into a namespace object with attributes matching the argument names. The if __name__ == "__main__": guard ensures the main function only runs when the script is executed directly, not when imported as a module.
Common mistakes
- Forgetting to call `parser.parse_args()` before accessing argument values
- Using `action="store_true"` without the `-u` short flag or `--uppercase` long flag
- Not using `default` for optional arguments, making them required unintentionally
Variations
- Add type conversion with `type=int` for numeric arguments
- Use `nargs='+'` to accept multiple positional values as a list
Real-world use cases
- Create a deployment script that takes environment names and flags as command-line inputs.
- Build a data processing tool with configurable paths and verbosity levels.
- Write a backup utility letting users specify source, destination, and compression options.
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.