Skip to content
GreenSnippets

Command-line tool skeleton with argparse

A small CLI with a positional argument, flags, a main function and proper exit codes.

Python
import argparse
import sys


def build_parser():
    parser = argparse.ArgumentParser(description="Count lines in files.")
    parser.add_argument("paths", nargs="+", help="files to read")
    parser.add_argument("-v", "--verbose", action="store_true", help="print each file")
    return parser


def main(argv=None):
    args = build_parser().parse_args(argv)
    total = 0
    for path in args.paths:
        try:
            with open(path, encoding="utf-8") as handle:
                count = sum(1 for _ in handle)
        except OSError as exc:
            print(f"error: {exc}", file=sys.stderr)
            return 1
        if args.verbose:
            print(f"{path}: {count}")
        total += count
    print(total)
    return 0

Example / expected output

Output
# At the bottom of count.py:  if __name__ == "__main__": raise SystemExit(main())
$ python count.py -v a.txt b.txt
a.txt: 3
b.txt: 5
8

How it works

Keep parsing in a function that accepts argv, so the program can be tested without touching sys.argv. Return an exit code from main and finish the script with if __name__ == "__main__": raise SystemExit(main()); 0 means success.