Python

Python argparse — Arguments, Options, and Subcommands

A script that reads its settings from the command line can be run by a person, a cron job, or another script, with no editing between runs. The argparse module in the standard library turns the words after the program name into named values the code can use, checks them as they arrive, and prints a usage message when they are wrong. This guide builds a parser one piece at a time: a positional argument first, then an option with a default, a type conversion, a fixed set of choices, a list of values, flags that take no value, and at the end a program with two subcommands. Each step is a small working program with the exact output it prints.

Written November 12, 2026 · Tested with Python 3.12.3 · 12 min read

By the end of this guide
  • The main program: positional arguments arrive as strings
  • Options take a default and a short name
  • The type setting converts the string
  • choices limits the values, required makes an option mandatory

Written November 12, 2026

Tested with Python 3.12.3

What this guide is

When a program runs from a command line, the words after its name arrive as a list of strings. The argparse module reads that list against a set of rules the program declares in advance: which words are required, which are options, what type each value should become, and which values are allowed at all. The parse step returns one object whose attributes hold the values, already converted. If the words break a rule, the parser prints a usage line and an error to the standard error stream and ends the program with exit code 2, before any of the program's own work runs. The programs in this guide pass their argument lists straight to parse_args, so each one runs as written and prints what a real command line would produce. A real script calls parse_args with no list, and the parser then reads the actual command line.

The main program: positional arguments arrive as strings

A positional argument is a value the command line must supply, in order. The name given to add_argument becomes the attribute name on the result:

Python
import argparse
parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("name")
parser.add_argument("count")
args = parser.parse_args(["ana", "3"])
print(args)
print(args.name)
print(args.count)
print(type(args.count))

The exact output:

Output
Namespace(name='ana', count='3')
ana
3
<class 'str'>

The result is a Namespace, a plain object whose attributes are the argument names. The last two lines carry the fact that shapes the rest of this guide: the count arrived as the string "3", not the number 3, even though the person who typed it meant a number. Every value starts as a string. Converting it is the parser's job only when the program asks, which is the type setting in a later section. The prog name given at the top is the name the parser uses in its usage and error messages, so a script run under a different file name still reports itself the same way.

Options take a default and a short name

An argument whose name starts with a dash is an option: it can be left out, and where it stands on the command line does not matter. The default setting gives the value an option carries when it is left out:

Python
import argparse
parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("name")
parser.add_argument("--greeting", default="hello")
parser.add_argument("-n", "--count", type=int, default=1)
print(parser.parse_args(["ana"]))
print(parser.parse_args(["bo", "--greeting", "hi", "-n", "2"]))
print(parser.parse_args(["cy", "--count=3"]))

The exact output:

Output
Namespace(name='ana', greeting='hello', count=1)
Namespace(name='bo', greeting='hi', count=2)
Namespace(name='cy', greeting='hello', count=3)

The first parse supplies no options at all, and both attributes still exist, holding their defaults. Code that reads args.greeting never has to test whether the option was given. The second parse shows the two name forms working side by side: a long name with two dashes and a short name with one. A program gives an option both forms by listing the short name first, and the attribute takes its name from the long form, with the dashes stripped and any inner dash turned into an underscore. The third parse shows the equals form, where the name and the value arrive as one word. All three forms put the same value in the same attribute.

The type setting converts the string

The type setting names a function the parser runs on the string before storing it. The built-in int and float functions are the common cases, and they make the stored value a number the code can do arithmetic on at once:

Python
import argparse, contextlib, io
parser = argparse.ArgumentParser(prog="add")
parser.add_argument("count", type=int)
parser.add_argument("ratio", type=float)
args = parser.parse_args(["3", "0.5"])
print(args)
print(args.count + 1)
print(args.ratio * 2)
print(type(args.count), type(args.ratio))
with contextlib.redirect_stderr(io.StringIO()):
    try:
        parser.parse_args(["three", "0.5"])
    except SystemExit as e:
        print("SystemExit", e.code)

The exact output:

Output
Namespace(count=3, ratio=0.5)
4
1.0
<class 'int'> <class 'float'>
SystemExit 2

The count adds and the ratio doubles because both are numbers now. The second half of the program shows what a bad value does. The word "three" cannot convert to an int, so the parser prints its usage line and an invalid int error to the standard error stream and raises SystemExit with code 2. On a real command line that ends the program with code 2, the code shells and scripts read as "the command was called wrong". The redirect in this program only captures that error text so the printed output stays readable; a normal script needs no such code, because the parser handles the bad call on its own. Any one-argument function can serve as a type, so a program that needs a date or a path can pass a function that builds one, and a failure inside that function fails the parse the same way.

choices limits the values, required makes an option mandatory

The choices setting holds the full set of values an argument may take. A value outside the set fails the parse. The required setting, set on an option, makes that option mandatory even though options are normally free to be left out:

Python
import argparse, contextlib, io
parser = argparse.ArgumentParser(prog="paint")
parser.add_argument("item")
parser.add_argument("--color", choices=["red", "green", "blue"], required=True)
print(parser.parse_args(["door", "--color", "green"]))
with contextlib.redirect_stderr(io.StringIO()):
    try:
        parser.parse_args(["door", "--color", "pink"])
    except SystemExit as e:
        print("SystemExit", e.code)
    try:
        parser.parse_args(["door"])
    except SystemExit as e:
        print("SystemExit", e.code)

The exact output:

Output
Namespace(item='door', color='green')
SystemExit 2
SystemExit 2

Two different mistakes give the same exit code. The pink call fails because pink is not in the choices list, and the bare call fails because a required option is missing. In both cases the parser's error message names the problem, the bad value in the first case and the missing option in the second, so the person who ran the command can fix the call without reading the source. Choices work on positional arguments as well, which suits a program whose first word must be one of a few fixed modes. The check runs after any type conversion, so a numeric argument with choices compares as a number.

