This page contains the API reference information. For a more gentle
introduction to Python command-line parsing, have a look at the
argparse tutorial.

The argparse module makes it easy to write user-friendly command-line
interfaces. The program defines what arguments it requires, and argparse
will figure out how to parse those out of sys.argv. The argparse
module also automatically generates help and usage messages and issues errors
when users give the program invalid arguments.

The following code is a Python program that takes a list of integers and
produces either the sum or the max:

importargparseparser=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()printargs.accumulate(args.integers)

Assuming the Python code above is saved into a file called prog.py, it can
be run at the command line and provides useful help messages:

Filling an ArgumentParser with information about program arguments is
done by making calls to the add_argument() method.
Generally, these calls tell the ArgumentParser how to take the strings
on the command line and turn them into objects. This information is stored and
used when parse_args() is called. For example:

Later, calling parse_args() will return an object with
two attributes, integers and accumulate. The integers attribute
will be a list of one or more ints, and the accumulate attribute will be
either the sum() function, if --sum was specified at the command line,
or the max() function if it was not.

ArgumentParser parses arguments through the
parse_args() method. This will inspect the command line,
convert each argument to the appropriate type and then invoke the appropriate action.
In most cases, this means a simple Namespace object will be built up from
attributes parsed out of the command line:

By default, ArgumentParser objects uses sys.argv[0] 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
myprogram.py with the following code:

Note that the program name, whether determined from sys.argv[0] or from the
prog= argument, is available to help messages using the %(prog)s format
specifier.

>>> parser=argparse.ArgumentParser(prog='myprogram')>>> parser.add_argument('--foo',help='foo of the %(prog)s program')>>> parser.print_help()usage: myprogram [-h] [--foo FOO]optional arguments: -h, --help show this help message and exit --foo FOO foo of the myprogram program

Most calls to the ArgumentParser constructor will use the
description= 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=argparse.ArgumentParser(description='A foo that bars')>>> parser.print_help()usage: argparse.py [-h]A foo that barsoptional arguments: -h, --help show this help message and exit

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.

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 parents= argument to ArgumentParser
can be used. The parents= argument takes a list of ArgumentParser
objects, collects all the positional and optional actions from them, and adds
these actions to the ArgumentParser object being constructed:

>>> parser=argparse.ArgumentParser(... prog='PROG',... description='''this description... was indented weird... but that is okay''',... epilog='''... likewise for this epilog whose whitespace will... be cleaned up and whose words will be wrapped... across a couple lines''')>>> parser.print_help()usage: PROG [-h]this description was indented weird but that is okayoptional arguments: -h, --help show this help message and exitlikewise for this epilog whose whitespace will be cleaned up and whose wordswill be wrapped across a couple lines

>>> parser=argparse.ArgumentParser(... prog='PROG',... formatter_class=argparse.RawDescriptionHelpFormatter,... description=textwrap.dedent('''\... Please do not mess up this text!... --------------------------------... I have indented it... exactly the way... I want it... '''))>>> parser.print_help()usage: PROG [-h]Please do not mess up this text!-------------------------------- I have indented it exactly the way I want itoptional arguments: -h, --help show this help message and exit

RawTextHelpFormatter maintains whitespace for all sorts of help text,
including argument descriptions.

Most command-line options will use - as the prefix, e.g. -f/--foo.
Parsers that need to support different or additional prefix
characters, e.g. for options
like +f or /foo, may specify them using the prefix_chars= argument
to the ArgumentParser constructor:

Sometimes, for example when dealing with a particularly long argument lists, it
may make sense to keep the list of arguments in a file rather than typing it out
at the command line. If the fromfile_prefix_chars= argument is given to the
ArgumentParser 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:

Arguments read from a file must by default be one per line (but see also
convert_arg_line_to_args()) 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 ['-f','foo','@args.txt']
is considered equivalent to the expression ['-f','foo','-f','bar'].

The fromfile_prefix_chars= argument defaults to None, meaning that
arguments will never be treated as file references.

Generally, argument defaults are specified either by passing a default to
add_argument() or by calling the
set_defaults() 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
argument_default= keyword argument to ArgumentParser. For example,
to globally suppress attribute creation on parse_args()
calls, we supply argument_default=SUPPRESS:

ArgumentParser objects do not allow two actions with the same option
string. By default, ArgumentParser objects raises an exception if an
attempt is made to create an argument with an option string that is already in
use:

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
'resolve' can be supplied to the conflict_handler= argument of
ArgumentParser:

Note that ArgumentParser objects only remove an action if all of its
option strings are overridden. So, in the example above, the old -f/--foo
action is retained as the -f action, because only the --foo option
string was overridden.

The help option is typically -h/--help. The exception to this is
if the prefix_chars= is specified and does not include -, in
which case -h and --help are not valid options. In
this case, the first character in prefix_chars is used to prefix
the help options:

The add_argument() method must know whether an optional
argument, like -f or --foo, or a positional argument, like a list of
filenames, is expected. The first arguments passed to
add_argument() must therefore be either a series of
flags, or a simple argument name. For example, an optional argument could
be created like:

>>> parser.add_argument('-f','--foo')

while a positional argument could be created like:

>>> parser.add_argument('bar')

When parse_args() is called, optional arguments will be
identified by the - prefix, and the remaining arguments will be assumed to
be positional:

ArgumentParser 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
parse_args(). The action keyword argument specifies
how the command-line arguments should be handled. The supplied actions are:

'store' - This just stores the argument’s value. This is the default
action. For example:

'store_const' - This stores the value specified by the const keyword
argument. (Note that the const keyword argument defaults to the rather
unhelpful None.) The 'store_const' action is most commonly used with
optional arguments that specify some sort of flag. For example:

'store_true' and 'store_false' - These are special cases of
'store_const' using for storing the values True and False
respectively. In addition, they create default values of False and True
respectively. For example:

'append_const' - This stores a list, and appends the value specified by
the const keyword argument to the list. (Note that the const keyword
argument defaults to None.) The 'append_const' action is typically
useful when multiple arguments need to store constants to the same list. For
example:

'help' - 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. See ArgumentParser for details of how the
output is created.

'version' - This expects a version= keyword argument in the
add_argument() call, and prints version information
and exits when invoked:

You may also specify an arbitrary action by passing an Action subclass or
other object that implements the same interface. The recommended way to do
this is to extend Action, overriding the __call__ method
and optionally the __init__ method.

ArgumentParser objects usually associate a single command-line argument with a
single action to be taken. The nargs keyword argument associates a
different number of command-line arguments with a single action. The supported
values are:

N (an integer). N arguments from the command line will be gathered
together into a list. For example:

Note that nargs=1 produces a list of one item. This is different from
the default, in which the item is produced by itself.

'?'. 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:

'*'. 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
with nargs='*', but multiple optional arguments with nargs='*' is
possible. For example:

If the nargs 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.

The const argument of add_argument() is used to hold
constant values that are not read from the command line but are required for
the various ArgumentParser actions. The two most common uses of it are:

When add_argument() is called with
action='store_const' or action='append_const'. These actions add the
const value to one of the attributes of the object returned by
parse_args(). See the action description for examples.

When add_argument() is called with option strings
(like -f or --foo) and nargs='?'. 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 of const will be assumed instead.
See the nargs description for examples.

All optional arguments and some positional arguments may be omitted at the
command line. The default keyword argument of
add_argument(), whose value defaults to None,
specifies what value should be used if the command-line argument is not present.
For optional arguments, the default value is used when the option string
was not present at the command line:

If the default 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
Namespace return value. Otherwise, the parser uses the value as is:

By default, ArgumentParser objects read command-line arguments in as simple
strings. However, quite often the command-line string should instead be
interpreted as another type, like a float or int. The
type keyword argument of add_argument() allows any
necessary type-checking and type conversions to be performed. Common built-in
types and functions can be used directly as the value of the type argument:

See the section on the default keyword argument for information on when the
type argument is applied to default arguments.

To ease the use of various types of files, the argparse module provides the
factory FileType which takes the mode= and bufsize= arguments of the
file object. For example, FileType('w') can be used to create a
writable file:

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 add_argument(). 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:

In general, the argparse module assumes that flags like -f and --bar
indicate optional arguments, which can always be omitted at the command line.
To make an option required, True can be specified for the required=
keyword argument to add_argument():

The help value is a string containing a brief description of the argument.
When a user requests help (usually by using -h or --help at the
command line), these help descriptions will be displayed with each
argument:

>>> parser=argparse.ArgumentParser(prog='frobble')>>> parser.add_argument('--foo',action='store_true',... help='foo the bars before frobbling')>>> parser.add_argument('bar',nargs='+',... help='one of the bars to be frobbled')>>> parser.parse_args('-h'.split())usage: frobble [-h] [--foo] bar [bar ...]positional arguments: bar one of the bars to be frobbledoptional arguments: -h, --help show this help message and exit --foo foo the bars before frobbling

The help 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, %(prog)s and most keyword arguments to
add_argument(), e.g. %(default)s, %(type)s, etc.:

When ArgumentParser 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
dest='bar' will be referred to as bar. A single
optional argument --foo that should be followed by a single command-line argument
will be referred to as FOO. An example:

Most ArgumentParser actions add some value as an attribute of the
object returned by parse_args(). The name of this
attribute is determined by the dest keyword argument of
add_argument(). For positional argument actions,
dest is normally supplied as the first argument to
add_argument():

For optional argument actions, the value of dest is normally inferred from
the option strings. ArgumentParser generates the value of dest by
taking the first long option string and stripping away the initial --
string. If no long option strings were supplied, dest will be derived from
the first short option string by stripping the initial - character. Any
internal - characters will be converted to _ characters to make sure
the string is a valid attribute name. The examples below illustrate this
behavior:

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 action parameter to add_argument().

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 ArgumentParser.add_argument() except for the action itself.

Instances of Action (or return value of any callable to the action
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 Action.__init__.

Action instances should be callable, so subclasses must override the
__call__ method, which should accept four parameters:

While parsing the command line, parse_args() 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:

The parse_args() 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 -1 could either be an
attempt to specify an option or an attempt to provide a positional argument.
The parse_args() method is cautious here: positional
arguments may only begin with - if they look like negative numbers and
there are no options in the parser that look like negative numbers:

If you have positional arguments that must begin with - and don’t look
like negative numbers, you can insert the pseudo-argument '--' which tells
parse_args() that everything after that is a positional
argument:

Sometimes it may be useful to have an ArgumentParser parse arguments other than those
of sys.argv. This can be accomplished by passing a list of strings to
parse_args(). This is useful for testing at the
interactive prompt:

Many programs split up their functionality into a number of sub-commands,
for example, the svn program can invoke sub-commands like svncheckout, svnupdate, and svncommit. 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.
ArgumentParser supports the creation of such sub-commands with the
add_subparsers() method. The add_subparsers() method is normally
called with no arguments and returns a special action object. This object
has a single method, add_parser(), which takes a
command name and any ArgumentParser constructor arguments, and
returns an ArgumentParser 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 None

prog - 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 None and no value is stored

Note that the object returned by parse_args() 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 a command is specified, only the foo and bar attributes are
present, and when the b command is specified, only the foo and
baz 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 help= argument
to add_parser() as above.)

One particularly effective way of handling sub-commands is to combine the use
of the add_subparsers() method with calls to set_defaults() so
that each subparser knows which Python function it should execute. For
example:

This way, you can let parse_args() 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 dest keyword
argument to the add_subparsers() call will work:

The FileType factory creates objects that can be passed to the type
argument of ArgumentParser.add_argument(). Arguments that have
FileType objects as their type will open command-line arguments as files
with the requested modes and buffer sizes:

By default, ArgumentParser groups command-line arguments into
“positional arguments” and “optional arguments” when displaying help
messages. When there is a better conceptual grouping of arguments than this
default one, appropriate groups can be created using the
add_argument_group() method:

The add_argument_group() method returns an argument group object which
has an add_argument() method just like a regular
ArgumentParser. 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 add_argument_group() method
accepts title and description arguments which can be used to
customize this display:

Most of the time, the attributes of the object returned by parse_args()
will be fully determined by inspecting the command-line arguments and the argument
actions. set_defaults() allows some additional
attributes that are determined without any inspection of the command line to
be added:

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
parse_known_args() method can be useful. It works much like
parse_args() 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.

Arguments that are read from a file (see the fromfile_prefix_chars
keyword argument to the ArgumentParser constructor) are read one
argument per line. convert_arg_line_to_args() can be overriden 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:

Originally, the argparse module had attempted to maintain compatibility
with optparse. However, optparse was difficult to extend
transparently, particularly with the changes required to support the new
nargs= specifiers and better usage messages. When most everything in
optparse had either been copy-pasted over or monkey-patched, it no
longer seemed practical to try to maintain the backwards compatibility.

The argparse module improves on the standard library optparse
module in a number of ways including:

Replace (options,args)=parser.parse_args() with args=parser.parse_args() and add additional ArgumentParser.add_argument()
calls for the positional arguments. Keep in mind that what was previously
called options, now in argparse context is called args.

Replace callback actions and the callback_* keyword arguments with
type or action arguments.