Sub topic 2
Creating a parser and reading arguments
This chapter assumes you can write and run Python scripts, define functions, handle exceptions, and use a terminal. It also assumes you know what sys.argv, standard output, standard error and exit codes are, from the previous chapter. Here you meet the two objects at the center of argparse: the ArgumentParser that describes your command line, and the Namespace that holds the parsed result.
The parser/namespace model
An ArgumentParser is a declaration. You create it, register the arguments your program accepts, and call parse_args. That call does three things:
- It takes a list of strings, normally
sys.argv[1:]. - It matches the strings against the declared arguments, converts values, and fills in defaults.
- It returns a
Namespace, a plain object with one attribute per argument. If the input is invalid, it prints a message to standard error and exits instead.
A first parser
import argparse
parser = argparse.ArgumentParser(prog="greet", description="Print a greeting.")
parser.add_argument("name")
parser.add_argument("--count", type=int, default=1)
args = parser.parse_args(["Ada", "--count", "2"])
print(args)
print(args.name, args.count)
print(vars(args))Running it prints:
Namespace(count=2, name='Ada')
Ada 2
{'name': 'Ada', 'count': 2}Three points to notice:
- Each argument becomes an attribute. Read it with
args.name, or turn the namespace into a dictionary withvars(args). - The
reprof aNamespacesorts attributes alphabetically. The dictionary fromvarsfollows the order in which the arguments were declared. - Passing a list to
parse_argsis the same as typing those words in a shell. This is how you experiment in a REPL, and later how you test (the testing chapter relies on it).
Where the strings come from
When you call parse_args() with no argument, or with None, argparse reads sys.argv[1:]. It skips element 0, which is the program name.
import argparse
import sys
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("word")
print(sys.argv)
args = parser.parse_args()
print(args.word)If you save this as demo.py and run python demo.py hello, you see ['demo.py', 'hello'] and then hello.
The shell has already split the line before Python sees it. python demo.py "two words" gives one argument, two words. Quoting, wildcards and variable expansion are the shell's job. argparse never sees them.
Constructor options you will use
ArgumentParser accepts many keyword arguments. These are the ones that matter at this stage:
| Parameter | Default | Effect |
|---|---|---|
| `prog` | basename of `sys.argv[0]` | Name shown in usage and error messages. |
| `description` | none | Text shown in help, before the argument list. |
| `add_help` | `True` | Adds `-h` and `--help`. Set `False` if you want to define `-h` yourself. |
| `allow_abbrev` | `True` | Lets users shorten long options, such as `--coun` for `--count`. |
| `exit_on_error` | `True` | When `False`, some errors raise `ArgumentError` instead of exiting. |
Set prog explicitly in anything you plan to test or package. The automatic value depends on how the script was launched, so messages can differ between python tool.py and an installed command.
What the Namespace contains
Every argument you declare ends up in the namespace, even when the user did not supply it. An argument that was not supplied holds its default, which is None unless you set another.
import argparse
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("--dry-run", action="store_true")
parser.add_argument("--output")
parser.add_argument("--retries", type=int, default=3)
args = parser.parse_args([])
print(args.dry_run, args.output, args.retries)This prints False None 3.
The attribute name is called the dest. argparse derives it from the first long option name: it strips the leading dashes and replaces inner dashes with underscores. So --dry-run becomes args.dry_run. You can override it with dest="...", but the default is usually what readers expect.
Because an unset option holds None, use is None when you need to detect "not provided". Don't test truthiness. A user who passes --retries 0 supplied a value, and 0 is falsy.
if args.output is None:
print("no output file given")Automatic help and automatic errors
add_help=True gives your tool -h and --help at no cost. Asking for help prints the help text to standard output and exits with status 0. Invalid input is handled differently: argparse prints the usage line and an error message to standard error, then exits with status 2.
With the greet parser from earlier, these two failures look like this:
usage: greet [-h] [--count COUNT] name
greet: error: the following arguments are required: nameusage: greet [-h] [--count COUNT] name
greet: error: argument --count: invalid int value: 'many'Exit status 2 is the convention for command-line usage errors, so shell scripts and CI systems can tell a bad invocation apart from a program failure, which conventionally uses status 1.
Under the hood, argparse reports these errors by calling parser.error(message). You can call it yourself when you find a problem that no single argument can express:
import argparse
parser = argparse.ArgumentParser(prog="range")
parser.add_argument("--low", type=int, default=0)
parser.add_argument("--high", type=int, default=10)
args = parser.parse_args(["--low", "5", "--high", "2"])
if args.low > args.high:
parser.error("--low must not be greater than --high")This prints the usage line and range: error: --low must not be greater than --high to standard error, then exits with status 2. Using parser.error keeps cross-argument checks consistent with argparse's own messages.
Unknown arguments
parse_args rejects anything it does not recognize. If you want to keep what it does not understand, for instance to forward it to another program, use parse_known_args. It returns a tuple of the namespace and a list of leftover strings.
import argparse
parser = argparse.ArgumentParser(prog="wrapper")
parser.add_argument("name")
args, extras = parser.parse_known_args(["Ada", "--color=red"])
print(args.name)
print(extras)This prints Ada and then ['--color=red'].
Use this sparingly. If your tool silently accepts typos, users get no feedback. A misspelled --verbos would end up in extras and be ignored, where parse_args would have rejected it.
The `--` separator and dash-prefixed values
argparse decides whether a string is an option or a value by looking at its first character. A string that starts with - is treated as an option. That causes trouble when a legitimate value begins with a dash, such as a filename or a search pattern.
The conventional fix is --. Everything after it is treated as a positional value:
import argparse
parser = argparse.ArgumentParser(prog="find")
parser.add_argument("pattern")
print(parser.parse_args(["--", "-v"]).pattern)This prints -v. Without the --, argparse would report that -v is an unrecognized argument.
Negative numbers are a special case. If your parser has no option that itself looks like a negative number, such as -1, then a string like -5 is treated as a value and parse_args accepts it.
Common mistakes
- Reading the wrong name.
--dry-runisargs.dry_run, notargs.dry-run. The hyphenated form is a syntax error in Python. - Forgetting the
type. Withouttype=int,--count 3gives the string"3". Arithmetic then fails or, worse, repeats a string. - Truthiness checks on optional values. Use
is None, as shown above, so that0and""count as supplied values. - Catching
SystemExitto handle usage errors in production code. Let argparse exit. CatchSystemExitonly in tests, where you want to inspect the status.
Exercise
A parser is built with parser.add_argument("--max-items", type=int). A user runs the program without that option. What does args.max_items contain, and how should you test whether the user supplied the option?
Show answer
It contains None, because an unset option with no default is None. Test with args.max_items is None. A truthiness check such as if not args.max_items would wrongly treat an explicit --max-items 0 as "not supplied".
Exercise
You want a tool to accept a pattern that starts with a dash, such as -draft, as its only positional argument. What do you type on the command line, and what does argparse do with the string after the separator?
Show answer
Type tool -- -draft. The -- tells argparse that every following string is a positional value, so -draft is stored as the positional argument and is not parsed as an option.