Command-line programs · 2 / 15 Theory

argparse: positional arguments

With sys.argv you have to check lengths, convert types and write the error messages yourself. The argparse module of the standard library does it for you: it validates the arguments, converts the types, generates the help (-h) and shows clear error messages.

Your first parser

You create an ArgumentParser, declare the arguments with add_argument and call parse_args(). Without parameters, parse_args() reads sys.argv; in these examples we pass it a list so that they are reproducible.

import argparse

parser = argparse.ArgumentParser(prog="greet", description="Greets someone")
parser.add_argument("name")
parser.add_argument("times", type=int, nargs="?", default=1)

args = parser.parse_args(["Ana", "3"])
print(args.name, args.times)   # Ana 3

args = parser.parse_args(["Luis"])
print(args.name, args.times)   # Luis 1
print(args)                    # Namespace(name='Luis', times=1)

The result is a Namespace object with one attribute per argument: args.name, args.times.

Positional arguments

A positional argument is identified by its position. These are the most useful options of add_argument:

ParameterWhat it is forExample
typeconverts the text to another typetype=int, type=float
defaultvalue if nothing is typed (with nargs="?")default=1
choicesonly accepts certain valueschoices=["+", "-", "x", "/"]
nargshow many values it accepts"?" (0 or 1), "*" (0 or more), "+" (1 or more), a number
helphelp texthelp="name of the person"
import argparse

parser = argparse.ArgumentParser(prog="calc")
parser.add_argument("a", type=int)
parser.add_argument("op", choices=["+", "-", "x", "/"])
parser.add_argument("b", type=int)

args = parser.parse_args(["6", "x", "7"])
print(args.a, args.op, args.b)   # 6 x 7
print(args.a * args.b)           # 42

type=int does the conversion (and the validation) for you: int(sys.argv[1]) is no longer needed. It is the structure of Calculator with argparse.

Lists of values with nargs

import argparse

parser = argparse.ArgumentParser(prog="statistics")
parser.add_argument("numbers", nargs="+", type=float)

args = parser.parse_args(["4", "8", "15"])
print(args.numbers)                            # [4.0, 8.0, 15.0]
print(sum(args.numbers) / len(args.numbers))   # 9.0

With nargs="+" one or more values are accepted and stored in a list. It is what you need in Statistics of a list of numbers.

What happens when there is an error

If an argument is invalid or missing, argparse writes a message to standard error and ends the program with exit code 2. In these examples we catch that termination to see it.

import argparse
import contextlib
import io

parser = argparse.ArgumentParser(prog="calc")
parser.add_argument("n", type=int)

error = io.StringIO()
try:
    with contextlib.redirect_stderr(error):
        parser.parse_args(["abc"])
except SystemExit as e:
    print("code:", e.code)                        # code: 2
print(error.getvalue().splitlines()[-1])          # calc: error: argument n: invalid int value: 'abc'

Automatic help

-h or --help show the help without you writing anything. With format_usage() you can see the usage line that is generated.

import argparse

parser = argparse.ArgumentParser(prog="calc")
parser.add_argument("a", type=int)
parser.add_argument("op", choices=["+", "-"])
parser.add_argument("b", type=int)
print(parser.format_usage().strip())   # usage: calc [-h] a {+,-} b

Describe each argument with help="..." and your program documents itself.