← Knowledge Base
PythonReference note1 min read · updated 2026-11-27

Python: a small command-line tool with argparse

Arguments, options and flags, help text and a main() entry point.

pythonargparsecli
#!/usr/bin/env python3
import argparse

def main():
    ap = argparse.ArgumentParser(description="Count lines that contain a word")
    ap.add_argument("file")
    ap.add_argument("-w", "--word", required=True)
    ap.add_argument("-i", "--ignore-case", action="store_true")
    args = ap.parse_args()
    needle = args.word.lower() if args.ignore_case else args.word
    n = 0
    with open(args.file, encoding="utf-8") as f:
        for line in f:
            if needle in (line.lower() if args.ignore_case else line):
                n += 1
    print(n)

if __name__ == "__main__":
    main()

-h produces help automatically. Return a non-zero exit code on failure (raise SystemExit(2)) so scripts and cron can react.