Stop 11 · Automation & ScriptingTopics · 3/7

Command-Line Scripts with argparse

Part of the Python Roadmap

In short

A script with the file name hard-coded on line 3 only works for you. argparse turns it into a real tool: anyone can pass in files and options, and --help explains how to use it.

argparse turns a script into a proper command-line tool with named options, defaults, type checking and an automatic --help message, so others can use it without editing the code.

The jaadu runs a tiny roadside chai stall, adjusting three knobs on a shiny kettle while a customer points at a picture menu board of cups.

Think of it like this

The chai stall order

At a chai stall in Kolkata you don't rewrite the recipe each time. You just say "two cutting, less sugar, extra ginger". The chaiwala has fixed options, sensible defaults, and tells you if you ask for something he doesn't make. argparse gives your script that counter: named options, defaults and a menu card.

Watch it happen

python linecount.py notes.txt -m 5 -v

terminal
argparse
your main()

sys.argv

1/3The shell splits the command into words and hands them to Python.

The big ideas

What you need to know

Positional arguments

Required values in order, like the input file. nargs="+" accepts one or more.

Optional flags

Names starting with - or --, like --min-length. Give them a default and a help text.

store_true

action="store_true" makes an on/off switch: present means True, absent means False.

Free --help

argparse writes the usage message from your help strings. Good help text is your documentation.

See it in code

Walk through the code

python
1import argparse2from pathlib import Path3 4 5def main() -> None:6    parser = argparse.ArgumentParser(description="Count lines in text files.")7    parser.add_argument("files", nargs="+", type=Path, help="one or more files")8    parser.add_argument(9        "-m", "--min-length", type=int, default=0,10        help="only count lines at least this long (default: 0)",11    )12    parser.add_argument("-v", "--verbose", action="store_true", help="show per-file counts")13    args = parser.parse_args()14 15    total = 016    for path in args.files:17        lines = path.read_text(encoding="utf-8").splitlines()18        count = sum(1 for line in lines if len(line) >= args.min_length)19        total += count20        if args.verbose:21            print(f"{path}: {count}")22    print(f"Total: {total}")23 24 25if __name__ == "__main__":26    main()

1/4The parser and one positional argument. type=Path converts each file name to a Path object.

Try python linecount.py --help, then python linecount.py a.txt b.txt -m 5 -v.

Save yourself the pain

Common mistakes

Oops

Reading sys.argv[1] by hand and crashing with IndexError when it's missing.

Do this instead

Let argparse handle it. It prints a usage message and a clear error instead.

Oops

Using type=bool for a flag.

Do this instead

bool("False") is True. Use action="store_true" for on/off switches.

Oops

Leaving out help= text.

Do this instead

Write a short help for every argument. It's the first thing your users, and future you, will read.

Your mission

A rupee converter tool

~25 min

Quick check

With parser.add_argument("--dry-run", action="store_true"), what is args.dry_run when the flag is not given?

Go deeper

  1. 1Add --input and --output options to one of your scripts.
  2. 2Use type=int and choices=[...] to validate arguments.
  3. 3Run your script with --help and check the message is clear.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge