Skip to content
Prev Previous commit
Next Next commit
Merge branch 'main' into argparse-filetype-deprecate
  • Loading branch information
serhiy-storchaka committed Oct 10, 2024
commit d899deb9295e2a8142d2bd438e0ba6c364728179
137 changes: 10 additions & 127 deletions Doc/library/argparse.rst
Original file line number Diff line number Diff line change
Expand Up @@ -49,133 +49,9 @@ the extracted data in a :class:`argparse.Namespace` object::
args = parser.parse_args()
print(args.filename, args.count, args.verbose)


Quick Links for add_argument()
------------------------------

============================ =========================================================== ==========================================================================================================================
Name Description Values
============================ =========================================================== ==========================================================================================================================
action_ Specify how an argument should be handled ``'store'``, ``'store_const'``, ``'store_true'``, ``'append'``, ``'append_const'``, ``'count'``, ``'help'``, ``'version'``
choices_ Limit values to a specific set of choices ``['foo', 'bar']``, ``range(1, 10)``, or :class:`~collections.abc.Container` instance
const_ Store a constant value
default_ Default value used when an argument is not provided Defaults to ``None``
dest_ Specify the attribute name used in the result namespace
help_ Help message for an argument
metavar_ Alternate display name for the argument as shown in help
nargs_ Number of times the argument can be used :class:`int`, ``'?'``, ``'*'``, or ``'+'``
required_ Indicate whether an argument is required or optional ``True`` or ``False``
:ref:`type <argparse-type>` Automatically convert an argument to the given type :class:`int`, :class:`float`, or callable function
============================ =========================================================== ==========================================================================================================================


Example
-------

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

import argparse

parser = 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()
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 ...]

Process some integers.

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

$ python prog.py 1 2 3 4 --sum
10

If invalid arguments are passed in, an error will be displayed:

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

The following sections walk you through this example.


Creating a parser
^^^^^^^^^^^^^^^^^

The first step in using the :mod:`argparse` is creating an
:class:`ArgumentParser` object::

>>> parser = argparse.ArgumentParser(description='Process some integers.')

The :class:`ArgumentParser` object will hold all the information necessary to
parse the command line into Python data types.


Adding arguments
^^^^^^^^^^^^^^^^

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

>>> 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)')

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


Parsing arguments
^^^^^^^^^^^^^^^^^

:class:`ArgumentParser` parses arguments through the
:meth:`~ArgumentParser.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 :class:`Namespace` object will be built up from
attributes parsed out of the command line::

>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
arguments, and the :class:`ArgumentParser` will automatically determine the
command-line arguments from :data:`sys.argv`.

.. note::
If you're looking a guide about how to upgrade optparse code
to argparse, see :ref:`Upgrading Optparse Code <upgrading-optparse-code>`.

ArgumentParser objects
----------------------
Expand Down Expand Up @@ -1132,6 +1008,13 @@ 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 :class:`~argparse.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.

Expand Down
You are viewing a condensed version of this merge commit. You can view the full changes here.