Command-line tool skeleton with argparse
A small CLI with a positional argument, flags, a main function and proper exit codes.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
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 0Example / expected 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
8How 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.
Related snippets
- Bash
Parse command-line flags with getopts
Handle -v, -o FILE and -h in a bash script with getopts and a usage message.
- Bash
Timestamped tar.gz backup that keeps the newest N
Archive a directory with a sortable timestamp and delete older backups beyond a retention count.
- Bash
Delete local Git branches that are already merged
Clean up merged local branches safely, excluding main, master, develop and the current branch.
- Bash
Safe header for Bash scripts
Fail fast on errors, unset variables and broken pipes, and clean up temp files with a trap.

