Sub topic 2
Creating a parser and reading arguments
This chapter assumes you can write Python functions and run scripts from a terminal. It also assumes you know that a program receives its arguments as a list of strings (sys.argv) and that it reports success or failure through an exit code. Here you will create an ArgumentParser and turn that list of strings into attributes you can use.
What the parser does
argparse.ArgumentParser is an object that holds your declaration of what the command accepts. You register each argument with add_argument. Then you call parse_args, which does three things:
- It reads the list of strings.
- It matches them against your declarations and converts them.
- It returns a
Namespace, a simple object with one attribute per argument.
If the input does not match, parse_args prints a usage message to stderr and exits with status 2.
A first parser
import argparse
parser = argparse.ArgumentParser(prog="greet", description="Print a greeting.")
parser.add_argument("name")
parser.add_argument("--max-count", type=int, default=1)
args = parser.parse_args(["Ada", "--max-count", "2"])
print(args)
print(args.name, args.max_count)This prints:
Namespace(name='Ada', max_count=2)
Ada 2Three details are worth noting:
progis the program name shown in usage messages. If you omit it, argparse uses the script's file name.descriptionappears in the--helpoutput. A-h/--helpoption is added automatically.- The option
--max-countbecomes the attributemax_count. argparse replaces dashes with underscores because dashes are not valid in Python names.
Where the arguments come from
parse_args(None) is the same as parse_args(sys.argv[1:]). That is the default when you pass nothing. Passing an explicit list of strings instead lets you try the parser in a REPL or a test without a terminal. Chapter 9 builds on this when it structures programs around main(argv).
import argparse
parser = argparse.ArgumentParser(prog="greet")
parser.add_argument("name")
args = parser.parse_args([])usage: greet [-h] name
greet: error: the following arguments are required: nameThe process then exits with status 2. In Python this is a SystemExit exception, so a test or a caller can catch it.
Working with the Namespace
Read values as attributes: args.name. To get a dictionary, for example to pass values on as keyword arguments, use vars(args).
print(vars(args))Common errors
- Parsing at import time. If you call
parse_args()at module level, importing the module (from a test, for instance) parses the importer's arguments, and it can exit. Build the parser in a function and parse only when you run the program. - Non-string items in the list. The list you pass must contain strings.
["Ada", 2]fails. Write"2"and lettype=intconvert it. - Wrong attribute name.
--max-countis read asargs.max_count, notargs.max-count. - Expecting exceptions. Bad input does not raise
ValueErroror similar. It ends the process throughSystemExit.
Exercise
A parser declares parser.add_argument("--dry-run", action="store_true"). What attribute name do you read from the result of parse_args(["--dry-run"]), and how can you run the parser in a test without touching the terminal?
Show answer
Read args.dry_run, since dashes become underscores. In a test, pass the list explicitly: parser.parse_args(["--dry-run"]), so argparse does not read sys.argv.