The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 will figure out how to parse those out of
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag04. The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 module also automatically generates help and usage messages. The module will also issue errors when users give the program invalid arguments.
Core Functionality¶
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 module’s support for command-line interfaces is built around an instance of
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag07. It is a container for argument specifications and has options that apply the parser as whole:
parser = argparse.ArgumentParser[ prog = 'ProgramName', description = 'What the program does', epilog = 'Text at the bottom of help']
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag08 method attaches individual argument specifications to the parser. It supports positional arguments, options that accept values, and on/off flags:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag09 method runs the parser and places the extracted data in a
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag10 object:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]
Quick Links for add_argument[]¶
Name
Description
Values
action
Specify how an argument should be handled
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag11,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag12,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag13,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag14,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag15,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag16,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag17,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag18
choices
Limit values to a specific set of choices
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag19,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag20, or
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag21 instance
const
Store a constant value
default
Default value used when an argument is not provided
Defaults to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag22
dest
Specify the attribute name used in the result namespace
help
Help message for an argument
metavar
Alternate display name for the argument as shown in help
nargs
Number of times the argument can be used
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag23,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag24,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag25,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag26, or
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag27
required
Indicate whether an argument is required or optional
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag28 or
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29
type
Automatically convert an argument to the given type
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag23,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag31,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag32, or callable function
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 above Python code is saved into a file called
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag33, it can be run at the command line and it 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 options: -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, an error will be displayed:
$ 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.
Creating a parser¶
The first step in using the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 is creating an
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 object:
>>> parser = argparse.ArgumentParser[description='Process some integers.']
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 object will hold all the information necessary to parse the command line into Python data types.
Adding arguments¶
Filling an
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 with information about program arguments is done by making calls to the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38 method. Generally, these calls tell the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 how to take the strings on the command line and turn them into objects. This information is stored and used when
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 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
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 will return an object with two attributes,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag42 and
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag43. The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag42 attribute will be a list of one or more integers, and the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag43 attribute will be either the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag46 function, if
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag47 was specified at the command line, or the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag48 function if it was not.
Parsing arguments¶
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 parses arguments through the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 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
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag51 object will be built up from attributes parsed out of the command line:
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]
In a script,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 will typically be called with no arguments, and the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 will automatically determine the command-line arguments from
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag04.
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, exit_on_error=True]¶Create a new
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:
prog - The name of the program [default:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
56]usage - The string describing the program usage [default: generated from arguments added to parser]
description - Text to display before the argument help [by default, no text]
epilog - Text to display after the argument help [by default, no text]
parents - A list of
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
35 objects whose arguments should also be includedformatter_class - A class for customizing the help output
prefix_chars - The set of characters that prefix optional arguments [default: ‘-‘]
fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read [default:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22]argument_default - The global default value for arguments [default:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22]conflict_handler - The strategy for resolving conflicting optionals [usually unnecessary]
add_help - Add a
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
60 option to the parser [default:parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
28]allow_abbrev - Allows long options to be abbreviated if the abbreviation is unambiguous. [default:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
28]exit_on_error - Determines whether or not ArgumentParser exits with error info when an error occurs. [default:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
28]
Changed in version 3.5: allow_abbrev parameter was added.
Changed in version 3.8: In previous versions, allow_abbrev also disabled grouping of short flags such as
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag64 to mean
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag65.
Changed in version 3.9: exit_on_error parameter was added.
The following sections describe how each of these are used.
prog¶
By default,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 objects use
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag67 to determine how to display the name of the program in help messages. This default is almost always desirable because it will make the help messages match how the program was invoked on the command line. For example, consider a file named
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag68 with the following code:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag0
The help for this program will display
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag68 as the program name [regardless of where the program was invoked from]:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag1
To change this default behavior, another value can be supplied using the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag70 argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag2
Note that the program name, whether determined from
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag67 or from the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag70 argument, is available to help messages using the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag74 format specifier.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag3
usage¶
By default,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 calculates the usage message from the arguments it contains:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag4
The default message can be overridden with the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag76 keyword argument:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag5
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag74 format specifier is available to fill in the program name in your usage messages.
description¶
Most calls to the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 constructor will use the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag79 keyword argument. This argument gives a brief description of what the program does and how it works. In help messages, the description is displayed between the command-line usage string and the help messages for the various arguments:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag6
By default, the description will be line-wrapped so that it fits within the given space. To change this behavior, see the formatter_class argument.
epilog¶
Some programs like to display additional description of the program after the description of the arguments. Such text can be specified using the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag80 argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag7
As with the description argument, the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag80 text is by default line-wrapped, but this behavior can be adjusted with the formatter_class argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35.
parents¶
Sometimes, several parsers share a common set of arguments. Rather than repeating the definitions of these arguments, a single parser with all the shared arguments and passed to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag84 argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 can be used. The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag84 argument takes a list of
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 objects, collects all the positional and optional actions from them, and adds these actions to the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 object being constructed:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag8
Note that most parent parsers will specify
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag89. Otherwise, the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 will see two
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag60 options [one in the parent and one in the child] and raise an error.
Note
You must fully initialize the parsers before passing them via
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag84. If you change the parent parsers after the child parser, those changes will not be reflected in the child.
formatter_class¶
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 objects allow the help formatting to be customized by specifying an alternate formatting class. Currently, there are four such classes:class argparse.RawDescriptionHelpFormatter¶class argparse.RawTextHelpFormatter¶class argparse.ArgumentDefaultsHelpFormatter¶class argparse.MetavarTypeHelpFormatter¶
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag94 and
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag95 give more control over how textual descriptions are displayed. By default,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 objects line-wrap the description and epilog texts in command-line help messages:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag9
Passing
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag94 as
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag98 indicates that description and epilog are already correctly formatted and should not be line-wrapped:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]0
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag95 maintains whitespace for all sorts of help text, including argument descriptions. However, multiple new lines are replaced with one. If you wish to preserve multiple blank lines, add spaces between the newlines.
args = parser.parse_args[] print[args.filename, args.count, args.verbose]00 automatically adds information about default values to each of the argument help messages:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]1
args = parser.parse_args[] print[args.filename, args.count, args.verbose]01 uses the name of the type argument for each argument as the display name for its values [rather than using the dest as the regular formatter does]:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]2
prefix_chars¶
Most command-line options will use
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 as the prefix, e.g.
args = parser.parse_args[] print[args.filename, args.count, args.verbose]03. Parsers that need to support different or additional prefix characters, e.g. for options like
args = parser.parse_args[] print[args.filename, args.count, args.verbose]04 or
args = parser.parse_args[] print[args.filename, args.count, args.verbose]05, may specify them using the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]06 argument to the ArgumentParser constructor:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]3
The
args = parser.parse_args[] print[args.filename, args.count, args.verbose]06 argument defaults to
args = parser.parse_args[] print[args.filename, args.count, args.verbose]08. Supplying a set of characters that does not include
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 will cause
args = parser.parse_args[] print[args.filename, args.count, args.verbose]03 options to be disallowed.
fromfile_prefix_chars¶
Sometimes, when dealing with a particularly long argument list, it may make sense to keep the list of arguments in a file rather than typing it out at the command line. If the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]11 argument is given to the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 constructor, then arguments that start with any of the specified characters will be treated as files, and will be replaced by the arguments they contain. For example:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]4
Arguments read from a file must by default be one per line [but see also
args = parser.parse_args[] print[args.filename, args.count, args.verbose]13] and are treated as if they were in the same place as the original file referencing argument on the command line. So in the example above, the expression
args = parser.parse_args[] print[args.filename, args.count, args.verbose]14 is considered equivalent to the expression
args = parser.parse_args[] print[args.filename, args.count, args.verbose]15.
The
args = parser.parse_args[] print[args.filename, args.count, args.verbose]11 argument defaults to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag22, meaning that arguments will never be treated as file references.
argument_default¶
Generally, argument defaults are specified either by passing a default to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38 or by calling the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]19 methods with a specific set of name-value pairs. Sometimes however, it may be useful to specify a single parser-wide default for arguments. This can be accomplished by passing the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]20 keyword argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35. For example, to globally suppress attribute creation on
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 calls, we supply
args = parser.parse_args[] print[args.filename, args.count, args.verbose]23:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]5
allow_abbrev¶
Normally, when you pass an argument list to the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 method of an
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35, it recognizes abbreviations of long options.
This feature can be disabled by setting
args = parser.parse_args[] print[args.filename, args.count, args.verbose]26 to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]6
New in version 3.5.
conflict_handler¶
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 objects do not allow two actions with the same option string. By default,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 objects raise an exception if an attempt is made to create an argument with an option string that is already in use:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]7
Sometimes [e.g. when using parents] it may be useful to simply override any older arguments with the same option string. To get this behavior, the value
args = parser.parse_args[] print[args.filename, args.count, args.verbose]30 can be supplied to the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]31 argument of
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]8
Note that
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 objects only remove an action if all of its option strings are overridden. So, in the example above, the old
args = parser.parse_args[] print[args.filename, args.count, args.verbose]03 action is retained as the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]35 action, because only the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]36 option string was overridden.
add_help¶
By default, ArgumentParser objects add an option which simply displays the parser’s help message. For example, consider a file named
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag68 containing the following code:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag0
If
args = parser.parse_args[] print[args.filename, args.count, args.verbose]38 or
args = parser.parse_args[] print[args.filename, args.count, args.verbose]39 is supplied at the command line, the ArgumentParser help will be printed:
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]]0
Occasionally, it may be useful to disable the addition of this help option. This can be achieved by passing
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29 as the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]41 argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35:
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]]1
The help option is typically
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag60. The exception to this is if the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]06 is specified and does not include
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02, in which case
args = parser.parse_args[] print[args.filename, args.count, args.verbose]38 and
args = parser.parse_args[] print[args.filename, args.count, args.verbose]39 are not valid options. In this case, the first character in
args = parser.parse_args[] print[args.filename, args.count, args.verbose]48 is used to prefix the help options:
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]]2
exit_on_error¶
Normally, when you pass an invalid argument list to the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 method of an
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35, it will exit with error info.
If the user would like to catch errors manually, the feature can be enabled by setting
args = parser.parse_args[] print[args.filename, args.count, args.verbose]51 to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29:
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]]3
New in version 3.9.
The add_argument[] method¶
ArgumentParser.add_argument[name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]]¶Define how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are:
name or flags - Either a name or a list of option strings, e.g.
args = parser.parse_args[] print[args.filename, args.count, args.verbose]
53 orargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
54.action - The basic type of action to be taken when this argument is encountered at the command line.
nargs - The number of command-line arguments that should be consumed.
const - A constant value required by some action and nargs selections.
default - The value produced if the argument is absent from the command line and if it is absent from the namespace object.
type - The type to which the command-line argument should be converted.
choices - A container of the allowable values for the argument.
required - Whether or not the command-line option may be omitted [optionals only].
help - A brief description of what the argument does.
metavar - A name for the argument in usage messages.
dest - The name of the attribute to be added to the object returned by
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
40.
The following sections describe how each of these are used.
name or flags¶
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38 method must know whether an optional argument, like
args = parser.parse_args[] print[args.filename, args.count, args.verbose]35 or
args = parser.parse_args[] print[args.filename, args.count, args.verbose]36, or a positional argument, like a list of filenames, is expected. The first arguments passed to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38 must therefore be either a series of flags, or a simple argument name.
For example, an optional argument could be created like:
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]]4
while a positional argument could be created like:
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]]5
When
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 is called, optional arguments will be identified by the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 prefix, and the remaining arguments will be assumed to be positional:
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]]6
action¶
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40. The
args = parser.parse_args[] print[args.filename, args.count, args.verbose]64 keyword argument specifies how the command-line arguments should be handled. The supplied actions are:
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
11 - This just stores the argument’s value. This is the default action. For example: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]]
7parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
12 - This stores the value specified by the const keyword argument; note that the const keyword argument defaults toparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22. Theparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
12 action is most commonly used with optional arguments that specify some sort of flag. For example: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]]
8parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
13 andargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
70 - These are special cases ofparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
12 used for storing the valuesparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
28 andparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
29 respectively. In addition, they create default values ofparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
29 andparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
28 respectively. For example: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]]
9parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
14 - This stores a list, and appends each argument value to the list. It is useful to allow an option to be specified multiple times. If the default value is non-empty, the default elements will be present in the parsed value for the option, with any values from the command line appended after those default values. Example usage:$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
0parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
15 - This stores a list, and appends the value specified by the const keyword argument to the list; note that the const keyword argument defaults toparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22. Theparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
15 action is typically useful when multiple arguments need to store constants to the same list. For example:$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
1parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
16 - This counts the number of times a keyword argument occurs. For example, this is useful for increasing verbosity levels:$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
2Note, the default will be
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22 unless explicitly set to 0.parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
17 - This prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. Seeparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
35 for details of how the output is created.parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
18 - This expects aargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
85 keyword argument in theparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
38 call, and prints version information and exits when invoked:$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
3args = parser.parse_args[] print[args.filename, args.count, args.verbose]
87 - This stores a list, and extends each argument value to the list. Example usage:$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
4New in version 3.8.
You may also specify an arbitrary action by passing an Action subclass or other object that implements the same interface. The
args = parser.parse_args[] print[args.filename, args.count, args.verbose]88 is available in
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 and adds support for boolean actions such as
args = parser.parse_args[] print[args.filename, args.count, args.verbose]36 and
args = parser.parse_args[] print[args.filename, args.count, args.verbose]91:
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]5
New in version 3.9.
The recommended way to create a custom action is to extend
args = parser.parse_args[] print[args.filename, args.count, args.verbose]92, overriding the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]93 method and optionally the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]94 and
args = parser.parse_args[] print[args.filename, args.count, args.verbose]95 methods.
An example of a custom action:
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]6
For more details, see
args = parser.parse_args[] print[args.filename, args.count, args.verbose]92.
nargs¶
ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The
args = parser.parse_args[] print[args.filename, args.count, args.verbose]97 keyword argument associates a different number of command-line arguments with a single action. The supported values are:
args = parser.parse_args[] print[args.filename, args.count, args.verbose]
98 [an integer].args = parser.parse_args[] print[args.filename, args.count, args.verbose]
98 arguments from the command line will be gathered together into a list. For example:$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
7Note that
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]]
00 produces a list of one item. This is different from the default, in which the item is produced by itself.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
24. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. Note that for optional arguments, there is an additional case - the option string is present but not followed by a command-line argument. In this case the value from const will be produced. Some examples to illustrate this:$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
8One of the more common uses of
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]]
02 is to allow optional input and output files:$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
9
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
25. All command-line arguments present are gathered into a list. Note that it generally doesn’t make much sense to have more than one positional argument withimport 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]]
04, but multiple optional arguments withimport 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]]
04 is possible. For example:$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
0
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
26. Just likeparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
25, all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present. For example:$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
1
If the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]97 keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item [not a list] will be produced.
const¶
The
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]]09 argument of
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38 is used to hold constant values that are not read from the command line but are required for the various
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 actions. The two most common uses of it are:
When
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
38 is called withimport 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]]
13 orimport 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]]
14. These actions add theimport 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]]
09 value to one of the attributes of the object returned byparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
40. See the action description for examples. Ifimport 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]]
09 is not provided toparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
38, it will receive a default value ofparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22.When
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
38 is called with option strings [likeargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
35 orargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
36] andimport 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]]
02. This creates an optional argument that can be followed by zero or one command-line arguments. When parsing the command line, if the option string is encountered with no command-line argument following it, the value ofimport 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]]
09 will be assumed to beparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22 instead. See the nargs description for examples.
Changed in version 3.11:
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]]26 by default, including when
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]]14 or
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]]13.
default¶
All optional arguments and some positional arguments may be omitted at the command line. The
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]]29 keyword argument of
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38, whose value defaults to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag22, specifies what value should be used if the command-line argument is not present. For optional arguments, the
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]]29 value is used when the option string was not present at the command line:
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 102
If the target namespace already has an attribute set, the action default will not over write it:
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 103
If the
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]]29 value is a string, the parser parses the value as if it were a command-line argument. In particular, the parser applies any type conversion argument, if provided, before setting the attribute on the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag51 return value. Otherwise, the parser uses the value as is:
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 104
For positional arguments with nargs equal to
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]]35 or
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]]36, the
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]]29 value is used when no command-line argument was present:
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 105
Providing
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]]38 causes no attribute to be added if the command-line argument was not present:
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 106
type¶
By default, the parser reads command-line arguments in as simple strings. However, quite often the command-line string should instead be interpreted as another type, such as a
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag31 or
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag23. The
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]]41 keyword for
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38 allows any necessary type-checking and type conversions to be performed.
If the type keyword is used with the default keyword, the type converter is only applied if the default is a string.
The argument to
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]]41 can be any callable that accepts a single string. If the function raises
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]]44,
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]]45, or
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]]46, the exception is caught and a nicely formatted error message is displayed. No other exception types are handled.
Common built-in types and functions can be used as type converters:
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 107
User defined functions can be used as well:
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 108
The
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]]47 function is not recommended as a type converter. All it does is convert empty strings to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29 and non-empty strings to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag28. This is usually not what is desired.
In general, the
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]]41 keyword is a convenience that should only be used for simple conversions that can only raise one of the three supported exceptions. Anything with more interesting error-handling or resource management should be done downstream after the arguments are parsed.
For example, JSON or YAML conversions have complex error cases that require better reporting than can be given by the
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]]41 keyword. A
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]]52 would not be well formatted and a
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]]53 exception would not be handled at all.
Even
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]]54 has its limitations for use with the
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]]41 keyword. If one argument uses FileType and then a subsequent argument fails, an error is reported but the file is not automatically closed. In this case, it would be better to wait until after the parser has run and then use the
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]]56-statement to manage the files.
For type checkers that simply check against a fixed set of values, consider using the choices keyword instead.
choices¶
Some command-line arguments should be selected from a restricted set of values. These can be handled by passing a container object as the choices keyword argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38. When the command line is parsed, argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values:
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 109
Note that inclusion in the choices container is checked after any type conversions have been performed, so the type of the objects in the choices container should match the type specified:
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'0
Any container can be passed as the choices value, so
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]]58 objects,
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]]59 objects, and custom containers are all supported.
Use of
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]]60 is not recommended because it is difficult to control its appearance in usage, help, and error messages.
Formatted choices override the default metavar which is normally derived from dest. This is usually what you want because the user never sees the dest parameter. If this display isn’t desirable [perhaps because there are many choices], just specify an explicit metavar.
required¶
In general, the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 module assumes that flags like
args = parser.parse_args[] print[args.filename, args.count, args.verbose]35 and
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]]63 indicate optional arguments, which can always be omitted at the command line. To make an option required,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag28 can be specified for the
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]]65 keyword argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38:
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'1
As the example shows, if an option is marked as
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]]67,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 will report an error if that option is not present at the command line.
Note
Required options are generally considered bad form because users expect options to be optional, and thus they should be avoided when possible.
help¶
The
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]]69 value is a string containing a brief description of the argument. When a user requests help [usually by using
args = parser.parse_args[] print[args.filename, args.count, args.verbose]38 or
args = parser.parse_args[] print[args.filename, args.count, args.verbose]39 at the command line], these
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]]69 descriptions will be displayed with each argument:
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'2
The
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]]69 strings can include various format specifiers to avoid repetition of things like the program name or the argument default. The available specifiers include the program name,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag74 and most keyword arguments to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38, e.g.
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]]76,
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]]77, etc.:
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'3
As the help string supports %-formatting, if you want a literal
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]]78 to appear in the help string, you must escape it as
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]]79.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 supports silencing the help entry for certain options, by setting the
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]]69 value to
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]]82:
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'4
metavar¶
When
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 generates help messages, it needs some way to refer to each expected argument. By default, ArgumentParser objects use the dest value as the “name” of each object. By default, for positional argument actions, the dest value is used directly, and for optional argument actions, the dest value is uppercased. So, a single positional argument with
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]]84 will be referred to as
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]]85. A single optional argument
args = parser.parse_args[] print[args.filename, args.count, args.verbose]36 that should be followed by a single command-line argument will be referred to as
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]]87. An example:
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'5
An alternative name can be specified with
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]]88:
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'6
Note that
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]]88 only changes the displayed name - the name of the attribute on the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 object is still determined by the dest value.
Different values of
args = parser.parse_args[] print[args.filename, args.count, args.verbose]97 may cause the metavar to be used multiple times. Providing a tuple to
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]]88 specifies a different display for each of the arguments:
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'7
dest¶
Most
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 actions add some value as an attribute of the object returned by
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40. The name of this attribute is determined by the
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]]95 keyword argument of
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38. For positional argument actions,
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]]95 is normally supplied as the first argument to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38:
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'8
For optional argument actions, the value of
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]]95 is normally inferred from the option strings.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 generates the value of
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]]95 by taking the first long option string and stripping away the initial
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]02 string. If no long option strings were supplied,
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]]95 will be derived from the first short option string by stripping the initial
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 character. Any internal
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 characters will be converted to
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]06 characters to make sure the string is a valid attribute name. The examples below illustrate this behavior:
$ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'9
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]]95 allows a custom attribute name to be provided:
>>> parser = argparse.ArgumentParser[description='Process some integers.']0
Action classes¶
Action classes implement the Action API, a callable which returns a callable which processes arguments from the command-line. Any object which follows this API may be passed as the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]64 parameter to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38.class argparse.Action[option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None]¶
Action objects are used by an ArgumentParser to represent the information needed to parse a single argument from one or more strings from the command line. The Action class must accept the two positional arguments plus any keyword arguments passed to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag08 except for the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]64 itself.
Instances of Action [or return value of any callable to the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]64 parameter] should have attributes “dest”, “option_strings”, “default”, “type”, “required”, “help”, etc. defined. The easiest way to ensure these attributes are defined is to call
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]13.
Action instances should be callable, so subclasses must override the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]93 method, which should accept four parameters:
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
15 - The ArgumentParser object which contains this action.$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
16 - Theparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
51 object that will be returned byparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
40. Most actions add an attribute to this object using$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
19.$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
20 - The associated command-line arguments, with any type conversions applied. Type conversions are specified with the type keyword argument toparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
38.$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
22 - The option string that was used to invoke this action. The$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]
22 argument is optional, and will be absent if the action is associated with a positional argument.
The
args = parser.parse_args[] print[args.filename, args.count, args.verbose]93 method may perform arbitrary actions, but will typically set attributes on the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]16 based on
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]]95 and
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]20.
Action subclasses can define a
args = parser.parse_args[] print[args.filename, args.count, args.verbose]95 method that takes no argument and return a string which will be used when printing the usage of the program. If such method is not provided, a sensible default will be used.
The parse_args[] method¶
ArgumentParser.parse_args[args=None, namespace=None]¶Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace.
Previous calls to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38 determine exactly what objects are created and how they are assigned. See the documentation for
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38 for details.
args - List of strings to parse. The default is taken from
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
04.namespace - An object to take the attributes. The default is a new empty
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
51 object.
Option value syntax¶
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 method supports several ways of specifying the value of an option [if it takes one]. In the simplest case, the option and its value are passed as two separate arguments:
>>> parser = argparse.ArgumentParser[description='Process some integers.']1
For long options [options with names longer than a single character], the option and value can also be passed as a single command-line argument, using
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]34 to separate them:
>>> parser = argparse.ArgumentParser[description='Process some integers.']2
For short options [options only one character long], the option and its value can be concatenated:
>>> parser = argparse.ArgumentParser[description='Process some integers.']3
Several short options can be joined together, using only a single
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 prefix, as long as only the last option [or none of them] requires a value:
>>> parser = argparse.ArgumentParser[description='Process some integers.']4
Invalid arguments¶
While parsing the command line,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 checks for a variety of errors, including ambiguous options, invalid types, invalid options, wrong number of positional arguments, etc. When it encounters such an error, it exits and prints the error along with a usage message:
>>> parser = argparse.ArgumentParser[description='Process some integers.']5
Arguments containing args = parser.parse_args[]
print[args.filename, args.count, args.verbose]
02¶
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 method attempts to give errors whenever the user has clearly made a mistake, but some situations are inherently ambiguous. For example, the command-line argument
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]39 could either be an attempt to specify an option or an attempt to provide a positional argument. The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 method is cautious here: positional arguments may only begin with
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 if they look like negative numbers and there are no options in the parser that look like negative numbers:
>>> parser = argparse.ArgumentParser[description='Process some integers.']6
If you have positional arguments that must begin with
args = parser.parse_args[] print[args.filename, args.count, args.verbose]02 and don’t look like negative numbers, you can insert the pseudo-argument
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]43 which tells
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 that everything after that is a positional argument:
>>> parser = argparse.ArgumentParser[description='Process some integers.']7
Argument abbreviations [prefix matching]¶
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 method by default allows long options to be abbreviated to a prefix, if the abbreviation is unambiguous [the prefix matches a unique option]:
>>> parser = argparse.ArgumentParser[description='Process some integers.']8
An error is produced for arguments that could produce more than one options. This feature can be disabled by setting allow_abbrev to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag29.
Beyond parser.add_argument['filename'] # positional argument
parser.add_argument['-c', '--count'] # option that takes a value
parser.add_argument['-v', '--verbose',
action='store_true'] # on/off flag
04¶
Sometimes it may be useful to have an ArgumentParser parse arguments other than those of
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag04. This can be accomplished by passing a list of strings to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40. This is useful for testing at the interactive prompt:
>>> parser = argparse.ArgumentParser[description='Process some integers.']9
The Namespace object¶
class argparse.Namespace¶Simple class used by default by
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 to create an object holding attributes and return it.
This class is deliberately simple, just an
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]51 subclass with a readable string representation. If you prefer to have dict-like view of the attributes, you can use the standard Python idiom,
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]52:
>>> 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]']0
It may also be useful to have an
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 assign attributes to an already existing object, rather than a new
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag51 object. This can be achieved by specifying the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]55 keyword argument:
>>> 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]']1
Other utilities¶
Sub-commands¶
ArgumentParser.add_subparsers[[title][, description][, prog][, parser_class][, action][, option_strings][, dest][, required][, help][, metavar]]¶Many programs split up their functionality into a number of sub-commands, for example, the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]56 program can invoke sub-commands like
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]57,
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]58, and
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]59. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 supports the creation of such sub-commands with the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]61 method. The
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]61 method is normally called with no arguments and returns a special action object. This object has a single method,
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]63, which takes a command name and any
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 constructor arguments, and returns an
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 object that can be modified as usual.
Description of parameters:
title - title for the sub-parser group in help output; by default “subcommands” if description is provided, otherwise uses title for positional arguments
description - description for the sub-parser group in help output, by default
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22prog - usage information that will be displayed with sub-command help, by default the name of the program and any positional arguments before the subparser argument
parser_class - class which will be used to create sub-parser instances, by default the class of the current parser [e.g. ArgumentParser]
action - the basic type of action to be taken when this argument is encountered at the command line
dest - name of the attribute under which sub-command name will be stored; by default
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22 and no value is storedrequired - Whether or not a subcommand must be provided, by default
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
29 [added in 3.7]help - help for sub-parser group in help output, by default
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22metavar - string presenting available sub-commands in help; by default it is
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
22 and presents sub-commands in form {cmd1, cmd2, ..}
Some example usage:
>>> 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]']2
Note that the object returned by
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 will only contain attributes for the main parser and the subparser that was selected by the command line [and not any other subparsers]. So in the example above, when the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]72 command is specified, only the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]53 and
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]]85 attributes are present, and when the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]75 command is specified, only the
args = parser.parse_args[] print[args.filename, args.count, args.verbose]53 and
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]77 attributes are present.
Similarly, when a help message is requested from a subparser, only the help for that particular parser will be printed. The help message will not include parent parser or sibling parser messages. [A help message for each subparser command, however, can be given by supplying the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]78 argument to
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]63 as above.]
>>> 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]']3
The
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]61 method also supports
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]81 and
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]82 keyword arguments. When either is present, the subparser’s commands will appear in their own group in the help output. 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]']4
Furthermore,
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]83 supports an additional
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]84 argument, which allows multiple strings to refer to the same subparser. This example, like
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]56, aliases
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]86 as a shorthand for
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]87:
>>> 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]']5
One particularly effective way of handling sub-commands is to combine the use of the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]61 method with calls to
args = parser.parse_args[] print[args.filename, args.count, args.verbose]19 so that each subparser knows which Python function it should execute. 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]']6
This way, you can let
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 do the job of calling the appropriate function after argument parsing is complete. Associating functions with actions like this is typically the easiest way to handle the different actions for each of your subparsers. However, if it is necessary to check the name of the subparser that was invoked, the
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]]95 keyword argument to the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]61 call will work:
>>> 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]']7
Changed in version 3.7: New required keyword argument.
FileType objects¶
class argparse.FileType[mode='r', bufsize=- 1, encoding=None, errors=None]¶The
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]]54 factory creates objects that can be passed to the type argument of
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag08. Arguments that have
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]]54 objects as their type will open command-line arguments as files with the requested modes, buffer sizes, encodings and error handling [see the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]96 function for more details]:
>>> 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]']8
FileType objects understand the pseudo-argument
args = parser.parse_args[] print[args.filename, args.count, args.verbose]08 and automatically convert this into
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]98 for readable
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]]54 objects and
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1000 for writable
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]]54 objects:
>>> 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]']9
New in version 3.4: The encodings and errors keyword arguments.
Argument groups¶
ArgumentParser.add_argument_group[title=None, description=None]¶By default,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 groups command-line arguments into “positional arguments” and “options” when displaying help messages. When there is a better conceptual grouping of arguments than this default one, appropriate groups can be created using the
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1003 method:
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]0
The
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1003 method returns an argument group object which has an
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38 method just like a regular
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35. When an argument is added to the group, the parser treats it just like a normal argument, but displays the argument in a separate group for help messages. The
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1003 method accepts title and description arguments which can be used to customize this display:
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]1
Note that any arguments not in your user-defined groups will end up back in the usual “positional arguments” and “optional arguments” sections.
Changed in version 3.11: Calling
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1003 on an argument group is deprecated. This feature was never supported and does not always work correctly. The function exists on the API by accident through inheritance and will be removed in the future.
Mutual exclusion¶
ArgumentParser.add_mutually_exclusive_group[required=False]¶Create a mutually exclusive group.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 will make sure that only one of the arguments in the mutually exclusive group was present on the command line:
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]2
The
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1010 method also accepts a required argument, to indicate that at least one of the mutually exclusive arguments is required:
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]3
Note that currently mutually exclusive argument groups do not support the title and description arguments of
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1003.
Changed in version 3.11: Calling
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1003 or
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1010 on a mutually exclusive group is deprecated. These features were never supported and do not always work correctly. The functions exist on the API by accident through inheritance and will be removed in the future.
Parser defaults¶
ArgumentParser.set_defaults[**kwargs]¶Most of the time, the attributes of the object returned by
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 will be fully determined by inspecting the command-line arguments and the argument actions.
args = parser.parse_args[] print[args.filename, args.count, args.verbose]19 allows some additional attributes that are determined without any inspection of the command line to be added:
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]4
Note that parser-level defaults always override argument-level defaults:
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]5
Parser-level defaults can be particularly useful when working with multiple parsers. See the
$ python prog.py -h usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator options: -h, --help show this help message and exit --sum sum the integers [default: find the max]61 method for an example of this type.ArgumentParser.get_default[dest]¶
Get the default value for a namespace attribute, as set by either
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag38 or by
args = parser.parse_args[] print[args.filename, args.count, args.verbose]19:
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]6
Printing help¶
In most typical applications,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 will take care of formatting and printing any usage or error messages. However, several formatting methods are available:ArgumentParser.print_usage[file=None]¶
Print a brief description of how the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 should be invoked on the command line. If file is
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag22,
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1000 is assumed.ArgumentParser.print_help[file=None]¶
Print a help message, including the program usage and information about the arguments registered with the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35. If file is
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag22,
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1000 is assumed.
There are also variants of these methods that simply return a string instead of printing it:
ArgumentParser.format_usage[]¶Return a string containing a brief description of how the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 should be invoked on the command line.ArgumentParser.format_help[]¶
Return a string containing a help message, including the program usage and information about the arguments registered with the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35.
Partial parsing¶
ArgumentParser.parse_known_args[args=None, namespace=None]¶Sometimes a script may only parse a few of the command-line arguments, passing the remaining arguments on to another script or program. In these cases, the
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1028 method can be useful. It works much like
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag40 except that it does not produce an error when extra arguments are present. Instead, it returns a two item tuple containing the populated namespace and the list of remaining argument strings.
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]7
Warning
Prefix matching rules apply to
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1028. The parser may consume an option even if it’s just a prefix of one of its known options, instead of leaving it in the remaining arguments list.
Customizing file parsing¶
ArgumentParser.convert_arg_line_to_args[arg_line]¶Arguments that are read from a file [see the fromfile_prefix_chars keyword argument to the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag35 constructor] are read one argument per line.
args = parser.parse_args[] print[args.filename, args.count, args.verbose]13 can be overridden for fancier reading.
This method takes a single argument arg_line which is a string read from the argument file. It returns a list of arguments parsed from this string. The method is called once per line read from the argument file, in order.
A useful override of this method is one that treats each space-separated word as an argument. The following example demonstrates how to do this:
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]8
Exiting methods¶
ArgumentParser.exit[status=0, message=None]¶This method terminates the program, exiting with the specified status and, if given, it prints a message before that. The user can override this method to handle these steps differently:
>>> parser.parse_args[['--sum', '7', '-1', '42']] Namespace[accumulate=, integers=[7, -1, 42]]9ArgumentParser.error[message]¶
This method prints a usage message including the message to the standard error and terminates the program with a status code of 2.
Intermixed parsing¶
ArgumentParser.parse_intermixed_args[args=None, namespace=None]¶ArgumentParser.parse_known_intermixed_args[args=None, namespace=None]¶A number of Unix commands allow the user to intermix optional arguments with positional arguments. The
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1033 and
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1034 methods support this parsing style.
These parsers do not support all the argparse features, and will raise exceptions if unsupported features are used. In particular, subparsers,
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag27, and mutually exclusive groups that include both optionals and positionals are not supported.
The following example shows the difference between
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1028 and
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1033: the former returns
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1038 as unparsed arguments, while the latter collects all the positionals into
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1039.
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag00
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1034 returns a two item tuple containing the populated namespace and the list of remaining argument strings.
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1033 raises an error if there are any remaining unparsed argument strings.
New in version 3.7.
Upgrading optparse code¶
Originally, the
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 module had attempted to maintain compatibility with
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1043. However,
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1043 was difficult to extend transparently, particularly with the changes required to support the new
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1045 specifiers and better usage messages. When most everything in
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1043 had either been copy-pasted over or monkey-patched, it no longer seemed practical to try to maintain the backwards compatibility.
The
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01 module improves on the standard library
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1043 module in a number of ways including:
Handling positional arguments.
Supporting sub-commands.
Allowing alternative option prefixes like
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
49 and$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
50.Handling zero-or-more and one-or-more style arguments.
Producing more informative usage messages.
Providing a much simpler interface for custom
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]]
41 andargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
64.
A partial upgrade path from
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 1043 to
parser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag01:
Replace all
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
55 calls withparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
08 calls.Replace
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
57 with$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
58 and add additionalparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
08 calls for the positional arguments. Keep in mind that what was previously called$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
60, now in theparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
01 context is called$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
62.Replace
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
63 by using$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
33 instead ofparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
40.Replace callback actions and the
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
66 keyword arguments withimport 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]]
41 orargs = parser.parse_args[] print[args.filename, args.count, args.verbose]
64 arguments.Replace string names for
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]]
41 keyword arguments with the corresponding type objects [e.g. int, float, complex, etc].Replace
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
70 withparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
51 and$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
72 and$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
73 with$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
74.Replace strings with implicit arguments such as
$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
75 or$ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10
76 with the standard Python syntax to use dictionaries to format strings, that is,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]]
76 andparser.add_argument['filename'] # positional argument parser.add_argument['-c', '--count'] # option that takes a value parser.add_argument['-v', '--verbose', action='store_true'] # on/off flag
74.