How to Build a CLI with argparse in Python

Create a beginner-friendly command-line tool in Python that processes multiple filenames with optional flags for verbose output and uppercase conversion.

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

Python code

20 lines
Python 3.9+
import argparse

def main():
    parser = argparse.ArgumentParser(
        description="A simple CLI to process files with optional verbose mode."
    )
    parser.add_argument("filenames", nargs="+", help="Files to process")
    parser.add_argument("-v", "--verbose", action="store_true", help="Print extra details")
    parser.add_argument("-u", "--upper", action="store_true", help="Convert file names to uppercase")
    args = parser.parse_args()

    for filename in args.filenames:
        name = filename.upper() if args.upper else filename
        if args.verbose:
            print(f"Processing: {name}")
        else:
            print(f"Done with {name}")

if __name__ == "__main__":
    main()

Output

stdout
$ python cli.py file1.txt file2.csv -v -u
Processing: FILE1.TXT
Processing: FILE2.CSV

$ python cli.py doc.txt
Done with doc.txt

How it works

The argparse module is part of the Python standard library, so no extra dependencies are needed. nargs="+" gathers one or more positional arguments into a list, letting you process many files in one run. The store_true action creates boolean flags that default to False and become True when present. The namespace object from parse_args holds all arguments, and reading them with args.filename keeps the code clean and readable.

Common mistakes

  • Forgetting to include `if __name__ == "__main__":` so the script runs on import.
  • Using `nargs="*"` instead of `"+"` when at least one filename is required.
  • Not handling the case where no filenames are passed, leading to a confusing error.
  • Accessing argument attributes incorrectly, like `args.filenames` vs the defined name.

Variations

  1. Add `default` values to flags, e.g., `-o --output` with a default file name.
  2. Use `choices` to restrict possible values for an argument, like `parser.add_argument("--mode", choices=["fast", "safe"])`.

Real-world use cases

  • A log aggregator script that takes multiple log file paths and outputs a processed summary.
  • A file conversion utility that converts several input files and optionally prints verbose progress.
  • A deployment script that takes a list of target servers and supports flags for dry-run or debug output.

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.