nargs collects a run of values into a list

Some arguments carry more than one value: the files a tool should process, the numbers a total should add. The nargs setting tells the parser how many values to gather. A plus sign means one or more, a star means zero or more, and a question mark means zero or one:

Python
import argparse
parser = argparse.ArgumentParser(prog="total")
parser.add_argument("numbers", nargs="+", type=int)
parser.add_argument("--tags", nargs="*", default=[])
parser.add_argument("--suffix", nargs="?")
args = parser.parse_args(["1", "2", "3"])
print(args)
print(sum(args.numbers))
args = parser.parse_args(["4", "5", "--tags", "a", "b", "--suffix", "end"])
print(args)
print(sum(args.numbers))

The exact output:

Output
Namespace(numbers=[1, 2, 3], tags=[], suffix=None)
6
Namespace(numbers=[4, 5], tags=['a', 'b'], suffix='end')
9

The numbers attribute is a list in both parses, and sum works on it directly because the type setting converted each item. The plus sign also does a counting job: a call with no numbers at all fails the parse, since one or more were promised. The tags option with a star gathers every word after it up to the next option name, and holds an empty list when the option is absent, so code can loop over it without a test. The suffix option with a question mark holds one value or None. The parser knows where the tags run ends because --suffix starts with a dash; a value that itself starts with a dash needs the equals form, as --tags=-x, to be read as a value instead of an option.

Flags take no value: store_true and count

A flag is an option that records whether it appeared. The store_true action stores True when the flag is present and False when it is not, and the flag takes no value after it. Its partner, store_false, does the reverse. The count action counts how many times a short flag repeats:

Python
import argparse
parser = argparse.ArgumentParser(prog="run")
parser.set_defaults(color=True)
parser.add_argument("--verbose", action="store_true")
parser.add_argument("--color", action="store_true")
parser.add_argument("--no-color", action="store_false", dest="color")
parser.add_argument("-v", action="count", default=0)
print(parser.parse_args([]))
print(parser.parse_args(["--verbose", "-vv"]))
print(parser.parse_args(["--no-color"]))
print(parser.parse_args(["--color"]))

The exact output:

Output
Namespace(verbose=False, color=True, v=0)
Namespace(verbose=True, color=True, v=2)
Namespace(verbose=False, color=False, v=0)
Namespace(verbose=False, color=True, v=0)

The --color and --no-color pair shows how two flags share one attribute: both name the same dest, so whichever appears sets the single color value, and set_defaults gives that value its starting point of True before either flag is read. Without that line the starting value would come from whichever action was declared first, which is a quiet way to ship a default the program never chose. The count lines show -v repeated as -vv storing 2, the form command-line tools use for a verbosity level that rises with each repeat. A valued option and a flag look alike on the command line until one is given a value: writing --verbose true makes true an extra word the parser has no positional argument for, and the parse fails.

Subparsers give one program several commands

A program that does several jobs, the way a package tool installs, removes, and lists, gives each job its own parser under one main parser. Each subparser declares only the arguments its job takes, and the dest on the group records which command word was given:

Python
import argparse
parser = argparse.ArgumentParser(prog="tool")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add")
add.add_argument("name")
show = sub.add_parser("show")
show.add_argument("name")
show.add_argument("--full", action="store_true")
print(parser.parse_args(["add", "ana"]))
print(parser.parse_args(["show", "ana", "--full"]))
print(parser.parse_args(["show", "bo"]).command)

The exact output:

Output
Namespace(command='add', name='ana')
Namespace(command='show', name='ana', full=True)
show

The two namespaces differ in shape, not just in values: the add result has no full attribute at all, because that option belongs to the show parser alone. Code that branches on args.command must read only the attributes the chosen subparser declares. Setting required on the group makes a bare call, with no command word, fail the parse instead of returning a namespace with command set to None; without it, the branch has to catch that case itself. Each subparser also gets its own help text, so tool show --help lists only the show arguments. That split is what keeps a large command-line program readable as it grows: one command's options never appear in another command's usage line.

Which form for which job

Job Form Why
A value every call must supply A positional argument The parse fails without it
A setting most calls leave alone An option with a default The attribute always exists
A number the code computes with The type setting with int or float The stored value is a number, and a bad one fails the parse
A value from a fixed set The choices setting An outside value fails with a named error
An option no call may skip An option with required set It stays an option in form but not in effect
A run of files or numbers nargs with a plus sign The values arrive as one list, and an empty run fails
A switch that is on or off The store_true or store_false action The flag takes no value
A level that rises with repetition The count action on a short flag Each repeat adds one
Several jobs in one program Subparsers with a required group Each job declares only its own arguments

Checklist

  • Before doing arithmetic on an argument, set its type, because every value arrives as a string until the parser converts it.
  • Before reading an option in the code, give it a default, because an option with no default stores None when it is left out.
  • Before letting a value reach the program's own checks, ask whether choices can state the allowed set, because a parse error names the bad value for free.
  • Before using a plus-sign nargs argument, check the empty case, because the parse fails when no value is given.
  • Before pairing a store_true and a store_false flag on one dest, set the starting value with set_defaults, because the first declared action otherwise picks it.
  • Before branching on a subcommand, set required on the subparser group, because a bare call otherwise returns a namespace whose command is None.

Sources

  • Python, argparse — the library reference for ArgumentParser, add_argument, and the type, choices, nargs, and action settings this guide follows.
  • Python, argparse Tutorial — the tutorial for positional and optional arguments, short names, and combining values in a parse.

Keep Exploring