Many useful Python programs are run from a terminal: python grades.py Nusrat 88 92 --round 2. The words after the script name are command-line arguments. You could read them from sys.argv yourself, but then you would also have to convert types, handle missing values and write help text. The built-in argparse module does all of that from a short description of the arguments you expect. This lesson builds two small command-line tools.
In this lesson you will learn
- Positional and optional arguments
- Converting types with
type=and accepting several values withnargs - Flags with
action="store_true", defaults andchoices - Subcommands such as
git addandgit commit - Automatic help and error messages
You should know functions and modules, and how to run a Python file from a terminal.
Positional Arguments, Options and Flags
import argparse
parser = argparse.ArgumentParser(
prog="grades",
description="Calculate a student's average mark.",
)
parser.add_argument("name", help="student name") # positional
parser.add_argument("marks", type=int, nargs="+", help="one or more marks")
parser.add_argument("-r", "--round", type=int, default=1, help="decimal places")
parser.add_argument("-v", "--verbose", action="store_true", help="show details")
# In a real script: args = parser.parse_args() (reads sys.argv)
# Here we pass the command-line words directly so the example is repeatable.
args = parser.parse_args(["Nusrat", "88", "92", "79", "--round", "2", "-v"])
print(args)
avg = sum(args.marks) / len(args.marks)
print(f"{args.name}: {avg:.{args.round}f}")
if args.verbose:
print(f" {len(args.marks)} marks, best {max(args.marks)}")
args = parser.parse_args(["Arif", "70", "65"])
print(f"{args.name}: {sum(args.marks) / len(args.marks):.{args.round}f} verbose={args.verbose}")
Output
Namespace(name='Nusrat', marks=[88, 92, 79], round=2, verbose=True)
Nusrat: 86.33
3 marks, best 92
Arif: 67.5 verbose=False
ArgumentParserholds the description of your program.proganddescriptionappear in the help text."name"and"marks"have no dashes, so they are positional: required and identified by their order.type=intconverts each mark from text to a number, andnargs="+"accepts one or more values, collected into a list.-r/--roundis an optional argument with a short and a long name and a default of 1. The second run did not give it, so the average was rounded to one decimal place.action="store_true"makes--verbosea flag:Truewhen present,Falsewhen absent.- The result is a
Namespacewhose attributes match the argument names, such asargs.marks. A real script callsparser.parse_args()with no list, so it reads what the user typed.
Choices, Subcommands, Errors and Help
import argparse
import contextlib
import io
parser = argparse.ArgumentParser(prog="shop", description="Simple shop tool")
parser.add_argument("--currency", choices=["BDT", "USD"], default="BDT")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", help="add an item")
add.add_argument("item", help="item name")
add.add_argument("--qty", type=int, default=1, help="how many (default 1)")
lst = sub.add_parser("list", help="list items")
lst.add_argument("--limit", type=int, default=10)
for words in (["add", "pen", "--qty", "3"], ["--currency", "USD", "list"]):
print(parser.parse_args(words))
# Bad input: argparse prints a usage message and exits with status 2
err = io.StringIO()
with contextlib.redirect_stderr(err):
try:
parser.parse_args(["add", "pen", "--qty", "three"])
except SystemExit as e:
print("exit status:", e.code)
print(err.getvalue().strip().splitlines()[-1])
# --help text is generated automatically
print(add.format_help())
Output
Namespace(currency='BDT', command='add', item='pen', qty=3)
Namespace(currency='USD', command='list', limit=10)
exit status: 2
shop add: error: argument --qty: invalid int value: 'three'
usage: shop add [-h] [--qty QTY] item
positional arguments:
item item name
options:
-h, --help show this help message and exit
--qty QTY how many (default 1)
choices=["BDT", "USD"]rejects any other currency with a clear message.add_subparserscreates subcommands, each with its own arguments, likegit addandgit commit.dest="command"records which one was used, so the program can branch onargs.command.- When the input is wrong, here “three” for an integer, argparse prints a usage line and an error, then exits with status 2. The example catches
SystemExitonly to show this; a normal script lets it end the program. - The help text, normally shown by running
python shop.py add --help, is generated from thehelp=strings. You never write or update it by hand.
add_argument Options
| Option | Example | Effect |
|---|---|---|
type | type=float | Convert the text to another type |
default | default=10 | Value when the option is not given |
required | required=True | Make an option (with dashes) mandatory |
nargs | "?", "*", "+", 2 | Zero or one, any number, one or more, exactly two |
action | "store_true", "count" | Flags, or counting -vvv |
choices | choices=["a", "b"] | Allow only listed values |
help | help="number of rows" | Text shown by --help |
Common Mistakes
- Reading
sys.argvby hand and forgetting that every value is a string. - Using
type=bool.bool("False")isTrue; useaction="store_true"for flags. - Accessing
args.dry-run. Dashes in option names become underscores:args.dry_run. - Parsing arguments at import time in a module that other code imports. Put it inside
if __name__ == "__main__":.
Practice Exercises
Exercise 1. Write a parser for convert.py 100 --to usd that takes an amount (float) and a --to option limited to usd or eur, defaulting to usd.
Show answer
import argparse
parser = argparse.ArgumentParser(prog="convert")
parser.add_argument("amount", type=float, help="amount in taka")
parser.add_argument("--to", choices=["usd", "eur"], default="usd")
args = parser.parse_args(["100", "--to", "eur"])
print(args.amount, args.to) # 100.0 eur
Exercise 2. Add a -v option that can be repeated, so -vv means verbosity level 2.
Show answer
parser.add_argument("-v", "--verbose", action="count", default=0)
args = parser.parse_args(["100", "-vv"])
print(args.verbose) # 2
Frequently Asked Questions
What is sys.argv?
A list of the words typed on the command line. sys.argv[0] is the script name and the rest are the arguments, all as strings. argparse reads this list for you.
Are there alternatives to argparse?
Yes. Third-party libraries such as Click and Typer build command-line tools with decorators or type hints. argparse is built in, so it needs no installation, which makes it a good default for scripts.
Summary
- argparse turns command-line words into typed values in a
Namespace. - Names without dashes are positional; names with dashes are optional.
- Use
type,nargs,default,choicesandstore_trueto describe input. - Help text and error messages are generated automatically.
