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