ArgumentParser, parsing for arguments

The add_argument() method defines 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. foo or -f, —foo.
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.
type — The type to which the command-line argument should be converted.
choices — A container of the allowable values for the arguments.
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 parse_args().
The following sections describe how each of these are used.

# -> name of flags <-

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.

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

# -> action <-

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.
’store_const’ — This stores the value specified by the const keyword argument. The ’store_const’ action is most commonly used with optional arguments that specify some sort of flag.
’store_true’ and ’store_false’ — These are special case of ’store_const’ used for storing the values True and False respectively. In addition, they create default values of False and True respectively.
’append’ — This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times.
’append_const’ — This store 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.
’count’ — This counts the number of times a keyword argument occurs. For example, this is useful for increasing verbosity levels.
’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.
’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.

# -> nargs <-

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.
Note the 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. One of the more common uses of nargs=‘?’ is to allow optional input and output files.
*. 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.
+. Just like *, all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least on command-line argument present.
argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities.
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.

# -> const <-

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().
When add_argument() is called with option string (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.
With the ’store_const’ and ’append_const’ actions, the const keyword argument must be given. For other actions, it defaults to None.

# -> default <-

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 string, the parser parses the value as if it were a command-line argument. In particular, the parser applies any type conversion argument, if provide, before setting the attribute on the Namespace return value. Otherwise, the parser uses the value as is.

For positional arguments with nargs equal to ? or *, the default value is used when no command-line argument was present.

Providing default=argparse.SUPPRESS cause no attribute to be added if the command-line argument was not present.

# -> type <-

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=, bufsize=, encoding= and errors= arguments of the open() function.

type= can take any callable that takes a single string argument and returns the converted value.

The choices keyword argument may be more convenient for type checkers that simply check against a range of values.

# -> choice <-

Some command-line arguments should be selected from a restricted set fo 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.

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.

Any object that supports the in operator can be passed as the choices value, so dict objects, set objects, custom containers, etc. are all supported.

# -> required <-

In general, the argparse module assume 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().

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 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.

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.

As the help string supports %-formatting, if you want a literal % to appear in the help string, you must escape it as %%.

argparse supports silencing the help entry for certain options, by setting the help value to argparse.SUPPRESS.

# -> metavar <-

When ArgumentParser generates help message, 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 alternative name can be specified with metavar.

Note that metavar only changes the displayed name - the name of the attribute on the parse_args() object is still determined by the dest value.

Different values of nargs may cause the metavar to be used multiple times, Providing a tuple to metavar specifies a different display for each of the arguments.

# -> dest <-

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 not 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.