Next / Previous / Contents / TCC Help System / NM Tech homepage

28.10.4. The ArgumentParser.add_argument() method

To define each command line argument, call the .add_argument() method of an ArgumentParser instance P. There are two forms, depending on whether you are defining a positional command line argument or an optional argument. In either case, there are a number of keyword arguments denoted as “**kw”; we will describe these arguments below.

To define a positional command line argument, use this form:

P.add_argument(posName, **kw)

The posName is a string that specifies the name of the argument (which cannot begin with “-”). For example, if your ArgumentParser instance is p, to define a positional argument called “inFile”, your call might begin like this:

p.add_argument("inFile", ...)

To define an optional command line argument, use this form:

P.add_argument(s0, s1, ..., , **kw)

Each si is a string defining the option name, starting with either "-" for short-form options or "--" for options with the long form.

For example, if you have an option whose short form is “-x” and whose long form is “--exec”, your method call would begin:

p.add_argument("-x", "--exec", ...)

You can specify any number of short and long form options in this way.

Here are the principle keyword arguments to the .add_argument() method. Some of these require information to be passed through other keyword arguments.

dest

Name of the attribute where the value of this argument will be stored in the result returned by the ArgumentParser.parse_args() method. If you don't specify this, the attribute name will be:

  • For positional arguments, the attribute name will be the name passed as the first argument to .add_argument().

  • For optional arguments, the attribute name is the first long-form option name given if there is at least one; otherwise the attribute name is the first short-form option name given.

    For example, if the method call looks like .add_argument('-x', '--exec', '--run', ...), the value will be stored in the .exec attribute of the result returned by .arg_parse().

action

Specifies what happens when this command line argument is processed. The value must be one of the following:

action='store'

Store the argument value as a string in the result returned by .arg_parse(). The name of the attribute where it is stored is given by the dest keyword argument, or the default name as explained above.

action='store_const'

You must provide a keyword argument const=V, where V is the value to be stored in the result returned from .arg_parse().

action='store_true'

Store a True value in the returned result. If the user does not supply this option, .parse_args() stores a False value in the returned result.

action='store_false'

Store a False value in the returned result. If the user doesn't supply this option, .parse_args() stores a True value in the returned result.

action='append'

For arguments that may be repeated, this action causes each repeated argument to be appended to the list of values in the result returned by .arg_parse() .

action='append_const'

This works like action='append', but the value V, specified elsewhere by const=V is appended to the list of arguments.

action='version'

This option instructs the ArgumentParser instance to implement a --version option that reports the current version of your script. You must provide a version=V argument that defines the version string as V.

If you don't supply an action argument, the default is action=None. In this case:

  • For positional command line arguments, the value of the argument is stored.

  • For optional command line arguments, the stored value is None, unless you provide a default=S argument to .add_argument().

nargs

Specifies the number of this kind of argument. This feature works for both positional and optional arguments. In the value returned by .parse_args(), the attribute associated with this argument will be a list, not a single value.

  • If the value of the nargs option is an integer, exactly that many arguments must be provided.

  • nargs='*' means zero or more. For positional arguments, this means all the remaining arguments supplied will be included in the returned list of values.

  • nargs='+' means one or more: there must be at least one such argument, but there may be any number.

  • nargs='?' means that this argument is optional.

    • For positional command line arguments, the returned value will be the value from the command line if there is one; otherwise you will supply the default returned value D by providing keyword argument default=D to the .add_argument() call.

    • For optional command line arguments, nargs='?' signifies that the option may be given a value.

      • If the user does not provide this option, the value returned by .arg_parse() will be the default value from the const=C argument to .add_argument().

      • If the user provides this option but does not follow it with a value, the value returned by .arg_parse() will be the default value from the default=D argument to .add_argument().

      • If the user provides this option with a value V, the attribute of the value returned by .arg_parse() will be V.

  • The default value is nargs=None. In this case:

    • For a positional command line argument, this means exactly one is expected.

    • For an optional command line argument, the stored value is None unless you provide a default value D with default=D.

const

See above under action='store_const' and action='append_const'.

default

Provides a default value; see above under nargs.

type

Convert the value to a given type. For example, type=int would attempt to convert the associated argument to a Python int; if the argument is not a valid integer, .arg_parse() will print the usage message and terminate.

For arguments that are file names, the argparse module will even open the file for you. Here is the general form:

type=argparse.FileType(mode=M)

where M is the mode string as in the second argument to open(). For example, this form would attempt to open a new file for writing, using the value of the command line option as the file name.

p.add_argument(..., type=argparse.FileType(mode='w'), ...)

Note that .arg_parse() may raise an IOError or OSError exception if the file can't be opened.

You can specify any converter function as the value of the type keyword argument. This function takes one argument, a string, and returns a value of whatever type you like. Your converter function may also raise an argparse.ArgumentTypeError exception to signify an invalid value.

choices

An iterable that specifies the only valid choices. For example, choices=('red', 'grn', 'blu') would allow only those three specific strings as values of the associated command line argument.

required

If an argument that starts with a hyphen is not actually optional, use required=True.

help

A string describing what this option does. Strongly recommended, and it will be displayed in the help message.

metavar

Specifies the name of this optional for external display. For example, suppose your .add_argument() call starts like this:

P.add_argument('inFile', metavar='INFILE', ...)

Then the argument value will be stored in attribute .inFile of the result returned by .arg_parse(), but the help message will refer to this argument as “INFILE”.