Command-line tools with argparse
Turn a script into a CLI with arguments, options and help text.
By Invicly Tech, , in Python Programming from Zero. About 10 minutes to read.
In short
argparse turns a script into a proper command-line tool. You declare the arguments and options it accepts, and argparse parses them, converts types, applies defaults and writes the --help text for you.
Explained simply
A command-line tool is a program you run by typing its name and some words after it, like git commit -m "fix". Those extra words are called arguments. They tell the program what to do without changing its code.
Python gives your script all those words as a list of strings in sys.argv. Turning that list into checked, typed values by hand is boring and full of edge cases. The argparse module does it for you, and it writes the help text too.
You describe what your tool accepts: required values, optional settings with a default, and simple on or off switches. argparse checks what the user typed, converts numbers, shows a clear error if something is wrong, and gives you an object with each value as an attribute.
Finally, you can install your script as a real command. After that, users type tracker add 12 instead of python path/to/tracker.py add 12, from any folder.
Press Play on a diagram to walk through it one step at a time.
- 1User types command
tracker add 12.5 --category food
- 2sys.argv
Raw list of strings from the shell
- 3parse_args()
Validates, converts types, fills defaults
- 4Namespace
args.amount, args.category ready to use
- 5Run & exit
Bad input prints usage and exits with error
- tracker add 12.5
- Required by default
- Identified by order
- Use for the main input
- --category food
- Takes a value
- Optional, with a default
- Use for settings
- --verbose
- No value: on or off
- action="store_true"
- Use for switches
In depth
How parse_args reads the command line
The shell splits what you type into words (respecting quotes) and passes them to Python. sys.argv[0] is the script name; parse_args() reads sys.argv[1:] by default. Words that start with - or -- are options; everything else fills positional arguments in order. A bare -- means "no more options", so tracker add -- -5 treats -5 as a value.
argparse also accepts --opt=value and unique prefixes of long options, like --cat for --category (turn this off with allow_abbrev=False). When input is wrong, it prints the usage line and a message to stderr and exits with status 2. -h and --help print the help and exit with 0. For tests, write def main(argv=None) and call parser.parse_args(argv): passing a list lets you test parsing without a real shell.
- 1Shell splits words
Quotes keep "two words" together
- 2sys.argv[1:]
["add", "12.5", "--category", "food"]
- 3Match options
--category consumes the next word
- 4Fill positionals
In the order they were added
- 5Convert and check
type=, choices=, required=
- 6Namespace or exit 2
Usage error goes to stderr
Options, flags and defaults
Beyond type and default, a few settings cover most needs. choices=["food", "travel"] rejects anything else and lists the valid values in the help. nargs controls how many values an argument takes: "?" for zero or one, "*" for any number, "+" for at least one, or a number like 2. required=True makes an option mandatory, though a positional argument is usually clearer.
For flags, action="store_true" gives False unless the flag appears. action="count" lets users type -vv for more detail (args.verbose == 2). action="append" collects repeated options into a list. argparse.BooleanOptionalAction (Python 3.9+) creates a pair like --color and --no-color. type can be any function that takes a string: type=pathlib.Path gives Path objects, and your own function can raise argparse.ArgumentTypeError with a helpful message.
- add_argument("-n", "--limit", type=int, default=10)
- add_argument("files", nargs="+", type=Path)
- add_argument("-v", "--verbose", action="count", default=0)
Subcommands like git add and git commit
Many tools have verbs: tracker add, tracker list, tracker summary. Create them with sub = parser.add_subparsers(dest="command", required=True), then p_add = sub.add_parser("add", help="add an expense"). Each subparser has its own arguments and its own --help page.
A clean pattern is to attach the function that handles each command: p_add.set_defaults(func=cmd_add). After parsing, main simply calls args.func(args). Options shared by every command, like --file, can go on the main parser (typed before the subcommand) or on a parent parser passed with parents=[common], so they work after the subcommand too. Keep each cmd_ function thin: read args, call your real logic in another module, print the result and return an exit code.
- add
- amount (float)
- --category
- --date
- list
- --month YYYY-MM
- --limit N
- summary
- --by category or month
- export
- --format csv or json
- --out PATH
Help text, errors and exit codes
Good help is the manual most users will ever read. Give the parser a description (shown at the top) and an epilog (shown at the bottom, great for examples). Write help= for every argument, and use metavar="AMOUNT" for readable placeholders. formatter_class=argparse.ArgumentDefaultsHelpFormatter adds each default to the help automatically; RawDescriptionHelpFormatter keeps your line breaks in the epilog.
Follow the conventions scripts rely on. Results go to stdout and errors go to stderr (print(..., file=sys.stderr)), so output can be piped without mixing in messages. Exit with 0 on success and non-zero on failure: return an int from main and call sys.exit(main()). For a problem argparse cannot detect, such as a start date after the end date, call parser.error("..."), which prints usage and exits with 2 like the built-in checks.
Turning the script into an installed command
Put your code in a package, for example src/tracker/cli.py with a main() function. In pyproject.toml add a [project.scripts] table: tracker = "tracker.cli:main". When the package is installed, pip creates a small launcher called tracker in the environment's bin (or Scripts on Windows) folder. The launcher imports tracker.cli, calls main() and passes its return value to sys.exit.
During development, run pip install -e . inside your virtual environment: the command works immediately and picks up code changes without reinstalling. Add a src/tracker/__main__.py that calls main() so python -m tracker works too. To share the tool, people can install it with pipx install . (or from a Git URL), which gives the command its own isolated environment.
- Step 1Shell finds tracker
In the venv bin folder on PATH
- Step 2Launcher script
Created by pip from [project.scripts]
- Step 3Import tracker.cli
Your installed package
- Step 4sys.exit(main())
Return value becomes the exit code
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Parse arguments with argparse~45m
- 2Add options, flags and defaults~45m
- 3Write helpful usage text~45m
- 4Package the script as a command~45m
Key points
- Positional arguments are required; options start with -- and are usually optional.
- type=int converts and validates; default= fills missing options.
- action="store_true" makes a simple on/off flag.
- -h / --help is generated automatically from your help= strings.
- Add [project.scripts] in pyproject.toml to install it as a real command.
Key terms
Tap a card to flip it. 0/5 known
Examples
import argparse
def main():
parser = argparse.ArgumentParser(description="Track expenses.")
parser.add_argument("amount", type=float, help="amount spent")
parser.add_argument("--category", default="other", help="expense category")
parser.add_argument("--verbose", action="store_true", help="show details")
args = parser.parse_args()
if args.verbose:
print("Parsed:", args)
print(f"Added {args.amount:.2f} to {args.category}")
if __name__ == "__main__":
main()
# python tracker.py 12.5 --category food --verboseA testable CLI with subcommands
Step 1: main(argv=None) builds the parser. Step 2: add one subparser per command and attach its handler with set_defaults. Step 3: parse argv and dispatch to args.func, returning its exit code. Step 4: a test calls main(["add", "12.5"]) directly, no shell needed.
import argparse, sys
def cmd_add(args):
print(f"Added {args.amount:.2f} ({args.category})")
return 0
def main(argv=None):
p = argparse.ArgumentParser(prog="tracker", description="Track expenses.")
sub = p.add_subparsers(dest="command", required=True)
a = sub.add_parser("add", help="add an expense")
a.add_argument("amount", type=float)
a.add_argument("-c", "--category", choices=["food", "travel", "other"], default="other")
a.set_defaults(func=cmd_add)
args = p.parse_args(argv)
return args.func(args)
if __name__ == "__main__":
sys.exit(main())A custom type that validates a month
tracker list --month should accept 2026-03 but reject 2026-13 with a clear message. Step 1: write a function that takes the string and returns a date, raising ArgumentTypeError if it fails. Step 2: pass it as type=. Step 3: argparse calls it and turns the error into a normal usage error with exit code 2.
import argparse
from datetime import datetime, date
def month(text: str) -> date:
try:
return datetime.strptime(text, "%Y-%m").date()
except ValueError:
raise argparse.ArgumentTypeError(f"expected YYYY-MM, got {text!r}")
parser = argparse.ArgumentParser(prog="tracker list")
parser.add_argument("--month", type=month, help="month to show, e.g. 2026-03")
print(parser.parse_args(["--month", "2026-03"]).month) # 2026-03-01
# parser.parse_args(["--month", "2026-13"]) -> error, exit code 2Quick reference
- parser.add_argument("name") positional; add_argument("--name") option
- type=int, choices=[...], default=..., required=True, help="..."
- action="store_true" flag; action="count" for -vv; action="append" for lists
- nargs="?" zero or one, "*" any, "+" one or more
- add_subparsers(dest="command", required=True) plus set_defaults(func=...)
- argparse errors exit with code 2; --help exits with 0
- main(argv=None) with parse_args(argv) makes parsing testable
- [project.scripts] tracker = "tracker.cli:main" then pip install -e .
Common mistakes
- Reading sys.argv by hand and re-inventing parsing and help text.
- Forgetting type=, so numbers arrive as strings.
- Printing errors but exiting with code 0, which hides failures from scripts.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write greet.py that takes a name and an optional --times N (default 1) and prints Hello, NAME! N times.
- Exercise 2medium
Write wc.py that accepts one or more file paths and a -l flag; it prints the line count of each file, or the character count without -l.
- Exercise 3hard
Add a check that --start is not after --end (both dates as YYYY-MM-DD), reporting the problem the same way argparse reports its own errors.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use argparse, click or typer?
- argparse is in the standard library and covers most tools well. click and typer (built on click) are third-party libraries that use decorators or type hints and are popular for larger CLIs; they are worth trying once argparse feels repetitive.
- How do I make an option required?
- Pass required=True to add_argument. If the value is the main input of the command, a positional argument is usually clearer.
- Why does my installed command say command not found?
- The virtual environment is not active, or its bin folder is not on PATH. Activate the venv, or install with pipx, which puts commands on PATH for you.
- How do I show default values in --help?
- Create the parser with formatter_class=argparse.ArgumentDefaultsHelpFormatter, or write %(default)s inside your help strings.