How to Build a Simple argparse CLI in Python
Create a beginner-friendly command-line tool with argparse that reads a file, optionally uppercases its lines, and prints a configurable number of lines.
Python code
27 linesimport argparse
def main():
parser = argparse.ArgumentParser(
description="Automate file processing with a simple CLI tool."
)
parser.add_argument("filename", help="Path to the input file")
parser.add_argument("--uppercase", action="store_true", help="Convert text to uppercase")
parser.add_argument("--lines", type=int, default=5, help="Number of lines to show (default: 5)")
args = parser.parse_args()
try:
with open(args.filename, "r") as file:
content = file.readlines()
except FileNotFoundError:
print(f"Error: File '{args.filename}' not found.")
return
if args.uppercase:
content = [line.upper() for line in content]
for line in content[:args.lines]:
print(line, end="")
if __name__ == "__main__":
main()
Output
> python cli.py sample.txt --uppercase --lines 2
FIRST LINE
SECOND LINE
How it works
argparse parses command-line arguments automatically and generates helpful usage messages. The add_argument calls define the positional filename and the two optional flags. --uppercase uses action="store_true" so it sets a boolean flag when present. parse_args() returns a Namespace object, giving you easy attribute access. The try/except block handles missing files gracefully, preventing a raw traceback.
Common mistakes
- Forgetting to call `parse_args()` — you must call it to actually parse the arguments.
- Confusing positional vs optional arguments; positional ones come first and are required.
- Aborting on missing files without a friendly error message.
- Using `input()` inside a CLI instead of relying on parsed arguments.
Variations
- Use `parser.add_argument("--file", help="Path")` with `--file` as an optional flag instead of a positional.
- Add `parser.set_defaults(func=handler)` and dispatch to separate functions for a scalable multi-command CLI.
Real-world use cases
- Automating log file inspection by piping line counts or filtering into a quick terminal command.
- Building a shared internal script where teammates pass different file paths and formatting flags.
- Wrapping a data processing routine so non-programmers can run it via a command-line interface.
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.