Command-line programs · 3 / 15 Theory

Options and flags

Besides positional arguments, almost all tools accept options: named arguments that start with - or -- and are optional (unless you say otherwise).

Options with a value

They are declared with a name that starts with -- (and, if you want, a short form with a single dash). The value goes after. If it is not typed, it is default (or None).

import argparse

parser = argparse.ArgumentParser(prog="table")
parser.add_argument("n", type=int)
parser.add_argument("--to", type=int, default=10)
parser.add_argument("-d", "--decimals", type=int, default=2)

print(parser.parse_args(["3"]))
# Namespace(n=3, to=10, decimals=2)
print(parser.parse_args(["3", "--to", "5", "-d", "0"]))
# Namespace(n=3, to=5, decimals=0)
print(parser.parse_args(["--to=7", "3"]))
# Namespace(n=3, to=7, decimals=2)

Options can go in any order and before or after the positionals. They accept --to 5 and --to=5. Note that the attribute of --decimals is args.decimals: the dashes are removed and inner dashes become _ (--max-size → args.max_size).

Flags: options without a value

A flag is activated just by typing it. With action="store_true" it is True if it appears and False if not. Short flags can be grouped: -lc is the same as -l -c.

import argparse

parser = argparse.ArgumentParser(prog="wc")
parser.add_argument("-l", "--lines", action="store_true")
parser.add_argument("-w", "--words", action="store_true")
parser.add_argument("-c", "--chars", action="store_true")

args = parser.parse_args(["-l", "-c"])
print(args.lines, args.words, args.chars)   # True False True

args = parser.parse_args(["-lc"])
print(args.lines, args.words, args.chars)   # True False True

args = parser.parse_args([])
print(args.lines, args.words, args.chars)   # False False False

It is what you use in Counter like wc: if no flag is activated, everything is shown.

More useful actions

ActionWhat it doesExample of use
store_true / store_falsestores True / False--verbose
store_conststores a fixed value--fast → const="fast"
countcounts how many times it appears-v, -vv, -vvv (level of detail)
appendaccumulates several appearances in a list--tag a --tag b → ["a", "b"]
import argparse

parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("-v", "--verbose", action="count", default=0)
parser.add_argument("--tag", action="append", default=[])

args = parser.parse_args(["-vv", "--tag", "a", "--tag", "b"])
print(args.verbose, args.tag)   # 2 ['a', 'b']

Required options and allowed values

Although they are called "options", you can demand that they are present with required=True, and limit their values with choices. This is how the converter of Unit converter is built.

import argparse
import contextlib
import io

FACTORS = {"m": 1.0, "km": 1000.0}

parser = argparse.ArgumentParser(prog="conv")
parser.add_argument("value", type=float)
parser.add_argument("--from", dest="source", choices=FACTORS, required=True)
parser.add_argument("--to", dest="target", choices=FACTORS, required=True)

args = parser.parse_args(["2.5", "--from", "km", "--to", "m"])
print(args.value * FACTORS[args.source] / FACTORS[args.target])   # 2500.0

try:
    with contextlib.redirect_stderr(io.StringIO()):
        parser.parse_args(["2.5", "--from", "km"])      # --to is missing
except SystemExit as e:
    print("code:", e.code)                              # code: 2

--from is a reserved word in Python, so it could not be a variable name: with dest="source" you decide the attribute name. The same technique appears in Multiplication table with options.

Options that exclude each other

import argparse
import contextlib
import io

parser = argparse.ArgumentParser(prog="output")
group = parser.add_mutually_exclusive_group()
group.add_argument("--json", action="store_true")
group.add_argument("--csv", action="store_true")

print(parser.parse_args(["--json"]))   # Namespace(json=True, csv=False)

try:
    with contextlib.redirect_stderr(io.StringIO()):
        parser.parse_args(["--json", "--csv"])
except SystemExit as e:
    print("code:", e.code)   # code: 2

If you use negative values as arguments (-5), argparse recognizes them as numbers as long as the program does not define options that look like numbers.