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.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 15 views 0 copies

Python code

27 lines
Python 3.9+
import 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

stdout
> 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

  1. Use `parser.add_argument("--file", help="Path")` with `--file` as an optional flag instead of a positional.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.