Reading history

Python argparse: Command-Line Arguments Tutorial

6 min read Updated 1 views

Build command-line tools with Python argparse: positional and optional arguments, type and nargs, flags, choices, subcommands, and automatic help and errors.

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 with nargs
  • Flags with action="store_true", defaults and choices
  • Subcommands such as git add and git 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
  • ArgumentParser holds the description of your program. prog and description appear in the help text.
  • "name" and "marks" have no dashes, so they are positional: required and identified by their order.
  • type=int converts each mark from text to a number, and nargs="+" accepts one or more values, collected into a list.
  • -r/--round is 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 --verbose a flag: True when present, False when absent.
  • The result is a Namespace whose attributes match the argument names, such as args.marks. A real script calls parser.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_subparsers creates subcommands, each with its own arguments, like git add and git commit. dest="command" records which one was used, so the program can branch on args.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 SystemExit only 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 the help= strings. You never write or update it by hand.

add_argument Options

OptionExampleEffect
typetype=floatConvert the text to another type
defaultdefault=10Value when the option is not given
requiredrequired=TrueMake an option (with dashes) mandatory
nargs"?", "*", "+", 2Zero or one, any number, one or more, exactly two
action"store_true", "count"Flags, or counting -vvv
choiceschoices=["a", "b"]Allow only listed values
helphelp="number of rows"Text shown by --help

Common Mistakes

  1. Reading sys.argv by hand and forgetting that every value is a string.
  2. Using type=bool. bool("False") is True; use action="store_true" for flags.
  3. Accessing args.dry-run. Dashes in option names become underscores: args.dry_run.
  4. 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, choices and store_true to describe input.
  • Help text and error messages are generated automatically.

Next: Python Scope, global, nonlocal and Closures.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *