The add_argument() method needs to know whether you’re expecting an optional argument, e.g. -f or --foo, or a positional argument, e.g. a list of filenames. 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 args with actions. These actions can do just about anything with the command-line args associated with them, though most actions simply add an attribute to the object returned by parse_args(). When you specify a new argument using the add_argument() method, you can indicate how the command-line args should be handled by specifying the action keyword argument. The supported 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 None, so you’ll almost always need to provide a value for it. The 'store_const' action is most commonly used with optional arguments that specify some sort of flag. 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, so you’ll almost always need to provide a value for it. The 'append_const' action is typically useful when you want multiple arguments to store constants to the same list, for example:

You can also specify an arbitrary action by passing an object that implements the Action API. The easiest way to do this is to extend argparse.Action, supplying an appropriate __call__ method. The __call__ method accepts four parameters:

parser - The ArgumentParser object which contains this action.

namespace - The namespace object that will be returned by parse_args(). Most actions add an attribute to this object.

values - The associated command-line args, with any type-conversions applied. (Type-conversions are specified with the type keyword argument to add_argument().

option_string - The option string that was used to invoke this action. The option_string argument is optional, and will be absent if the action is associated with a positional argument.

ArgumentParser objects usually associate a single command-line argument with a single action to be taken. In the situations where you’d like to associate a different number of command-line arguments with a single action, you can use the nargs keyword argument to add_argument(). The supported values are:

N (an integer). N args 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 arg will be consumed from the command-line if possible, and produced as a single item. If no command-line arg 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 arg. In this case the value from const will be produced. Some examples to illustrate this:

'*'. All command-line args 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 args consumed is determined by the action. Generally this means a single command-line arg 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 args. When parsing the command-line, if the option string is encountered with no command-line arg 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 arg is not present. For optional arguments, the default value is used when the option string was not present at the command line:

By default, ArgumentParser objects read command-line args in as simple strings. However, quite often the command-line string should instead be interpreted as another type, e.g. float, int or file. The type keyword argument of add_argument() allows any necessary type-checking and type-conversions to be performed. Many common builtin types can be used directly as the value of the type argument:

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:

If you need to do some special type-checking or type-conversions, you can provide your own types by passing to type= a callable that takes a single string argument and returns the type-converted value:

Some command-line args should be selected from a restricted set of values. ArgumentParser objects can be told about such sets of values by passing a container object as the choices keyword argument to add_argument(). When the command-line is parsed with parse_args(), arg values will be checked, and an error message will be displayed if the arg 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 change this behavior, i.e. to make an option required, the value True should be specified for the required= keyword argument to add_argument():

A great command-line interface isn’t worth anything if your users can’t figure out which option does what. So for the end-users, help is probably the most important argument to include in your add_argument() calls. The help value should be a string containing a brief description of what the argument specifies. 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 objects generate help messages, they need 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 if we have a single positional argument with dest='bar', that argument will be referred to as bar. And if we have a single optional argument --foo that should be followed by a single command-line arg, that arg will be referred to as FOO. You can see this behavior in the example below:

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 objects generate 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: