Argparse.rst
Argparse.rst
===============================================================================
.. module:: argparse
:synopsis: Command-line option and argument parsing library.
.. versionadded:: 3.2
--------------
.. sidebar:: Tutorial
This page contains the API reference information. For a more gentle
introduction to Python command-line parsing, have a look at the
:ref:`argparse tutorial <argparse-tutorial>`.
Core Functionality
------------------
parser = argparse.ArgumentParser(
prog='ProgramName',
description='What the program does',
epilog='Text at the bottom of help')
args = parser.parse_args()
print(args.filename, args.count, args.verbose)
Example
-------
The following code is a Python program that takes a list of integers and
produces either the sum or the max::
import argparse
args = parser.parse_args()
print(args.accumulate(args.integers))
Assuming the above Python code is saved into a file called ``prog.py``, it can
be run at the command line and it provides useful help messages:
.. code-block:: shell-session
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]
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:
.. code-block:: shell-session
$ python prog.py 1 2 3 4
4
.. code-block:: shell-session
$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'
Creating a parser
^^^^^^^^^^^^^^^^^
Adding arguments
^^^^^^^^^^^^^^^^
Parsing arguments
^^^^^^^^^^^^^^^^^
ArgumentParser objects
----------------------
* usage_ - The string describing the program usage (default: generated from
arguments added to parser)
* epilog_ - Text to display after the argument help (by default, no text)
.. versionchanged:: 3.5
*allow_abbrev* parameter was added.
.. versionchanged:: 3.8
In previous versions, *allow_abbrev* also disabled grouping of short
flags such as ``-vv`` to mean ``-v -v``.
.. versionchanged:: 3.9
*exit_on_error* parameter was added.
.. _prog:
prog
^^^^
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()
The help for this program will display ``myprogram.py`` as the program name
(regardless of where the program was invoked from):
.. code-block:: shell-session
options:
-h, --help show this help message and exit
--foo FOO foo help
$ cd ..
$ python subdir/myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]
options:
-h, --help show this help message and exit
--foo FOO foo help
To change this default behavior, another value can be supplied using the
``prog=`` argument to :class:`ArgumentParser`::
options:
-h, --help show this help message and exit
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.
::
options:
-h, --help show this help message and exit
--foo FOO foo of the myprogram program
usage
^^^^^
positional arguments:
bar bar help
options:
-h, --help show this help message and exit
--foo [FOO] foo help
The default message can be overridden with the ``usage=`` keyword argument::
options:
-h, --help show this help message and exit
--foo [FOO] foo help
.. _description:
description
^^^^^^^^^^^
options:
-h, --help show this help message and exit
epilog
^^^^^^
Some programs like to display additional description of the program after the
description of the arguments. Such text can be specified using the ``epilog=``
argument to :class:`ArgumentParser`::
options:
-h, --help show this help message and exit
Note that most parent parsers will specify ``add_help=False``. Otherwise, the
:class:`ArgumentParser` will see two ``-h/--help`` 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 ``parents=``.
If you change the parent parsers after the child parser, those changes will
not be reflected in the child.
.. _formatter_class:
formatter_class
^^^^^^^^^^^^^^^
.. class:: RawDescriptionHelpFormatter
RawTextHelpFormatter
ArgumentDefaultsHelpFormatter
MetavarTypeHelpFormatter
options:
-h, --help show this help message and exit
likewise for this epilog whose whitespace will be cleaned up and whose words
will be wrapped across a couple lines
options:
-h, --help show this help message and exit
positional arguments:
bar BAR! (default: [1, 2, 3])
options:
-h, --help show this help message and exit
--foo FOO FOO! (default: 42)
positional arguments:
float
options:
-h, --help show this help message and exit
--foo int
prefix_chars
^^^^^^^^^^^^
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::
fromfile_prefix_chars
^^^^^^^^^^^^^^^^^^^^^
Arguments read from a file must by default be one per line (but see also
:meth:`~ArgumentParser.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']``.
.. versionchanged:: 3.12
:class:`ArgumentParser` changed encoding and errors to read arguments files
from default (e.g. :func:`locale.getpreferredencoding(False)
<locale.getpreferredencoding>` and
``"strict"``) to :term:`filesystem encoding and error handler`.
Arguments file should be encoded in UTF-8 instead of ANSI Codepage on Windows.
argument_default
^^^^^^^^^^^^^^^^
.. _allow_abbrev:
allow_abbrev
^^^^^^^^^^^^
.. versionadded:: 3.5
conflict_handler
^^^^^^^^^^^^^^^^
:class:`ArgumentParser` objects do not allow two actions with the same option
string. By default, :class:`ArgumentParser` objects raise 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
:class:`ArgumentParser`::
options:
-h, --help show this help message and exit
-f FOO old foo help
--foo FOO new foo help
add_help
^^^^^^^^
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()
.. code-block:: shell-session
$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]
options:
-h, --help show this help message and exit
--foo FOO foo help
options:
--foo FOO foo help
options:
+h, ++help show this help message and exit
exit_on_error
^^^^^^^^^^^^^
If the user would like to catch errors manually, the feature can be enabled by
setting
``exit_on_error`` to ``False``::
.. versionadded:: 3.9
The add_argument() method
-------------------------
.. _name_or_flags:
name or flags
^^^^^^^^^^^^^
>>> parser.add_argument('bar')
When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
identified by the ``-`` prefix, and the remaining arguments will be assumed to
be positional::
.. _action:
action
^^^^^^
* ``'store'`` - This just stores the argument's value. This is the default
action. For example::
* ``'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. See :class:`ArgumentParser` for details of how the
output is created.
* ``'extend'`` - This stores a list, and extends each argument value to the
list.
Example usage::
.. versionadded:: 3.9
.. _nargs:
nargs
^^^^^
* ``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::
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. For example::
* ``'+'``. 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 one command-line argument present. 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.
.. _const:
const
^^^^^
.. versionchanged:: 3.11
``const=None`` by default, including when ``action='append_const'`` or
``action='store_const'``.
.. _default:
default
^^^^^^^
All optional arguments and some positional arguments may be omitted at the
command line. The ``default`` keyword argument of
:meth:`~ArgumentParser.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 target namespace already has an attribute set, the action *default*
will not over write it::
For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
is used when no command-line argument was present::
.. _argparse-type:
type
^^^^
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 ``type`` can be any callable that accepts a single string.
If the function raises :exc:`ArgumentTypeError`, :exc:`TypeError`, or
:exc:`ValueError`, the exception is caught and a nicely formatted error
message is displayed. No other exception types are handled.
.. testcode::
import argparse
import pathlib
parser = argparse.ArgumentParser()
parser.add_argument('count', type=int)
parser.add_argument('distance', type=float)
parser.add_argument('street', type=ascii)
parser.add_argument('code_point', type=ord)
parser.add_argument('source_file', type=open)
parser.add_argument('dest_file', type=argparse.FileType('w', encoding='latin-
1'))
parser.add_argument('datapath', type=pathlib.Path)
.. doctest::
In general, the ``type`` 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 ``type`` keyword. A
:exc:`~json.JSONDecodeError` would not be well formatted and a
:exc:`FileNotFoundError` exception would not be handled at all.
Even :class:`~argparse.FileType` has its limitations for use with the ``type``
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
:keyword:`with`-statement to manage the files.
For type checkers that simply check against a fixed set of values, consider
using the choices_ keyword instead.
.. _choices:
choices
^^^^^^^
Note that inclusion in the *choices* sequence is checked after any type_
conversions have been performed, so the type of the objects in the *choices*
sequence should match the type_ specified::
.. _required:
required
^^^^^^^^
In general, the :mod:`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 :meth:`~ArgumentParser.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:
help
^^^^
positional arguments:
bar one of the bars to be frobbled
options:
-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
:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::
positional arguments:
bar the bar to frobble (default: 42)
options:
-h, --help show this help message and exit
As the help string supports %-formatting, if you want a literal ``%`` to appear
in the help string, you must escape it as ``%%``.
options:
-h, --help show this help message and exit
.. _metavar:
metavar
^^^^^^^
positional arguments:
bar
options:
-h, --help show this help message and exit
--foo FOO
positional arguments:
XXX
options:
-h, --help show this help message and exit
--foo YYY
Note that ``metavar`` only changes the *displayed* name - the name of the
attribute on the :meth:`~ArgumentParser.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::
options:
-h, --help show this help message and exit
-x X X
--foo bar baz
.. _dest:
dest
^^^^
For optional argument actions, the value of ``dest`` is normally inferred from
the option strings. :class:`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
^^^^^^^^^^^^^^
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
:meth:`~ArgumentParser.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.
The ``__call__`` method may perform arbitrary actions, but will typically set
attributes on the ``namespace`` based on ``dest`` and ``values``.
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 ``=`` to
separate them::
>>> parser.parse_args(['--foo=FOO'])
Namespace(foo='FOO', x=None)
For short options (options only one character long), the option and its value
can be concatenated::
>>> parser.parse_args(['-xX'])
Namespace(foo=None, x='X')
Several short options can be joined together, using only a single ``-`` prefix,
as long as only the last option (or none of them) requires a value::
Invalid arguments
^^^^^^^^^^^^^^^^^
If you have positional arguments that must begin with ``-`` and don't look
like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
:meth:`~ArgumentParser.parse_args` that everything after that is a positional
argument::
>>> parser.parse_args(['--', '-f'])
Namespace(foo='-f', one=None)
.. _prefix-matching:
An error is produced for arguments that could produce more than one options.
This feature can be disabled by setting :ref:`allow_abbrev` to ``False``.
.. _args:
Beyond ``sys.argv``
^^^^^^^^^^^^^^^^^^^
.. _namespace:
>>> class C:
... pass
...
>>> c = C()
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
>>> c.foo
'BAR'
Other utilities
---------------
Sub-commands
^^^^^^^^^^^^
Description of parameters:
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 :meth:`~_SubParsersAction.add_parser` as above.)
::
>>> parser.parse_args(['--help'])
usage: PROG [-h] [--foo] {a,b} ...
positional arguments:
{a,b} sub-command help
a a help
b b help
options:
-h, --help show this help message and exit
--foo foo help
positional arguments:
bar bar help
options:
-h, --help show this help message and exit
options:
-h, --help show this help message and exit
--baz {X,Y,Z} baz help
options:
-h, --help show this help message and exit
subcommands:
valid subcommands
This way, you can let :meth:`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 :meth:`add_subparsers` call will work::
.. versionchanged:: 3.7
New *required* keyword argument.
FileType objects
^^^^^^^^^^^^^^^^
The :class:`FileType` factory creates objects that can be passed to the type
argument of :meth:`ArgumentParser.add_argument`. Arguments that have
:class:`FileType` objects as their type will open command-line arguments as
files with the requested modes, buffer sizes, encodings and error handling
(see the :func:`open` function for more details)::
.. versionadded:: 3.4
The *encodings* and *errors* keyword arguments.
Argument groups
^^^^^^^^^^^^^^^
group:
bar bar help
--foo FOO foo help
group1:
group1 description
group2:
group2 description
Note that any arguments not in your user-defined groups will end up back
in the usual "positional arguments" and "optional arguments" sections.
.. versionchanged:: 3.11
Calling :meth:`add_argument_group` 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
^^^^^^^^^^^^^^^^
.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)
Create a mutually exclusive group. :mod:`argparse` will make sure that only
one of the arguments in the mutually exclusive group was present on the
command line::
Note that currently mutually exclusive argument groups do not support the
*title* and *description* arguments of
:meth:`~ArgumentParser.add_argument_group`. However, a mutually exclusive
group can be added to an argument group that has a title and description.
For example::
options:
-h, --help show this help message and exit
Group title:
Group description
.. versionchanged:: 3.11
Calling :meth:`add_argument_group` or :meth:`add_mutually_exclusive_group`
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
^^^^^^^^^^^^^^^
.. method:: ArgumentParser.set_defaults(**kwargs)
.. method:: ArgumentParser.get_default(dest)
Printing help
^^^^^^^^^^^^^
.. method:: ArgumentParser.print_usage(file=None)
.. method:: ArgumentParser.print_help(file=None)
Print a help message, including the program usage and information about the
arguments registered with the :class:`ArgumentParser`. If *file* is
``None``, :data:`sys.stdout` is assumed.
There are also variants of these methods that simply return a string instead of
printing it:
.. method:: ArgumentParser.format_usage()
.. method:: ArgumentParser.format_help()
Return a string containing a help message, including the program usage and
information about the arguments registered with the :class:`ArgumentParser`.
Partial parsing
^^^^^^^^^^^^^^^
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
:meth:`~ArgumentParser.parse_known_args` method can be useful. It works much like
:meth:`~ArgumentParser.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.
::
.. warning::
:ref:`Prefix matching <prefix-matching>` rules apply to
:meth:`~ArgumentParser.parse_known_args`. 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.
.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
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::
class MyArgumentParser(argparse.ArgumentParser):
def convert_arg_line_to_args(self, arg_line):
return arg_line.split()
Exiting methods
^^^^^^^^^^^^^^^
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::
class ErrorCatchingArgumentParser(argparse.ArgumentParser):
def exit(self, status=0, message=None):
if status:
raise Exception(f'Exiting because of an error: {message}')
exit(status)
.. method:: ArgumentParser.error(message)
Intermixed parsing
^^^^^^^^^^^^^^^^^^
A number of Unix commands allow the user to intermix optional arguments with
positional arguments. The :meth:`~ArgumentParser.parse_intermixed_args`
and :meth:`~ArgumentParser.parse_known_intermixed_args` 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,
and mutually exclusive groups that include both
optionals and positionals are not supported.
.. versionadded:: 3.7
.. _upgrading-optparse-code:
* Replace :meth:`optparse.OptionParser.disable_interspersed_args`
by using :meth:`~ArgumentParser.parse_intermixed_args` instead of
:meth:`~ArgumentParser.parse_args`.
* Replace string names for ``type`` keyword arguments with the corresponding
type objects (e.g. int, float, complex, etc).
Exceptions
----------
.. exception:: ArgumentError
.. exception:: ArgumentTypeError
Raised when something goes wrong converting a command line string to a type.