16.4. argparse — Parser for command-line options, arguments and sub-commands¶
3.2 版新加入.
Source code: Lib/argparse.py
The argparse module makes it easy to write user-friendly command-line
interfaces. The program defines what arguments it requires, and argparse
will figure out how to parse those out of sys.argv. The argparse
module also automatically generates help and usage messages and issues errors
when users give the program invalid arguments.
16.4.1. Example¶
The following code is a Python program that takes a list of integers and produces either the sum or the max:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
Assuming the Python code above is saved into a file called prog.py, it can
be run at the command line and provides useful help messages:
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]
Process some integers.
positional arguments:
N an integer for the accumulator
optional arguments:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)
When run with the appropriate arguments, it prints either the sum or the max of the command-line integers:
$ python prog.py 1 2 3 4
4
$ python prog.py 1 2 3 4 --sum
10
If invalid arguments are passed in, it will issue an error:
$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'
The following sections walk you through this example.
16.4.1.1. Creating a parser¶
The first step in using the argparse is creating an
ArgumentParser object:
>>> parser = argparse.ArgumentParser(description='Process some integers.')
The ArgumentParser object will hold all the information necessary to
parse the command line into Python data types.
16.4.1.2. Adding arguments¶
Filling an ArgumentParser with information about program arguments is
done by making calls to the add_argument() method.
Generally, these calls tell the ArgumentParser how to take the strings
on the command line and turn them into objects. This information is stored and
used when parse_args() is called. For example:
>>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
... help='an integer for the accumulator')
>>> parser.add_argument('--sum', dest='accumulate', action='store_const',
... const=sum, default=max,
... help='sum the integers (default: find the max)')
Later, calling parse_args() will return an object with
two attributes, integers and accumulate. The integers attribute
will be a list of one or more ints, and the accumulate attribute will be
either the sum() function, if --sum was specified at the command line,
or the max() function if it was not.
16.4.1.3. Parsing arguments¶
ArgumentParser parses arguments through the
parse_args() method. This will inspect the command line,
convert each argument to the appropriate type and then invoke the appropriate action.
In most cases, this means a simple Namespace object will be built up from
attributes parsed out of the command line:
>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
In a script, parse_args() will typically be called with no
arguments, and the ArgumentParser will automatically determine the
command-line arguments from sys.argv.
16.4.2. ArgumentParser objects¶
-
class
argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True)¶ Create a new
ArgumentParserobject. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:
