Add some x-refs.

This commit is contained in:
Georg Brandl 2010-03-02 22:17:38 +00:00
parent 5e32fe5f9d
commit d2decd9965
1 changed files with 204 additions and 207 deletions

View File

@ -9,11 +9,11 @@
The :mod:`argparse` module makes it easy to write user friendly command line
interfaces. You define what arguments your program requires, and
:mod:`argparse` will figure out how to parse those out of ``sys.argv``. The
:mod:`argparse` module also automatically generates help and usage messages
based on the arguments you have defined, and issues errors when users give your
program invalid arguments.
interfaces. You define what arguments your program requires, and :mod:`argparse`
will figure out how to parse those out of :data:`sys.argv`. The :mod:`argparse`
module also automatically generates help and usage messages based on the
arguments you have defined, and issues errors when users give your program
invalid arguments.
Example
-------
@ -93,11 +93,11 @@ them into objects for you. This information is stored and used when
... const=sum, default=max,
... help='sum the integers (default: find the max)')
when we later call :meth:`parse_args`, we can expect it to return an object
with two attributes, ``integers`` and ``accumulate``. The ``integers``
attribute will be a list of one or more ints, and the ``accumulate`` attribute
will be either the ``sum`` function, if ``--sum`` was specified at the command
line, or the ``max`` function if it was not.
when we later call :meth:`parse_args`, we can expect it to return an object with
two attributes, ``integers`` and ``accumulate``. The ``integers`` attribute
will be a list of one or more ints, 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
^^^^^^^^^^^^^^^^^
@ -105,17 +105,17 @@ Parsing arguments
Once an :class:`ArgumentParser` has been initialized with appropriate calls to
:meth:`add_argument`, it can be instructed to parse the command-line args by
calling the :meth:`parse_args` method. This will inspect the command-line,
convert each arg to the appropriate type and then invoke the appropriate
action. In most cases, this means a simple namespace object will be built up
from attributes parsed out of the command-line::
convert each arg to the appropriate type and then invoke the appropriate action.
In most cases, this means a simple 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:`parse_args` will typically be called with no arguments, and
the :class:`ArgumentParser` will automatically determine the command-line args
from ``sys.argv``. That's pretty much it. You're now ready to go write some
command line interfaces!
from :data:`sys.argv`. That's pretty much it. You're now ready to go write
some command line interfaces!
ArgumentParser objects
@ -184,7 +184,7 @@ 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 ArgumentParser::
argument to :class:`ArgumentParser`::
>>> parser = argparse.ArgumentParser(
... description='A foo that bars',
@ -261,12 +261,12 @@ disallowed.
fromfile_prefix_chars
^^^^^^^^^^^^^^^^^^^^^
Sometimes, e.g. for particularly long argument lists, it may make sense to
keep the list of arguments in a file rather than typing it out at the command
line. If the ``fromfile_prefix_chars=`` argument is given to the ArgumentParser
constructor, then arguments that start with any of the specified characters
will be treated as files, and will be replaced by the arguments they contain.
For example::
Sometimes, e.g. for particularly long argument lists, it may make sense to keep
the list of arguments in a file rather than typing it out at the command line.
If the ``fromfile_prefix_chars=`` argument is given to the ArgumentParser
constructor, then arguments that start with any of the specified characters will
be treated as files, and will be replaced by the arguments they contain. For
example::
>>> open('args.txt', 'w').write('-f\nbar')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
@ -291,8 +291,8 @@ Generally, argument defaults are specified either by passing a default to
specific set of name-value pairs. Sometimes however, it may be useful to
specify a single parser-wide default for arguments. This can be accomplished by
passing the ``argument_default=`` keyword argument to ArgumentParser. For
example, to globally suppress attribute creation on :meth:`parse_args` calls,
we supply ``argument_default=SUPPRESS``::
example, to globally suppress attribute creation on :meth:`parse_args` calls, we
supply ``argument_default=SUPPRESS``::
>>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
>>> parser.add_argument('--foo')
@ -310,8 +310,8 @@ Sometimes, several parsers share a common set of arguments. Rather than
repeating the definitions of these arguments, you can define a single parser
with all the shared arguments and then use the ``parents=`` argument to
ArgumentParser to have these "inherited". The ``parents=`` argument takes a
list of ArgumentParser objects, collects all the positional and optional
actions from them, and adds these actions to the ArgumentParser object being
list of ArgumentParser objects, collects all the positional and optional actions
from them, and adds these actions to the ArgumentParser object being
constructed::
>>> parent_parser = argparse.ArgumentParser(add_help=False)
@ -337,10 +337,11 @@ formatter_class
ArgumentParser objects allow the help formatting to be customized by specifying
an alternate formatting class. Currently, there are three such classes:
``argparse.RawDescriptionHelpFormatter``, ``argparse.RawTextHelpFormatter`` and
``argparse.ArgumentDefaultsHelpFormatter``. The first two allow more control
over how textual descriptions are displayed, while the last automatically adds
information about argument default values.
:class:`argparse.RawDescriptionHelpFormatter`,
:class:`argparse.RawTextHelpFormatter` and
:class:`argparse.ArgumentDefaultsHelpFormatter`. The first two allow more
control over how textual descriptions are displayed, while the last
automatically adds information about argument default values.
By default, ArgumentParser objects line-wrap the description_ and epilog_ texts
in command-line help messages::
@ -367,8 +368,8 @@ in command-line help messages::
When you have description_ and epilog_ that is already correctly formatted and
should not be line-wrapped, you can indicate this by passing
``argparse.RawDescriptionHelpFormatter`` as the ``formatter_class=`` argument
to ArgumentParser::
``argparse.RawDescriptionHelpFormatter`` as the ``formatter_class=`` argument to
ArgumentParser::
>>> parser = argparse.ArgumentParser(
... prog='PROG',
@ -395,9 +396,8 @@ to ArgumentParser::
If you want to maintain whitespace for all sorts of help text (including
argument descriptions), you can use ``argparse.RawTextHelpFormatter``.
The other formatter class available,
``argparse.ArgumentDefaultsHelpFormatter``, will add information about the
default value of each of the arguments::
The other formatter class available, ``argparse.ArgumentDefaultsHelpFormatter``,
will add information about the default value of each of the arguments::
>>> parser = argparse.ArgumentParser(
... prog='PROG',
@ -418,9 +418,9 @@ default value of each of the arguments::
conflict_handler
^^^^^^^^^^^^^^^^
ArgumentParser objects do not allow two actions with the same option string.
By default, ArgumentParser objects will raise an exception if you try to create
an argument with an option string that is already in use::
ArgumentParser objects do not allow two actions with the same option string. By
default, ArgumentParser objects will raise an exception if you try to create an
argument with an option string that is already in use::
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-f', '--foo', help='old foo help')
@ -665,9 +665,9 @@ are:
* ``'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::
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::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--str', dest='types', action='append_const', const=str)
@ -687,8 +687,8 @@ are:
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:
supplying an appropriate :meth:`__call__` method. The ``__call__`` method
accepts four parameters:
* ``parser`` - The ArgumentParser object which contains this action.
@ -725,12 +725,11 @@ nargs
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 :meth:`add_argument`. The supported values
are:
different number of command-line arguments with a single action, you can use the
``nargs`` keyword argument to :meth:`add_argument`. The supported values are:
* N (an integer). N args from the command-line will be gathered together into
a list. For example::
* N (an integer). N args from the command-line will be gathered together into a
list. For example::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
@ -770,9 +769,9 @@ are:
Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>, outfile=<open file '<stdout>', mode 'w' at 0x...>)
* ``'*'``. 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::
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::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs='*')
@ -863,8 +862,8 @@ type
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 :meth:`add_argument` allows any necessary type-checking and
another type, e.g. :class:`float`, :class:`int` or :class:`file`. The ``type``
keyword argument of :meth:`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::
@ -949,8 +948,8 @@ container should match the type_ specified::
PROG: error: argument foo: invalid choice: (-4+0j) (choose from 1, 1j)
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.
value, so :class:`dict` objects, :class:`set` objects, custom containers,
etc. are all supported.
required
@ -982,12 +981,12 @@ help
^^^^
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 :meth:`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::
out which option does what. So for the end-users, ``help`` is probably the most
important argument to include in your :meth:`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',
@ -1074,8 +1073,8 @@ attribute on the :meth:`parse_args` object is still determined by the dest_
value.
Different values of ``nargs`` may cause the metavar to be used multiple times.
If you'd like to specify a different display name for each of the arguments,
you can provide a tuple to ``metavar``::
If you'd like to specify a different display name for each of the arguments, you
can provide a tuple to ``metavar``::
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
@ -1108,8 +1107,8 @@ 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
internal ``'-'`` characters will be converted to ``'_'`` characters to make sure
the string is a valid attribute name. The examples below illustrate this
behavior::
>>> parser = argparse.ArgumentParser()
@ -1142,7 +1141,7 @@ The parse_args() method
created and how they are assigned. See the documentation for
:meth:`add_argument` for details.
By default, the arg strings are taken from ``sys.argv``, and a new empty
By default, the arg strings are taken from :data:`sys.argv`, and a new empty
``Namespace`` object is created for the attributes.
Option value syntax
@ -1161,8 +1160,8 @@ passed as two separate arguments::
Namespace(foo='FOO', x=None)
For long options (options with names longer than a single character), you may
also pass the option and value as a single command line argument, using ``=``
to separate them::
also pass the option and value as a single command line argument, using ``=`` to
separate them::
>>> parser.parse_args('--foo=FOO'.split())
Namespace(foo='FOO', x=None)
@ -1285,11 +1284,11 @@ refer to more than one option.
Beyond ``sys.argv``
^^^^^^^^^^^^^^^^^^^
Sometimes it may be useful to have an ArgumentParser parse args other than
those of ``sys.argv``. This can be accomplished by passing a list of strings
to ``parse_args``. You may have noticed that the examples in the argparse
documentation have made heavy use of this calling style - it is much easier
to use at the interactive prompt::
Sometimes it may be useful to have an ArgumentParser parse args other than those
of :data:`sys.argv`. This can be accomplished by passing a list of strings to
``parse_args``. You may have noticed that the examples in the argparse
documentation have made heavy use of this calling style - it is much easier to
use at the interactive prompt::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument(
@ -1308,9 +1307,8 @@ Custom namespaces
^^^^^^^^^^^^^^^^^
It may also be useful to have an ArgumentParser assign attributes to an already
existing object, rather than the newly-created Namespace object that is
normally used. This can be achieved by specifying the ``namespace=`` keyword
argument::
existing object, rather than the newly-created Namespace object that is normally
used. This can be achieved by specifying the ``namespace=`` keyword argument::
>>> class C(object):
... pass
@ -1331,18 +1329,17 @@ Sub-commands
.. method:: add_subparsers()
A lot of programs split up their functionality into a number of
sub-commands, for example, the ``svn`` program can invoke sub-commands like
``svn checkout``, ``svn update``, ``svn commit``, etc. Splitting up
functionality this way can be a particularly good idea when a program
performs several different functions which require different kinds of
command-line arguments. ArgumentParser objects support the creation of such
sub-commands with the :meth:`add_subparsers` method. The
:meth:`add_subparsers` method is normally called with no arguments and
returns an special action object. This object has a single method,
``add_parser``, which takes a command name and any ArgumentParser
constructor arguments, and returns an ArgumentParser object that can be
modified as usual.
A lot of programs split up their functionality into a number of sub-commands,
for example, the ``svn`` program can invoke sub-commands like ``svn
checkout``, ``svn update``, ``svn commit``, etc. Splitting up functionality
this way can be a particularly good idea when a program performs several
different functions which require different kinds of command-line arguments.
ArgumentParser objects support the creation of such sub-commands with the
:meth:`add_subparsers` method. The :meth:`add_subparsers` method is normally
called with no arguments and returns an special action object. This object
has a single method, ``add_parser``, which takes a command name and any
ArgumentParser constructor arguments, and returns an ArgumentParser object
that can be modified as usual.
Some example usage::
@ -1368,15 +1365,15 @@ Sub-commands
Note that the object returned by :meth:`parse_args` will only contain
attributes for the main parser and the subparser that was selected by the
command line (and not any other subparsers). So in the example above, when
the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes
are present, and when the ``"b"`` command is specified, only the ``foo`` and
the ``"a"`` command is specified, only the ``foo`` and ``bar`` attributes are
present, and when the ``"b"`` command is specified, only the ``foo`` and
``baz`` attributes are present.
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. (You can however supply a
help message for each subparser command by suppling the ``help=`` argument
to ``add_parser`` as above.)
help message for each subparser command by suppling the ``help=`` argument to
``add_parser`` as above.)
::
@ -1408,9 +1405,9 @@ Sub-commands
-h, --help show this help message and exit
--baz {X,Y,Z} baz help
The :meth:`add_subparsers` method also supports ``title`` and
``description`` keyword arguments. When either is present, the subparser's
commands will appear in their own group in the help output. For example::
The :meth:`add_subparsers` method also supports ``title`` and ``description``
keyword arguments. When either is present, the subparser's commands will
appear in their own group in the help output. For example::
>>> parser = argparse.ArgumentParser()
>>> subparsers = parser.add_subparsers(title='subcommands',
@ -1430,9 +1427,9 @@ Sub-commands
{foo,bar} additional help
One particularly effective way of handling sub-commands is to combine the
use of the :meth:`add_subparsers` method with calls to :meth:`set_defaults`
so that each subparser knows which Python function it should execute. For
One particularly effective way of handling sub-commands is to combine the use
of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
that each subparser knows which Python function it should execute. For
example::
>>> # sub-command functions
@ -1469,8 +1466,8 @@ Sub-commands
This way, you can let :meth:`parse_args` do all the work for you, and then
just call the appropriate function after the 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 you
Associating functions with actions like this is typically the easiest way to
handle the different actions for each of your subparsers. However, if you
find it necessary to check the name of the subparser that was invoked, you
can always provide a ``dest`` keyword argument to the :meth:`add_subparsers`
call::
@ -1492,8 +1489,8 @@ FileType objects
The :class:`FileType` factory creates objects that can be passed to the type
argument of :meth:`add_argument`. Arguments that have :class:`FileType`
objects as their type will open command-line args as files with the
requested modes and buffer sizes:
objects as their type will open command-line args as files with the requested
modes and buffer sizes:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
@ -1608,12 +1605,12 @@ Parser defaults
.. method:: set_defaults(**kwargs)
Most of the time, the attributes of the object returned by
:meth:`parse_args` will be fully determined by inspecting the command-line
args and the argument actions described in your :meth:`add_argument` calls.
However, sometimes it may be useful to add some additional attributes that
are determined without any inspection of the command-line. The
:meth:`set_defaults` method allows you to do this::
Most of the time, the attributes of the object returned by :meth:`parse_args`
will be fully determined by inspecting the command-line args and the argument
actions described in your :meth:`add_argument` calls. However, sometimes it
may be useful to add some additional attributes that are determined without
any inspection of the command-line. The :meth:`set_defaults` method allows
you to do this::
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('foo', type=int)
@ -1688,9 +1685,9 @@ 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:`parse_known_args` method can be useful. It works much like
:meth:`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.
:meth:`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.
::
@ -1716,8 +1713,8 @@ Customizing file parsing
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::
A useful override of this method is one that treats each space-separated word
as an argument::
def convert_arg_line_to_args(self, arg_line):
for arg in arg_line.split():
@ -1730,19 +1727,19 @@ Upgrading optparse code
-----------------------
Originally, the argparse module had attempted to maintain compatibility with
optparse. However, optparse was difficult to extend transparently,
particularly with the changes required to support the new ``nargs=``
specifiers and better usage messges. When most everything in optparse had
either been copy-pasted over or monkey-patched, it no longer seemed practical
to try to maintain the backwards compatibility.
optparse. However, optparse was difficult to extend transparently, particularly
with the changes required to support the new ``nargs=`` specifiers and better
usage messges. When most everything in optparse had either been copy-pasted
over or monkey-patched, it no longer seemed practical to try to maintain the
backwards compatibility.
A partial upgrade path from optparse to argparse:
* Replace all ``add_option()`` calls with :meth:`add_argument` calls.
* Replace ``options, args = parser.parse_args()`` with
``args = parser.parse_args()`` and add additional :meth:`add_argument` calls
for the positional arguments.
* Replace ``options, args = parser.parse_args()`` with ``args =
parser.parse_args()`` and add additional :meth:`add_argument` calls for the
positional arguments.
* Replace callback actions and the ``callback_*`` keyword arguments with
``type`` or ``action`` arguments.
@ -1753,6 +1750,6 @@ A partial upgrade path from optparse to argparse:
* Replace ``Values`` with ``Namespace`` and ``OptionError/OptionValueError``
with ``ArgumentError``.
* Replace strings with implicit arguments such as ``%default`` or ``%prog``
with the standard python syntax to use dictionaries to format strings, that
is, ``%(default)s`` and ``%(prog)s``.
* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
the standard python syntax to use dictionaries to format strings, that is,
``%(default)s`` and ``%(prog)s``.