argparse.py revision 63755f3bd94c7e193a44324d3248b2478cbf47fc
141deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake# Author: Steven J. Bethard <steven.bethard@gmail.com>.
241deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
341deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake"""Command-line parsing library
441deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
541deb1efc2f969b58e49af669cc20d15ccdb04c6Fred DrakeThis module is an optparse-inspired command-line parsing library that:
641deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
741deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    - handles both optional and positional arguments
8bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake    - produces highly informative usage messages
9bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake    - supports parsers that dispatch to sub-parsers
10bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake
11bd7f818c508248e12f88e51198cb5e9b861dacbfFred DrakeThe following is a simple usage example that sums integers from the
1241deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drakecommand-line and writes the result to a file::
1341deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
1433ad28b68dd6caadc1e6cb8f917665d6270e7b25Andrew M. Kuchling    parser = argparse.ArgumentParser(
1533ad28b68dd6caadc1e6cb8f917665d6270e7b25Andrew M. Kuchling        description='sum the integers at the command line')
1633ad28b68dd6caadc1e6cb8f917665d6270e7b25Andrew M. Kuchling    parser.add_argument(
1733ad28b68dd6caadc1e6cb8f917665d6270e7b25Andrew M. Kuchling        'integers', metavar='int', nargs='+', type=int,
1833ad28b68dd6caadc1e6cb8f917665d6270e7b25Andrew M. Kuchling        help='an integer to be summed')
1933ad28b68dd6caadc1e6cb8f917665d6270e7b25Andrew M. Kuchling    parser.add_argument(
2033ad28b68dd6caadc1e6cb8f917665d6270e7b25Andrew M. Kuchling        '--log', default=sys.stdout, type=argparse.FileType('w'),
2133ad28b68dd6caadc1e6cb8f917665d6270e7b25Andrew M. Kuchling        help='the file where the sum should be written')
2241deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    args = parser.parse_args()
23e029242d5cfb8a3879bdc7324db4449e6a8451cfFred Drake    args.log.write('%s' % sum(args.integers))
24e029242d5cfb8a3879bdc7324db4449e6a8451cfFred Drake    args.log.close()
25e029242d5cfb8a3879bdc7324db4449e6a8451cfFred Drake
2641deb1efc2f969b58e49af669cc20d15ccdb04c6Fred DrakeThe module contains the following public classes:
2741deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
289a9d219f07656a9f1eb6f8beb2a9e2ee462b77f8Fred Drake    - ArgumentParser -- The main entry point for command-line parsing. As the
2940fc16059f04ee8fda0b5956cc4883eb21ca8f8cSkip Montanaro        example above shows, the add_argument() method is used to populate
3040fc16059f04ee8fda0b5956cc4883eb21ca8f8cSkip Montanaro        the parser with actions for optional and positional arguments. Then
3141deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        the parse_args() method is invoked to convert the args at the
32bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake        command-line into an object with attributes.
335e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
34bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake    - ArgumentError -- The exception raised by ArgumentParser objects when
3541deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        there are errors with the parser's actions. Errors raised while
36bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake        parsing the command-line are caught by ArgumentParser and emitted
37bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake        as command-line messages.
38bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake
3941deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    - FileType -- A factory for defining types of files to be created. As the
4041deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        example above shows, instances of FileType are typically passed as
419d2c85dec7262475b83d45fdb53651c9c069e1cbFred Drake        the type= argument of add_argument() calls.
429d2c85dec7262475b83d45fdb53651c9c069e1cbFred Drake
439d2c85dec7262475b83d45fdb53651c9c069e1cbFred Drake    - Action -- The base class for parser actions. Typically actions are
4441deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        selected by passing strings like 'store_true' or 'append_const' to
450a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        the action= argument of add_argument(). However, for greater
460a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        customization of ArgumentParser actions, subclasses of Action may
470a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        be defined and passed as the action= argument.
480a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake
490a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake    - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
500a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        ArgumentDefaultsHelpFormatter -- Formatter classes which
519166e1a24ac7b15776ffd38e436fa51a9b002674Georg Brandl        may be passed as the formatter_class= argument to the
520a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        ArgumentParser constructor. HelpFormatter is the default,
5341deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
544fd06e0170aa75e4873b73f733bfd3f3de19d967Fred Drake        not to change the formatting for help text, and
5541deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        ArgumentDefaultsHelpFormatter adds information about argument defaults
5641deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        to the help.
5741deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
5841deb1efc2f969b58e49af669cc20d15ccdb04c6Fred DrakeAll other classes in this module are considered implementation details.
5941deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
6061146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettingerconsidered public as object names -- the API of the formatter objects is
6161146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettingerstill considered an implementation detail.)
6261146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger"""
6361146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger
6461146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger__version__ = '1.1'
6561146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger__all__ = [
6661146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    'ArgumentParser',
6761146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    'ArgumentError',
6861146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    'ArgumentTypeError',
6961146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    'FileType',
7061146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    'HelpFormatter',
7161146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    'ArgumentDefaultsHelpFormatter',
7261146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    'RawDescriptionHelpFormatter',
7361146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    'RawTextHelpFormatter',
7441deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    'MetavarTypeHelpFormatter',
759d2c85dec7262475b83d45fdb53651c9c069e1cbFred Drake    'Namespace',
7641deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    'Action',
7741deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    'ONE_OR_MORE',
780a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake    'OPTIONAL',
7941deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    'PARSER',
8041deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    'REMAINDER',
819d2c85dec7262475b83d45fdb53651c9c069e1cbFred Drake    'SUPPRESS',
82bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake    'ZERO_OR_MORE',
83bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake]
8441deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
8541deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
869d2c85dec7262475b83d45fdb53651c9c069e1cbFred Drakeimport collections as _collections
8741deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drakeimport copy as _copy
881d9e4b7de3d15007d5b9e7ac4b38f5e158d3c840Fred Drakeimport os as _os
8941deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drakeimport re as _re
90bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drakeimport sys as _sys
9141deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drakeimport textwrap as _textwrap
9241deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
9341deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drakefrom gettext import gettext as _, ngettext
94bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake
9541deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
9641deb1efc2f969b58e49af669cc20d15ccdb04c6Fred DrakeSUPPRESS = '==SUPPRESS=='
9741deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
9841deb1efc2f969b58e49af669cc20d15ccdb04c6Fred DrakeOPTIONAL = '?'
9941deb1efc2f969b58e49af669cc20d15ccdb04c6Fred DrakeZERO_OR_MORE = '*'
10041deb1efc2f969b58e49af669cc20d15ccdb04c6Fred DrakeONE_OR_MORE = '+'
10141deb1efc2f969b58e49af669cc20d15ccdb04c6Fred DrakePARSER = 'A...'
102312a5dc539b583abcbbf006942a4ceead9b9172bFred DrakeREMAINDER = '...'
103bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
104bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake
10541deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake# =============================
106312a5dc539b583abcbbf006942a4ceead9b9172bFred Drake# Utility functions and classes
10741deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake# =============================
10841deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
109101209d44ce063cd04fd6793d94991f8e6688428Fred Drakeclass _AttributeHolder(object):
11061146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    """Abstract base class that provides __repr__.
11161146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger
11261146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    The __repr__ method returns a string in the format::
11361146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger        ClassName(attr=name, attr=name, ...)
114101209d44ce063cd04fd6793d94991f8e6688428Fred Drake    The attributes are determined either by a class-level attribute,
115101209d44ce063cd04fd6793d94991f8e6688428Fred Drake    '_kwarg_names', or by inspecting the instance __dict__.
116101209d44ce063cd04fd6793d94991f8e6688428Fred Drake    """
11761146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger
11861146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    def __repr__(self):
11961146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger        type_name = type(self).__name__
120101209d44ce063cd04fd6793d94991f8e6688428Fred Drake        arg_strings = []
121101209d44ce063cd04fd6793d94991f8e6688428Fred Drake        for arg in self._get_args():
12261146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger            arg_strings.append(repr(arg))
12361146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger        for name, value in self._get_kwargs():
12461146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger            arg_strings.append('%s=%r' % (name, value))
12561146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger        return '%s(%s)' % (type_name, ', '.join(arg_strings))
126101209d44ce063cd04fd6793d94991f8e6688428Fred Drake
12741deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    def _get_kwargs(self):
12841deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        return sorted(self.__dict__.items())
129bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake
130bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake    def _get_args(self):
13141deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        return []
13241deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
13341deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
1342c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettingerdef _ensure_value(namespace, name, value):
1352c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger    if getattr(namespace, name, None) is None:
1362c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger        setattr(namespace, name, value)
1372c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger    return getattr(namespace, name)
1382c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger
1392c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger
1402c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger# ===============
1412c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger# Formatting Help
1422c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger# ===============
1432c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger
1442c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettingerclass HelpFormatter(object):
1452c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger    """Formatter for generating usage messages and argument help strings.
14680ce6dd5642025f5cdf0ba5556f08df0803f5636Walter Dörwald
14741deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    Only the name of this class is considered a public API. All the methods
148bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake    provided by the class are considered an implementation detail.
14941deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    """
1500a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake
15141deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake    def __init__(self,
15241deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake                 prog,
153bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake                 indent_increment=2,
15441deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake                 max_help_position=24,
15531017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger                 width=None):
15641deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
15731017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger        # default setting for width
15831017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger        if width is None:
15931017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger            try:
16031017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger                width = int(_os.environ['COLUMNS'])
1610a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake            except (KeyError, ValueError):
16231017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger                width = 80
16331017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger            width -= 2
16441deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
16541deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        self._prog = prog
16641deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        self._indent_increment = indent_increment
167bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake        self._max_help_position = max_help_position
168bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake        self._width = width
16941deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake
17041deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        self._current_indent = 0
17141deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        self._level = 0
17241deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        self._action_max_length = 0
1730a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake
1740a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        self._root_section = self._Section(self, None)
1750a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        self._current_section = self._root_section
1760a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake
1770a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        self._whitespace_matcher = _re.compile(r'\s+')
1780a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        self._long_break_matcher = _re.compile(r'\n\n\n+')
1790a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake
1800a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake    # ===============================
1810a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake    # Section and indentation methods
1820a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake    # ===============================
1830a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake    def _indent(self):
1840a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        self._current_indent += self._indent_increment
1850a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        self._level += 1
1860a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake
1870a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake    def _dedent(self):
1880a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        self._current_indent -= self._indent_increment
1890a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        assert self._current_indent >= 0, 'Indent decreased below 0.'
1900a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake        self._level -= 1
1910a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake
1920a4dd390bf653128de8bc2e99da64967c8cdf86eFred Drake    class _Section(object):
193746fe0fae5442403c64be34b87609601166e97c8Fred Drake
19441deb1efc2f969b58e49af669cc20d15ccdb04c6Fred Drake        def __init__(self, formatter, parent, heading=None):
1955e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            self.formatter = formatter
196bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake            self.parent = parent
197bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake            self.heading = heading
198bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake            self.items = []
199bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake
200bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake        def format_help(self):
201bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake            # format the indented section
202bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake            if self.parent is not None:
203bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake                self.formatter._indent()
204bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake            join = self.formatter._join_parts
2055e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            for func, args in self.items:
2065e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis                func(*args)
2075e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            item_help = join([func(*args) for func, args in self.items])
208746fe0fae5442403c64be34b87609601166e97c8Fred Drake            if self.parent is not None:
209746fe0fae5442403c64be34b87609601166e97c8Fred Drake                self.formatter._dedent()
210746fe0fae5442403c64be34b87609601166e97c8Fred Drake
211746fe0fae5442403c64be34b87609601166e97c8Fred Drake            # return nothing if the section was empty
2125e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            if not item_help:
213009afb7c90882ee83e196b62b1555067e14fd950Guido van Rossum                return ''
2145e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
215b663a2ccbdd9bbd9a13f0cea743af709c53ec0c1Fred Drake            # add the heading if the section was non-empty
216886128f4f8b30b7e3623418eab063a3a8dd3495cTim Peters            if self.heading is not SUPPRESS and self.heading is not None:
217b663a2ccbdd9bbd9a13f0cea743af709c53ec0c1Fred Drake                current_indent = self.formatter._current_indent
2185e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis                heading = '%*s%s:\n' % (current_indent, '', self.heading)
2195e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            else:
2205e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis                heading = ''
2215e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
2225e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            # join the section-initial newline, the heading and the help
2235e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            return join(['\n', heading, item_help, '\n'])
2245e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
2255e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis    def _add_item(self, func, args):
2265e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis        self._current_section.items.append((func, args))
2275e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
2285e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis    # ========================
2295e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis    # Message building methods
2305e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis    # ========================
2315e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis    def start_section(self, heading):
2325e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis        self._indent()
2339d2c85dec7262475b83d45fdb53651c9c069e1cbFred Drake        section = self._Section(self, self._current_section, heading)
2345e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis        self._add_item(section.format_help, [])
2351d9e4b7de3d15007d5b9e7ac4b38f5e158d3c840Fred Drake        self._current_section = section
2365e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
2375e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis    def end_section(self):
2381d9e4b7de3d15007d5b9e7ac4b38f5e158d3c840Fred Drake        self._current_section = self._current_section.parent
2393bae7ddf8e63889b185235f85a6695bc05d59059Fred Drake        self._dedent()
2403bae7ddf8e63889b185235f85a6695bc05d59059Fred Drake
2413bae7ddf8e63889b185235f85a6695bc05d59059Fred Drake    def add_text(self, text):
2423bae7ddf8e63889b185235f85a6695bc05d59059Fred Drake        if text is not SUPPRESS and text is not None:
24354f0222547b1e92cd018ef132307a6f793dc9505Raymond Hettinger            self._add_item(self._format_text, [text])
2441d9e4b7de3d15007d5b9e7ac4b38f5e158d3c840Fred Drake
24554f0222547b1e92cd018ef132307a6f793dc9505Raymond Hettinger    def add_usage(self, usage, actions, groups, prefix=None):
24654f0222547b1e92cd018ef132307a6f793dc9505Raymond Hettinger        if usage is not SUPPRESS:
24754f0222547b1e92cd018ef132307a6f793dc9505Raymond Hettinger            args = usage, actions, groups, prefix
24854f0222547b1e92cd018ef132307a6f793dc9505Raymond Hettinger            self._add_item(self._format_usage, args)
24954f0222547b1e92cd018ef132307a6f793dc9505Raymond Hettinger
25054f0222547b1e92cd018ef132307a6f793dc9505Raymond Hettinger    def add_argument(self, action):
251c411dbaeee29dba87d5432a92fe76ea65d8e25f0Tim Peters        if action.help is not SUPPRESS:
2525e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
2535e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            # find all invocations
2545e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            get_invocation = self._format_action_invocation
2555e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            invocations = [get_invocation(action)]
2565e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            for subaction in self._iter_indented_subactions(action):
2575e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis                invocations.append(get_invocation(subaction))
2585e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
2595e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            # update the maximum item length
260101209d44ce063cd04fd6793d94991f8e6688428Fred Drake            invocation_length = max([len(s) for s in invocations])
26161146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger            action_length = invocation_length + self._current_indent
26261146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger            self._action_max_length = max(self._action_max_length,
26361146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger                                          action_length)
26461146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger
265101209d44ce063cd04fd6793d94991f8e6688428Fred Drake            # add the item to the list
266101209d44ce063cd04fd6793d94991f8e6688428Fred Drake            self._add_item(self._format_action, [action])
26761146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger
26861146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    def add_arguments(self, actions):
26961146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger        for action in actions:
27061146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger            self.add_argument(action)
27161146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger
27261146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    # =======================
27361146790992e0a00b76a6bf6ecc9e53289a1ecd7Raymond Hettinger    # Help-formatting methods
274101209d44ce063cd04fd6793d94991f8e6688428Fred Drake    # =======================
275101209d44ce063cd04fd6793d94991f8e6688428Fred Drake    def format_help(self):
276101209d44ce063cd04fd6793d94991f8e6688428Fred Drake        help = self._root_section.format_help()
277101209d44ce063cd04fd6793d94991f8e6688428Fred Drake        if help:
2781d9e4b7de3d15007d5b9e7ac4b38f5e158d3c840Fred Drake            help = self._long_break_matcher.sub('\n\n', help)
2791d9e4b7de3d15007d5b9e7ac4b38f5e158d3c840Fred Drake            help = help.strip('\n') + '\n'
280bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake        return help
281bd7f818c508248e12f88e51198cb5e9b861dacbfFred Drake
2821d9e4b7de3d15007d5b9e7ac4b38f5e158d3c840Fred Drake    def _join_parts(self, part_strings):
2831d9e4b7de3d15007d5b9e7ac4b38f5e158d3c840Fred Drake        return ''.join([part
2841d9e4b7de3d15007d5b9e7ac4b38f5e158d3c840Fred Drake                        for part in part_strings
2851d9e4b7de3d15007d5b9e7ac4b38f5e158d3c840Fred Drake                        if part and part is not SUPPRESS])
2865e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
2875e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis    def _format_usage(self, usage, actions, groups, prefix):
2885e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis        if prefix is None:
2895e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            prefix = _('usage: ')
2905e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
2915e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis        # if usage is specified, use that
2925e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis        if usage is not None:
2932c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger            usage = usage % dict(prog=self._prog)
2942c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger
2952c2d322884ee72077a256ec3cd0aa9ce3580eedcRaymond Hettinger        # if no optionals or positionals are available, usage is just prog
29680ce6dd5642025f5cdf0ba5556f08df0803f5636Walter Dörwald        elif usage is None and not actions:
2975e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis            usage = '%(prog)s' % dict(prog=self._prog)
2985e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis
29931017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger        # if optionals and positionals are available, calculate usage
3005e1633365d8a48e96dd4f42c4e7c8729bc62c26dMartin v. Löwis        elif usage is None:
30131017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger            prog = '%(prog)s' % dict(prog=self._prog)
30231017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger
30331017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger            # split optionals from positionals
30431017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger            optionals = []
30531017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger            positionals = []
30631017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger            for action in actions:
30731017aed36a5c5b0e4b16ca58bea09c9ce360134Raymond Hettinger                if action.option_strings:
308                    optionals.append(action)
309                else:
310                    positionals.append(action)
311
312            # build full usage string
313            format = self._format_actions_usage
314            action_usage = format(optionals + positionals, groups)
315            usage = ' '.join([s for s in [prog, action_usage] if s])
316
317            # wrap the usage parts if it's too long
318            text_width = self._width - self._current_indent
319            if len(prefix) + len(usage) > text_width:
320
321                # break usage into wrappable parts
322                part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
323                opt_usage = format(optionals, groups)
324                pos_usage = format(positionals, groups)
325                opt_parts = _re.findall(part_regexp, opt_usage)
326                pos_parts = _re.findall(part_regexp, pos_usage)
327                assert ' '.join(opt_parts) == opt_usage
328                assert ' '.join(pos_parts) == pos_usage
329
330                # helper for wrapping lines
331                def get_lines(parts, indent, prefix=None):
332                    lines = []
333                    line = []
334                    if prefix is not None:
335                        line_len = len(prefix) - 1
336                    else:
337                        line_len = len(indent) - 1
338                    for part in parts:
339                        if line_len + 1 + len(part) > text_width:
340                            lines.append(indent + ' '.join(line))
341                            line = []
342                            line_len = len(indent) - 1
343                        line.append(part)
344                        line_len += len(part) + 1
345                    if line:
346                        lines.append(indent + ' '.join(line))
347                    if prefix is not None:
348                        lines[0] = lines[0][len(indent):]
349                    return lines
350
351                # if prog is short, follow it with optionals or positionals
352                if len(prefix) + len(prog) <= 0.75 * text_width:
353                    indent = ' ' * (len(prefix) + len(prog) + 1)
354                    if opt_parts:
355                        lines = get_lines([prog] + opt_parts, indent, prefix)
356                        lines.extend(get_lines(pos_parts, indent))
357                    elif pos_parts:
358                        lines = get_lines([prog] + pos_parts, indent, prefix)
359                    else:
360                        lines = [prog]
361
362                # if prog is long, put it on its own line
363                else:
364                    indent = ' ' * len(prefix)
365                    parts = opt_parts + pos_parts
366                    lines = get_lines(parts, indent)
367                    if len(lines) > 1:
368                        lines = []
369                        lines.extend(get_lines(opt_parts, indent))
370                        lines.extend(get_lines(pos_parts, indent))
371                    lines = [prog] + lines
372
373                # join lines into usage
374                usage = '\n'.join(lines)
375
376        # prefix with 'usage:'
377        return '%s%s\n\n' % (prefix, usage)
378
379    def _format_actions_usage(self, actions, groups):
380        # find group indices and identify actions in groups
381        group_actions = set()
382        inserts = {}
383        for group in groups:
384            try:
385                start = actions.index(group._group_actions[0])
386            except ValueError:
387                continue
388            else:
389                end = start + len(group._group_actions)
390                if actions[start:end] == group._group_actions:
391                    for action in group._group_actions:
392                        group_actions.add(action)
393                    if not group.required:
394                        if start in inserts:
395                            inserts[start] += ' ['
396                        else:
397                            inserts[start] = '['
398                        inserts[end] = ']'
399                    else:
400                        if start in inserts:
401                            inserts[start] += ' ('
402                        else:
403                            inserts[start] = '('
404                        inserts[end] = ')'
405                    for i in range(start + 1, end):
406                        inserts[i] = '|'
407
408        # collect all actions format strings
409        parts = []
410        for i, action in enumerate(actions):
411
412            # suppressed arguments are marked with None
413            # remove | separators for suppressed arguments
414            if action.help is SUPPRESS:
415                parts.append(None)
416                if inserts.get(i) == '|':
417                    inserts.pop(i)
418                elif inserts.get(i + 1) == '|':
419                    inserts.pop(i + 1)
420
421            # produce all arg strings
422            elif not action.option_strings:
423                default = self._get_default_metavar_for_positional(action)
424                part = self._format_args(action, default)
425
426                # if it's in a group, strip the outer []
427                if action in group_actions:
428                    if part[0] == '[' and part[-1] == ']':
429                        part = part[1:-1]
430
431                # add the action string to the list
432                parts.append(part)
433
434            # produce the first way to invoke the option in brackets
435            else:
436                option_string = action.option_strings[0]
437
438                # if the Optional doesn't take a value, format is:
439                #    -s or --long
440                if action.nargs == 0:
441                    part = '%s' % option_string
442
443                # if the Optional takes a value, format is:
444                #    -s ARGS or --long ARGS
445                else:
446                    default = self._get_default_metavar_for_optional(action)
447                    args_string = self._format_args(action, default)
448                    part = '%s %s' % (option_string, args_string)
449
450                # make it look optional if it's not required or in a group
451                if not action.required and action not in group_actions:
452                    part = '[%s]' % part
453
454                # add the action string to the list
455                parts.append(part)
456
457        # insert things at the necessary indices
458        for i in sorted(inserts, reverse=True):
459            parts[i:i] = [inserts[i]]
460
461        # join all the action items with spaces
462        text = ' '.join([item for item in parts if item is not None])
463
464        # clean up separators for mutually exclusive groups
465        open = r'[\[(]'
466        close = r'[\])]'
467        text = _re.sub(r'(%s) ' % open, r'\1', text)
468        text = _re.sub(r' (%s)' % close, r'\1', text)
469        text = _re.sub(r'%s *%s' % (open, close), r'', text)
470        text = _re.sub(r'\(([^|]*)\)', r'\1', text)
471        text = text.strip()
472
473        # return the text
474        return text
475
476    def _format_text(self, text):
477        if '%(prog)' in text:
478            text = text % dict(prog=self._prog)
479        text_width = self._width - self._current_indent
480        indent = ' ' * self._current_indent
481        return self._fill_text(text, text_width, indent) + '\n\n'
482
483    def _format_action(self, action):
484        # determine the required width and the entry label
485        help_position = min(self._action_max_length + 2,
486                            self._max_help_position)
487        help_width = self._width - help_position
488        action_width = help_position - self._current_indent - 2
489        action_header = self._format_action_invocation(action)
490
491        # ho nelp; start on same line and add a final newline
492        if not action.help:
493            tup = self._current_indent, '', action_header
494            action_header = '%*s%s\n' % tup
495
496        # short action name; start on the same line and pad two spaces
497        elif len(action_header) <= action_width:
498            tup = self._current_indent, '', action_width, action_header
499            action_header = '%*s%-*s  ' % tup
500            indent_first = 0
501
502        # long action name; start on the next line
503        else:
504            tup = self._current_indent, '', action_header
505            action_header = '%*s%s\n' % tup
506            indent_first = help_position
507
508        # collect the pieces of the action help
509        parts = [action_header]
510
511        # if there was help for the action, add lines of help text
512        if action.help:
513            help_text = self._expand_help(action)
514            help_lines = self._split_lines(help_text, help_width)
515            parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
516            for line in help_lines[1:]:
517                parts.append('%*s%s\n' % (help_position, '', line))
518
519        # or add a newline if the description doesn't end with one
520        elif not action_header.endswith('\n'):
521            parts.append('\n')
522
523        # if there are any sub-actions, add their help as well
524        for subaction in self._iter_indented_subactions(action):
525            parts.append(self._format_action(subaction))
526
527        # return a single string
528        return self._join_parts(parts)
529
530    def _format_action_invocation(self, action):
531        if not action.option_strings:
532            default = self._get_default_metavar_for_positional(action)
533            metavar, = self._metavar_formatter(action, default)(1)
534            return metavar
535
536        else:
537            parts = []
538
539            # if the Optional doesn't take a value, format is:
540            #    -s, --long
541            if action.nargs == 0:
542                parts.extend(action.option_strings)
543
544            # if the Optional takes a value, format is:
545            #    -s ARGS, --long ARGS
546            else:
547                default = self._get_default_metavar_for_optional(action)
548                args_string = self._format_args(action, default)
549                for option_string in action.option_strings:
550                    parts.append('%s %s' % (option_string, args_string))
551
552            return ', '.join(parts)
553
554    def _metavar_formatter(self, action, default_metavar):
555        if action.metavar is not None:
556            result = action.metavar
557        elif action.choices is not None:
558            choice_strs = [str(choice) for choice in action.choices]
559            result = '{%s}' % ','.join(choice_strs)
560        else:
561            result = default_metavar
562
563        def format(tuple_size):
564            if isinstance(result, tuple):
565                return result
566            else:
567                return (result, ) * tuple_size
568        return format
569
570    def _format_args(self, action, default_metavar):
571        get_metavar = self._metavar_formatter(action, default_metavar)
572        if action.nargs is None:
573            result = '%s' % get_metavar(1)
574        elif action.nargs == OPTIONAL:
575            result = '[%s]' % get_metavar(1)
576        elif action.nargs == ZERO_OR_MORE:
577            result = '[%s [%s ...]]' % get_metavar(2)
578        elif action.nargs == ONE_OR_MORE:
579            result = '%s [%s ...]' % get_metavar(2)
580        elif action.nargs == REMAINDER:
581            result = '...'
582        elif action.nargs == PARSER:
583            result = '%s ...' % get_metavar(1)
584        else:
585            formats = ['%s' for _ in range(action.nargs)]
586            result = ' '.join(formats) % get_metavar(action.nargs)
587        return result
588
589    def _expand_help(self, action):
590        params = dict(vars(action), prog=self._prog)
591        for name in list(params):
592            if params[name] is SUPPRESS:
593                del params[name]
594        for name in list(params):
595            if hasattr(params[name], '__name__'):
596                params[name] = params[name].__name__
597        if params.get('choices') is not None:
598            choices_str = ', '.join([str(c) for c in params['choices']])
599            params['choices'] = choices_str
600        return self._get_help_string(action) % params
601
602    def _iter_indented_subactions(self, action):
603        try:
604            get_subactions = action._get_subactions
605        except AttributeError:
606            pass
607        else:
608            self._indent()
609            for subaction in get_subactions():
610                yield subaction
611            self._dedent()
612
613    def _split_lines(self, text, width):
614        text = self._whitespace_matcher.sub(' ', text).strip()
615        return _textwrap.wrap(text, width)
616
617    def _fill_text(self, text, width, indent):
618        text = self._whitespace_matcher.sub(' ', text).strip()
619        return _textwrap.fill(text, width, initial_indent=indent,
620                                           subsequent_indent=indent)
621
622    def _get_help_string(self, action):
623        return action.help
624
625    def _get_default_metavar_for_optional(self, action):
626        return action.dest.upper()
627
628    def _get_default_metavar_for_positional(self, action):
629        return action.dest
630
631
632class RawDescriptionHelpFormatter(HelpFormatter):
633    """Help message formatter which retains any formatting in descriptions.
634
635    Only the name of this class is considered a public API. All the methods
636    provided by the class are considered an implementation detail.
637    """
638
639    def _fill_text(self, text, width, indent):
640        return ''.join(indent + line for line in text.splitlines(keepends=True))
641
642
643class RawTextHelpFormatter(RawDescriptionHelpFormatter):
644    """Help message formatter which retains formatting of all help text.
645
646    Only the name of this class is considered a public API. All the methods
647    provided by the class are considered an implementation detail.
648    """
649
650    def _split_lines(self, text, width):
651        return text.splitlines()
652
653
654class ArgumentDefaultsHelpFormatter(HelpFormatter):
655    """Help message formatter which adds default values to argument help.
656
657    Only the name of this class is considered a public API. All the methods
658    provided by the class are considered an implementation detail.
659    """
660
661    def _get_help_string(self, action):
662        help = action.help
663        if '%(default)' not in action.help:
664            if action.default is not SUPPRESS:
665                defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
666                if action.option_strings or action.nargs in defaulting_nargs:
667                    help += ' (default: %(default)s)'
668        return help
669
670
671class MetavarTypeHelpFormatter(HelpFormatter):
672    """Help message formatter which uses the argument 'type' as the default
673    metavar value (instead of the argument 'dest')
674
675    Only the name of this class is considered a public API. All the methods
676    provided by the class are considered an implementation detail.
677    """
678
679    def _get_default_metavar_for_optional(self, action):
680        return action.type.__name__
681
682    def _get_default_metavar_for_positional(self, action):
683        return action.type.__name__
684
685
686
687# =====================
688# Options and Arguments
689# =====================
690
691def _get_action_name(argument):
692    if argument is None:
693        return None
694    elif argument.option_strings:
695        return  '/'.join(argument.option_strings)
696    elif argument.metavar not in (None, SUPPRESS):
697        return argument.metavar
698    elif argument.dest not in (None, SUPPRESS):
699        return argument.dest
700    else:
701        return None
702
703
704class ArgumentError(Exception):
705    """An error from creating or using an argument (optional or positional).
706
707    The string value of this exception is the message, augmented with
708    information about the argument that caused it.
709    """
710
711    def __init__(self, argument, message):
712        self.argument_name = _get_action_name(argument)
713        self.message = message
714
715    def __str__(self):
716        if self.argument_name is None:
717            format = '%(message)s'
718        else:
719            format = 'argument %(argument_name)s: %(message)s'
720        return format % dict(message=self.message,
721                             argument_name=self.argument_name)
722
723
724class ArgumentTypeError(Exception):
725    """An error from trying to convert a command line string to a type."""
726    pass
727
728
729# ==============
730# Action classes
731# ==============
732
733class Action(_AttributeHolder):
734    """Information about how to convert command line strings to Python objects.
735
736    Action objects are used by an ArgumentParser to represent the information
737    needed to parse a single argument from one or more strings from the
738    command line. The keyword arguments to the Action constructor are also
739    all attributes of Action instances.
740
741    Keyword Arguments:
742
743        - option_strings -- A list of command-line option strings which
744            should be associated with this action.
745
746        - dest -- The name of the attribute to hold the created object(s)
747
748        - nargs -- The number of command-line arguments that should be
749            consumed. By default, one argument will be consumed and a single
750            value will be produced.  Other values include:
751                - N (an integer) consumes N arguments (and produces a list)
752                - '?' consumes zero or one arguments
753                - '*' consumes zero or more arguments (and produces a list)
754                - '+' consumes one or more arguments (and produces a list)
755            Note that the difference between the default and nargs=1 is that
756            with the default, a single value will be produced, while with
757            nargs=1, a list containing a single value will be produced.
758
759        - const -- The value to be produced if the option is specified and the
760            option uses an action that takes no values.
761
762        - default -- The value to be produced if the option is not specified.
763
764        - type -- A callable that accepts a single string argument, and
765            returns the converted value.  The standard Python types str, int,
766            float, and complex are useful examples of such callables.  If None,
767            str is used.
768
769        - choices -- A container of values that should be allowed. If not None,
770            after a command-line argument has been converted to the appropriate
771            type, an exception will be raised if it is not a member of this
772            collection.
773
774        - required -- True if the action must always be specified at the
775            command line. This is only meaningful for optional command-line
776            arguments.
777
778        - help -- The help string describing the argument.
779
780        - metavar -- The name to be used for the option's argument with the
781            help string. If None, the 'dest' value will be used as the name.
782    """
783
784    def __init__(self,
785                 option_strings,
786                 dest,
787                 nargs=None,
788                 const=None,
789                 default=None,
790                 type=None,
791                 choices=None,
792                 required=False,
793                 help=None,
794                 metavar=None):
795        self.option_strings = option_strings
796        self.dest = dest
797        self.nargs = nargs
798        self.const = const
799        self.default = default
800        self.type = type
801        self.choices = choices
802        self.required = required
803        self.help = help
804        self.metavar = metavar
805
806    def _get_kwargs(self):
807        names = [
808            'option_strings',
809            'dest',
810            'nargs',
811            'const',
812            'default',
813            'type',
814            'choices',
815            'help',
816            'metavar',
817        ]
818        return [(name, getattr(self, name)) for name in names]
819
820    def __call__(self, parser, namespace, values, option_string=None):
821        raise NotImplementedError(_('.__call__() not defined'))
822
823
824class _StoreAction(Action):
825
826    def __init__(self,
827                 option_strings,
828                 dest,
829                 nargs=None,
830                 const=None,
831                 default=None,
832                 type=None,
833                 choices=None,
834                 required=False,
835                 help=None,
836                 metavar=None):
837        if nargs == 0:
838            raise ValueError('nargs for store actions must be > 0; if you '
839                             'have nothing to store, actions such as store '
840                             'true or store const may be more appropriate')
841        if const is not None and nargs != OPTIONAL:
842            raise ValueError('nargs must be %r to supply const' % OPTIONAL)
843        super(_StoreAction, self).__init__(
844            option_strings=option_strings,
845            dest=dest,
846            nargs=nargs,
847            const=const,
848            default=default,
849            type=type,
850            choices=choices,
851            required=required,
852            help=help,
853            metavar=metavar)
854
855    def __call__(self, parser, namespace, values, option_string=None):
856        setattr(namespace, self.dest, values)
857
858
859class _StoreConstAction(Action):
860
861    def __init__(self,
862                 option_strings,
863                 dest,
864                 const,
865                 default=None,
866                 required=False,
867                 help=None,
868                 metavar=None):
869        super(_StoreConstAction, self).__init__(
870            option_strings=option_strings,
871            dest=dest,
872            nargs=0,
873            const=const,
874            default=default,
875            required=required,
876            help=help)
877
878    def __call__(self, parser, namespace, values, option_string=None):
879        setattr(namespace, self.dest, self.const)
880
881
882class _StoreTrueAction(_StoreConstAction):
883
884    def __init__(self,
885                 option_strings,
886                 dest,
887                 default=False,
888                 required=False,
889                 help=None):
890        super(_StoreTrueAction, self).__init__(
891            option_strings=option_strings,
892            dest=dest,
893            const=True,
894            default=default,
895            required=required,
896            help=help)
897
898
899class _StoreFalseAction(_StoreConstAction):
900
901    def __init__(self,
902                 option_strings,
903                 dest,
904                 default=True,
905                 required=False,
906                 help=None):
907        super(_StoreFalseAction, self).__init__(
908            option_strings=option_strings,
909            dest=dest,
910            const=False,
911            default=default,
912            required=required,
913            help=help)
914
915
916class _AppendAction(Action):
917
918    def __init__(self,
919                 option_strings,
920                 dest,
921                 nargs=None,
922                 const=None,
923                 default=None,
924                 type=None,
925                 choices=None,
926                 required=False,
927                 help=None,
928                 metavar=None):
929        if nargs == 0:
930            raise ValueError('nargs for append actions must be > 0; if arg '
931                             'strings are not supplying the value to append, '
932                             'the append const action may be more appropriate')
933        if const is not None and nargs != OPTIONAL:
934            raise ValueError('nargs must be %r to supply const' % OPTIONAL)
935        super(_AppendAction, self).__init__(
936            option_strings=option_strings,
937            dest=dest,
938            nargs=nargs,
939            const=const,
940            default=default,
941            type=type,
942            choices=choices,
943            required=required,
944            help=help,
945            metavar=metavar)
946
947    def __call__(self, parser, namespace, values, option_string=None):
948        items = _copy.copy(_ensure_value(namespace, self.dest, []))
949        items.append(values)
950        setattr(namespace, self.dest, items)
951
952
953class _AppendConstAction(Action):
954
955    def __init__(self,
956                 option_strings,
957                 dest,
958                 const,
959                 default=None,
960                 required=False,
961                 help=None,
962                 metavar=None):
963        super(_AppendConstAction, self).__init__(
964            option_strings=option_strings,
965            dest=dest,
966            nargs=0,
967            const=const,
968            default=default,
969            required=required,
970            help=help,
971            metavar=metavar)
972
973    def __call__(self, parser, namespace, values, option_string=None):
974        items = _copy.copy(_ensure_value(namespace, self.dest, []))
975        items.append(self.const)
976        setattr(namespace, self.dest, items)
977
978
979class _CountAction(Action):
980
981    def __init__(self,
982                 option_strings,
983                 dest,
984                 default=None,
985                 required=False,
986                 help=None):
987        super(_CountAction, self).__init__(
988            option_strings=option_strings,
989            dest=dest,
990            nargs=0,
991            default=default,
992            required=required,
993            help=help)
994
995    def __call__(self, parser, namespace, values, option_string=None):
996        new_count = _ensure_value(namespace, self.dest, 0) + 1
997        setattr(namespace, self.dest, new_count)
998
999
1000class _HelpAction(Action):
1001
1002    def __init__(self,
1003                 option_strings,
1004                 dest=SUPPRESS,
1005                 default=SUPPRESS,
1006                 help=None):
1007        super(_HelpAction, self).__init__(
1008            option_strings=option_strings,
1009            dest=dest,
1010            default=default,
1011            nargs=0,
1012            help=help)
1013
1014    def __call__(self, parser, namespace, values, option_string=None):
1015        parser.print_help()
1016        parser.exit()
1017
1018
1019class _VersionAction(Action):
1020
1021    def __init__(self,
1022                 option_strings,
1023                 version=None,
1024                 dest=SUPPRESS,
1025                 default=SUPPRESS,
1026                 help="show program's version number and exit"):
1027        super(_VersionAction, self).__init__(
1028            option_strings=option_strings,
1029            dest=dest,
1030            default=default,
1031            nargs=0,
1032            help=help)
1033        self.version = version
1034
1035    def __call__(self, parser, namespace, values, option_string=None):
1036        version = self.version
1037        if version is None:
1038            version = parser.version
1039        formatter = parser._get_formatter()
1040        formatter.add_text(version)
1041        parser.exit(message=formatter.format_help())
1042
1043
1044class _SubParsersAction(Action):
1045
1046    class _ChoicesPseudoAction(Action):
1047
1048        def __init__(self, name, aliases, help):
1049            metavar = dest = name
1050            if aliases:
1051                metavar += ' (%s)' % ', '.join(aliases)
1052            sup = super(_SubParsersAction._ChoicesPseudoAction, self)
1053            sup.__init__(option_strings=[], dest=dest, help=help,
1054                         metavar=metavar)
1055
1056    def __init__(self,
1057                 option_strings,
1058                 prog,
1059                 parser_class,
1060                 dest=SUPPRESS,
1061                 help=None,
1062                 metavar=None):
1063
1064        self._prog_prefix = prog
1065        self._parser_class = parser_class
1066        self._name_parser_map = _collections.OrderedDict()
1067        self._choices_actions = []
1068
1069        super(_SubParsersAction, self).__init__(
1070            option_strings=option_strings,
1071            dest=dest,
1072            nargs=PARSER,
1073            choices=self._name_parser_map,
1074            help=help,
1075            metavar=metavar)
1076
1077    def add_parser(self, name, **kwargs):
1078        # set prog from the existing prefix
1079        if kwargs.get('prog') is None:
1080            kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1081
1082        aliases = kwargs.pop('aliases', ())
1083
1084        # create a pseudo-action to hold the choice help
1085        if 'help' in kwargs:
1086            help = kwargs.pop('help')
1087            choice_action = self._ChoicesPseudoAction(name, aliases, help)
1088            self._choices_actions.append(choice_action)
1089
1090        # create the parser and add it to the map
1091        parser = self._parser_class(**kwargs)
1092        self._name_parser_map[name] = parser
1093
1094        # make parser available under aliases also
1095        for alias in aliases:
1096            self._name_parser_map[alias] = parser
1097
1098        return parser
1099
1100    def _get_subactions(self):
1101        return self._choices_actions
1102
1103    def __call__(self, parser, namespace, values, option_string=None):
1104        parser_name = values[0]
1105        arg_strings = values[1:]
1106
1107        # set the parser name if requested
1108        if self.dest is not SUPPRESS:
1109            setattr(namespace, self.dest, parser_name)
1110
1111        # select the parser
1112        try:
1113            parser = self._name_parser_map[parser_name]
1114        except KeyError:
1115            args = {'parser_name': parser_name,
1116                    'choices': ', '.join(self._name_parser_map)}
1117            msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
1118            raise ArgumentError(self, msg)
1119
1120        # parse all the remaining options into the namespace
1121        # store any unrecognized options on the object, so that the top
1122        # level parser can decide what to do with them
1123        namespace, arg_strings = parser.parse_known_args(arg_strings, namespace)
1124        if arg_strings:
1125            vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1126            getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
1127
1128
1129# ==============
1130# Type classes
1131# ==============
1132
1133class FileType(object):
1134    """Factory for creating file object types
1135
1136    Instances of FileType are typically passed as type= arguments to the
1137    ArgumentParser add_argument() method.
1138
1139    Keyword Arguments:
1140        - mode -- A string indicating how the file is to be opened. Accepts the
1141            same values as the builtin open() function.
1142        - bufsize -- The file's desired buffer size. Accepts the same values as
1143            the builtin open() function.
1144    """
1145
1146    def __init__(self, mode='r', bufsize=-1):
1147        self._mode = mode
1148        self._bufsize = bufsize
1149
1150    def __call__(self, string):
1151        # the special argument "-" means sys.std{in,out}
1152        if string == '-':
1153            if 'r' in self._mode:
1154                return _sys.stdin
1155            elif 'w' in self._mode:
1156                return _sys.stdout
1157            else:
1158                msg = _('argument "-" with mode %r') % self._mode
1159                raise ValueError(msg)
1160
1161        # all other arguments are used as file names
1162        try:
1163            return open(string, self._mode, self._bufsize)
1164        except IOError as e:
1165            message = _("can't open '%s': %s")
1166            raise ArgumentTypeError(message % (string, e))
1167
1168    def __repr__(self):
1169        args = self._mode, self._bufsize
1170        args_str = ', '.join(repr(arg) for arg in args if arg != -1)
1171        return '%s(%s)' % (type(self).__name__, args_str)
1172
1173# ===========================
1174# Optional and Positional Parsing
1175# ===========================
1176
1177class Namespace(_AttributeHolder):
1178    """Simple object for storing attributes.
1179
1180    Implements equality by attribute names and values, and provides a simple
1181    string representation.
1182    """
1183
1184    def __init__(self, **kwargs):
1185        for name in kwargs:
1186            setattr(self, name, kwargs[name])
1187
1188    def __eq__(self, other):
1189        return vars(self) == vars(other)
1190
1191    def __ne__(self, other):
1192        return not (self == other)
1193
1194    def __contains__(self, key):
1195        return key in self.__dict__
1196
1197
1198class _ActionsContainer(object):
1199
1200    def __init__(self,
1201                 description,
1202                 prefix_chars,
1203                 argument_default,
1204                 conflict_handler):
1205        super(_ActionsContainer, self).__init__()
1206
1207        self.description = description
1208        self.argument_default = argument_default
1209        self.prefix_chars = prefix_chars
1210        self.conflict_handler = conflict_handler
1211
1212        # set up registries
1213        self._registries = {}
1214
1215        # register actions
1216        self.register('action', None, _StoreAction)
1217        self.register('action', 'store', _StoreAction)
1218        self.register('action', 'store_const', _StoreConstAction)
1219        self.register('action', 'store_true', _StoreTrueAction)
1220        self.register('action', 'store_false', _StoreFalseAction)
1221        self.register('action', 'append', _AppendAction)
1222        self.register('action', 'append_const', _AppendConstAction)
1223        self.register('action', 'count', _CountAction)
1224        self.register('action', 'help', _HelpAction)
1225        self.register('action', 'version', _VersionAction)
1226        self.register('action', 'parsers', _SubParsersAction)
1227
1228        # raise an exception if the conflict handler is invalid
1229        self._get_handler()
1230
1231        # action storage
1232        self._actions = []
1233        self._option_string_actions = {}
1234
1235        # groups
1236        self._action_groups = []
1237        self._mutually_exclusive_groups = []
1238
1239        # defaults storage
1240        self._defaults = {}
1241
1242        # determines whether an "option" looks like a negative number
1243        self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1244
1245        # whether or not there are any optionals that look like negative
1246        # numbers -- uses a list so it can be shared and edited
1247        self._has_negative_number_optionals = []
1248
1249    # ====================
1250    # Registration methods
1251    # ====================
1252    def register(self, registry_name, value, object):
1253        registry = self._registries.setdefault(registry_name, {})
1254        registry[value] = object
1255
1256    def _registry_get(self, registry_name, value, default=None):
1257        return self._registries[registry_name].get(value, default)
1258
1259    # ==================================
1260    # Namespace default accessor methods
1261    # ==================================
1262    def set_defaults(self, **kwargs):
1263        self._defaults.update(kwargs)
1264
1265        # if these defaults match any existing arguments, replace
1266        # the previous default on the object with the new one
1267        for action in self._actions:
1268            if action.dest in kwargs:
1269                action.default = kwargs[action.dest]
1270
1271    def get_default(self, dest):
1272        for action in self._actions:
1273            if action.dest == dest and action.default is not None:
1274                return action.default
1275        return self._defaults.get(dest, None)
1276
1277
1278    # =======================
1279    # Adding argument actions
1280    # =======================
1281    def add_argument(self, *args, **kwargs):
1282        """
1283        add_argument(dest, ..., name=value, ...)
1284        add_argument(option_string, option_string, ..., name=value, ...)
1285        """
1286
1287        # if no positional args are supplied or only one is supplied and
1288        # it doesn't look like an option string, parse a positional
1289        # argument
1290        chars = self.prefix_chars
1291        if not args or len(args) == 1 and args[0][0] not in chars:
1292            if args and 'dest' in kwargs:
1293                raise ValueError('dest supplied twice for positional argument')
1294            kwargs = self._get_positional_kwargs(*args, **kwargs)
1295
1296        # otherwise, we're adding an optional argument
1297        else:
1298            kwargs = self._get_optional_kwargs(*args, **kwargs)
1299
1300        # if no default was supplied, use the parser-level default
1301        if 'default' not in kwargs:
1302            dest = kwargs['dest']
1303            if dest in self._defaults:
1304                kwargs['default'] = self._defaults[dest]
1305            elif self.argument_default is not None:
1306                kwargs['default'] = self.argument_default
1307
1308        # create the action object, and add it to the parser
1309        action_class = self._pop_action_class(kwargs)
1310        if not callable(action_class):
1311            raise ValueError('unknown action "%s"' % (action_class,))
1312        action = action_class(**kwargs)
1313
1314        # raise an error if the action type is not callable
1315        type_func = self._registry_get('type', action.type, action.type)
1316        if not callable(type_func):
1317            raise ValueError('%r is not callable' % (type_func,))
1318
1319        # raise an error if the metavar does not match the type
1320        if hasattr(self, "_get_formatter"):
1321            try:
1322                self._get_formatter()._format_args(action, None)
1323            except TypeError:
1324                raise ValueError("length of metavar tuple does not match nargs")
1325
1326        return self._add_action(action)
1327
1328    def add_argument_group(self, *args, **kwargs):
1329        group = _ArgumentGroup(self, *args, **kwargs)
1330        self._action_groups.append(group)
1331        return group
1332
1333    def add_mutually_exclusive_group(self, **kwargs):
1334        group = _MutuallyExclusiveGroup(self, **kwargs)
1335        self._mutually_exclusive_groups.append(group)
1336        return group
1337
1338    def _add_action(self, action):
1339        # resolve any conflicts
1340        self._check_conflict(action)
1341
1342        # add to actions list
1343        self._actions.append(action)
1344        action.container = self
1345
1346        # index the action by any option strings it has
1347        for option_string in action.option_strings:
1348            self._option_string_actions[option_string] = action
1349
1350        # set the flag if any option strings look like negative numbers
1351        for option_string in action.option_strings:
1352            if self._negative_number_matcher.match(option_string):
1353                if not self._has_negative_number_optionals:
1354                    self._has_negative_number_optionals.append(True)
1355
1356        # return the created action
1357        return action
1358
1359    def _remove_action(self, action):
1360        self._actions.remove(action)
1361
1362    def _add_container_actions(self, container):
1363        # collect groups by titles
1364        title_group_map = {}
1365        for group in self._action_groups:
1366            if group.title in title_group_map:
1367                msg = _('cannot merge actions - two groups are named %r')
1368                raise ValueError(msg % (group.title))
1369            title_group_map[group.title] = group
1370
1371        # map each action to its group
1372        group_map = {}
1373        for group in container._action_groups:
1374
1375            # if a group with the title exists, use that, otherwise
1376            # create a new group matching the container's group
1377            if group.title not in title_group_map:
1378                title_group_map[group.title] = self.add_argument_group(
1379                    title=group.title,
1380                    description=group.description,
1381                    conflict_handler=group.conflict_handler)
1382
1383            # map the actions to their new group
1384            for action in group._group_actions:
1385                group_map[action] = title_group_map[group.title]
1386
1387        # add container's mutually exclusive groups
1388        # NOTE: if add_mutually_exclusive_group ever gains title= and
1389        # description= then this code will need to be expanded as above
1390        for group in container._mutually_exclusive_groups:
1391            mutex_group = self.add_mutually_exclusive_group(
1392                required=group.required)
1393
1394            # map the actions to their new mutex group
1395            for action in group._group_actions:
1396                group_map[action] = mutex_group
1397
1398        # add all actions to this container or their group
1399        for action in container._actions:
1400            group_map.get(action, self)._add_action(action)
1401
1402    def _get_positional_kwargs(self, dest, **kwargs):
1403        # make sure required is not specified
1404        if 'required' in kwargs:
1405            msg = _("'required' is an invalid argument for positionals")
1406            raise TypeError(msg)
1407
1408        # mark positional arguments as required if at least one is
1409        # always required
1410        if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1411            kwargs['required'] = True
1412        if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1413            kwargs['required'] = True
1414
1415        # return the keyword arguments with no option strings
1416        return dict(kwargs, dest=dest, option_strings=[])
1417
1418    def _get_optional_kwargs(self, *args, **kwargs):
1419        # determine short and long option strings
1420        option_strings = []
1421        long_option_strings = []
1422        for option_string in args:
1423            # error on strings that don't start with an appropriate prefix
1424            if not option_string[0] in self.prefix_chars:
1425                args = {'option': option_string,
1426                        'prefix_chars': self.prefix_chars}
1427                msg = _('invalid option string %(option)r: '
1428                        'must start with a character %(prefix_chars)r')
1429                raise ValueError(msg % args)
1430
1431            # strings starting with two prefix characters are long options
1432            option_strings.append(option_string)
1433            if option_string[0] in self.prefix_chars:
1434                if len(option_string) > 1:
1435                    if option_string[1] in self.prefix_chars:
1436                        long_option_strings.append(option_string)
1437
1438        # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1439        dest = kwargs.pop('dest', None)
1440        if dest is None:
1441            if long_option_strings:
1442                dest_option_string = long_option_strings[0]
1443            else:
1444                dest_option_string = option_strings[0]
1445            dest = dest_option_string.lstrip(self.prefix_chars)
1446            if not dest:
1447                msg = _('dest= is required for options like %r')
1448                raise ValueError(msg % option_string)
1449            dest = dest.replace('-', '_')
1450
1451        # return the updated keyword arguments
1452        return dict(kwargs, dest=dest, option_strings=option_strings)
1453
1454    def _pop_action_class(self, kwargs, default=None):
1455        action = kwargs.pop('action', default)
1456        return self._registry_get('action', action, action)
1457
1458    def _get_handler(self):
1459        # determine function from conflict handler string
1460        handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1461        try:
1462            return getattr(self, handler_func_name)
1463        except AttributeError:
1464            msg = _('invalid conflict_resolution value: %r')
1465            raise ValueError(msg % self.conflict_handler)
1466
1467    def _check_conflict(self, action):
1468
1469        # find all options that conflict with this option
1470        confl_optionals = []
1471        for option_string in action.option_strings:
1472            if option_string in self._option_string_actions:
1473                confl_optional = self._option_string_actions[option_string]
1474                confl_optionals.append((option_string, confl_optional))
1475
1476        # resolve any conflicts
1477        if confl_optionals:
1478            conflict_handler = self._get_handler()
1479            conflict_handler(action, confl_optionals)
1480
1481    def _handle_conflict_error(self, action, conflicting_actions):
1482        message = ngettext('conflicting option string: %s',
1483                           'conflicting option strings: %s',
1484                           len(conflicting_actions))
1485        conflict_string = ', '.join([option_string
1486                                     for option_string, action
1487                                     in conflicting_actions])
1488        raise ArgumentError(action, message % conflict_string)
1489
1490    def _handle_conflict_resolve(self, action, conflicting_actions):
1491
1492        # remove all conflicting options
1493        for option_string, action in conflicting_actions:
1494
1495            # remove the conflicting option
1496            action.option_strings.remove(option_string)
1497            self._option_string_actions.pop(option_string, None)
1498
1499            # if the option now has no option string, remove it from the
1500            # container holding it
1501            if not action.option_strings:
1502                action.container._remove_action(action)
1503
1504
1505class _ArgumentGroup(_ActionsContainer):
1506
1507    def __init__(self, container, title=None, description=None, **kwargs):
1508        # add any missing keyword arguments by checking the container
1509        update = kwargs.setdefault
1510        update('conflict_handler', container.conflict_handler)
1511        update('prefix_chars', container.prefix_chars)
1512        update('argument_default', container.argument_default)
1513        super_init = super(_ArgumentGroup, self).__init__
1514        super_init(description=description, **kwargs)
1515
1516        # group attributes
1517        self.title = title
1518        self._group_actions = []
1519
1520        # share most attributes with the container
1521        self._registries = container._registries
1522        self._actions = container._actions
1523        self._option_string_actions = container._option_string_actions
1524        self._defaults = container._defaults
1525        self._has_negative_number_optionals = \
1526            container._has_negative_number_optionals
1527        self._mutually_exclusive_groups = container._mutually_exclusive_groups
1528
1529    def _add_action(self, action):
1530        action = super(_ArgumentGroup, self)._add_action(action)
1531        self._group_actions.append(action)
1532        return action
1533
1534    def _remove_action(self, action):
1535        super(_ArgumentGroup, self)._remove_action(action)
1536        self._group_actions.remove(action)
1537
1538
1539class _MutuallyExclusiveGroup(_ArgumentGroup):
1540
1541    def __init__(self, container, required=False):
1542        super(_MutuallyExclusiveGroup, self).__init__(container)
1543        self.required = required
1544        self._container = container
1545
1546    def _add_action(self, action):
1547        if action.required:
1548            msg = _('mutually exclusive arguments must be optional')
1549            raise ValueError(msg)
1550        action = self._container._add_action(action)
1551        self._group_actions.append(action)
1552        return action
1553
1554    def _remove_action(self, action):
1555        self._container._remove_action(action)
1556        self._group_actions.remove(action)
1557
1558
1559class ArgumentParser(_AttributeHolder, _ActionsContainer):
1560    """Object for parsing command line strings into Python objects.
1561
1562    Keyword Arguments:
1563        - prog -- The name of the program (default: sys.argv[0])
1564        - usage -- A usage message (default: auto-generated from arguments)
1565        - description -- A description of what the program does
1566        - epilog -- Text following the argument descriptions
1567        - parents -- Parsers whose arguments should be copied into this one
1568        - formatter_class -- HelpFormatter class for printing help messages
1569        - prefix_chars -- Characters that prefix optional arguments
1570        - fromfile_prefix_chars -- Characters that prefix files containing
1571            additional arguments
1572        - argument_default -- The default value for all arguments
1573        - conflict_handler -- String indicating how to handle conflicts
1574        - add_help -- Add a -h/-help option
1575    """
1576
1577    def __init__(self,
1578                 prog=None,
1579                 usage=None,
1580                 description=None,
1581                 epilog=None,
1582                 parents=[],
1583                 formatter_class=HelpFormatter,
1584                 prefix_chars='-',
1585                 fromfile_prefix_chars=None,
1586                 argument_default=None,
1587                 conflict_handler='error',
1588                 add_help=True):
1589
1590        superinit = super(ArgumentParser, self).__init__
1591        superinit(description=description,
1592                  prefix_chars=prefix_chars,
1593                  argument_default=argument_default,
1594                  conflict_handler=conflict_handler)
1595
1596        # default setting for prog
1597        if prog is None:
1598            prog = _os.path.basename(_sys.argv[0])
1599
1600        self.prog = prog
1601        self.usage = usage
1602        self.epilog = epilog
1603        self.formatter_class = formatter_class
1604        self.fromfile_prefix_chars = fromfile_prefix_chars
1605        self.add_help = add_help
1606
1607        add_group = self.add_argument_group
1608        self._positionals = add_group(_('positional arguments'))
1609        self._optionals = add_group(_('optional arguments'))
1610        self._subparsers = None
1611
1612        # register types
1613        def identity(string):
1614            return string
1615        self.register('type', None, identity)
1616
1617        # add help argument if necessary
1618        # (using explicit default to override global argument_default)
1619        default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
1620        if self.add_help:
1621            self.add_argument(
1622                default_prefix+'h', default_prefix*2+'help',
1623                action='help', default=SUPPRESS,
1624                help=_('show this help message and exit'))
1625
1626        # add parent arguments and defaults
1627        for parent in parents:
1628            self._add_container_actions(parent)
1629            try:
1630                defaults = parent._defaults
1631            except AttributeError:
1632                pass
1633            else:
1634                self._defaults.update(defaults)
1635
1636    # =======================
1637    # Pretty __repr__ methods
1638    # =======================
1639    def _get_kwargs(self):
1640        names = [
1641            'prog',
1642            'usage',
1643            'description',
1644            'formatter_class',
1645            'conflict_handler',
1646            'add_help',
1647        ]
1648        return [(name, getattr(self, name)) for name in names]
1649
1650    # ==================================
1651    # Optional/Positional adding methods
1652    # ==================================
1653    def add_subparsers(self, **kwargs):
1654        if self._subparsers is not None:
1655            self.error(_('cannot have multiple subparser arguments'))
1656
1657        # add the parser class to the arguments if it's not present
1658        kwargs.setdefault('parser_class', type(self))
1659
1660        if 'title' in kwargs or 'description' in kwargs:
1661            title = _(kwargs.pop('title', 'subcommands'))
1662            description = _(kwargs.pop('description', None))
1663            self._subparsers = self.add_argument_group(title, description)
1664        else:
1665            self._subparsers = self._positionals
1666
1667        # prog defaults to the usage message of this parser, skipping
1668        # optional arguments and with no "usage:" prefix
1669        if kwargs.get('prog') is None:
1670            formatter = self._get_formatter()
1671            positionals = self._get_positional_actions()
1672            groups = self._mutually_exclusive_groups
1673            formatter.add_usage(self.usage, positionals, groups, '')
1674            kwargs['prog'] = formatter.format_help().strip()
1675
1676        # create the parsers action and add it to the positionals list
1677        parsers_class = self._pop_action_class(kwargs, 'parsers')
1678        action = parsers_class(option_strings=[], **kwargs)
1679        self._subparsers._add_action(action)
1680
1681        # return the created parsers action
1682        return action
1683
1684    def _add_action(self, action):
1685        if action.option_strings:
1686            self._optionals._add_action(action)
1687        else:
1688            self._positionals._add_action(action)
1689        return action
1690
1691    def _get_optional_actions(self):
1692        return [action
1693                for action in self._actions
1694                if action.option_strings]
1695
1696    def _get_positional_actions(self):
1697        return [action
1698                for action in self._actions
1699                if not action.option_strings]
1700
1701    # =====================================
1702    # Command line argument parsing methods
1703    # =====================================
1704    def parse_args(self, args=None, namespace=None):
1705        args, argv = self.parse_known_args(args, namespace)
1706        if argv:
1707            msg = _('unrecognized arguments: %s')
1708            self.error(msg % ' '.join(argv))
1709        return args
1710
1711    def parse_known_args(self, args=None, namespace=None):
1712        if args is None:
1713            # args default to the system args
1714            args = _sys.argv[1:]
1715        else:
1716            # make sure that args are mutable
1717            args = list(args)
1718
1719        # default Namespace built from parser defaults
1720        if namespace is None:
1721            namespace = Namespace()
1722
1723        # add any action defaults that aren't present
1724        for action in self._actions:
1725            if action.dest is not SUPPRESS:
1726                if not hasattr(namespace, action.dest):
1727                    if action.default is not SUPPRESS:
1728                        setattr(namespace, action.dest, action.default)
1729
1730        # add any parser defaults that aren't present
1731        for dest in self._defaults:
1732            if not hasattr(namespace, dest):
1733                setattr(namespace, dest, self._defaults[dest])
1734
1735        # parse the arguments and exit if there are any errors
1736        try:
1737            namespace, args = self._parse_known_args(args, namespace)
1738            if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1739                args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1740                delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1741            return namespace, args
1742        except ArgumentError:
1743            err = _sys.exc_info()[1]
1744            self.error(str(err))
1745
1746    def _parse_known_args(self, arg_strings, namespace):
1747        # replace arg strings that are file references
1748        if self.fromfile_prefix_chars is not None:
1749            arg_strings = self._read_args_from_files(arg_strings)
1750
1751        # map all mutually exclusive arguments to the other arguments
1752        # they can't occur with
1753        action_conflicts = {}
1754        for mutex_group in self._mutually_exclusive_groups:
1755            group_actions = mutex_group._group_actions
1756            for i, mutex_action in enumerate(mutex_group._group_actions):
1757                conflicts = action_conflicts.setdefault(mutex_action, [])
1758                conflicts.extend(group_actions[:i])
1759                conflicts.extend(group_actions[i + 1:])
1760
1761        # find all option indices, and determine the arg_string_pattern
1762        # which has an 'O' if there is an option at an index,
1763        # an 'A' if there is an argument, or a '-' if there is a '--'
1764        option_string_indices = {}
1765        arg_string_pattern_parts = []
1766        arg_strings_iter = iter(arg_strings)
1767        for i, arg_string in enumerate(arg_strings_iter):
1768
1769            # all args after -- are non-options
1770            if arg_string == '--':
1771                arg_string_pattern_parts.append('-')
1772                for arg_string in arg_strings_iter:
1773                    arg_string_pattern_parts.append('A')
1774
1775            # otherwise, add the arg to the arg strings
1776            # and note the index if it was an option
1777            else:
1778                option_tuple = self._parse_optional(arg_string)
1779                if option_tuple is None:
1780                    pattern = 'A'
1781                else:
1782                    option_string_indices[i] = option_tuple
1783                    pattern = 'O'
1784                arg_string_pattern_parts.append(pattern)
1785
1786        # join the pieces together to form the pattern
1787        arg_strings_pattern = ''.join(arg_string_pattern_parts)
1788
1789        # converts arg strings to the appropriate and then takes the action
1790        seen_actions = set()
1791        seen_non_default_actions = set()
1792
1793        def take_action(action, argument_strings, option_string=None):
1794            seen_actions.add(action)
1795            argument_values = self._get_values(action, argument_strings)
1796
1797            # error if this argument is not allowed with other previously
1798            # seen arguments, assuming that actions that use the default
1799            # value don't really count as "present"
1800            if argument_values is not action.default:
1801                seen_non_default_actions.add(action)
1802                for conflict_action in action_conflicts.get(action, []):
1803                    if conflict_action in seen_non_default_actions:
1804                        msg = _('not allowed with argument %s')
1805                        action_name = _get_action_name(conflict_action)
1806                        raise ArgumentError(action, msg % action_name)
1807
1808            # take the action if we didn't receive a SUPPRESS value
1809            # (e.g. from a default)
1810            if argument_values is not SUPPRESS:
1811                action(self, namespace, argument_values, option_string)
1812
1813        # function to convert arg_strings into an optional action
1814        def consume_optional(start_index):
1815
1816            # get the optional identified at this index
1817            option_tuple = option_string_indices[start_index]
1818            action, option_string, explicit_arg = option_tuple
1819
1820            # identify additional optionals in the same arg string
1821            # (e.g. -xyz is the same as -x -y -z if no args are required)
1822            match_argument = self._match_argument
1823            action_tuples = []
1824            while True:
1825
1826                # if we found no optional action, skip it
1827                if action is None:
1828                    extras.append(arg_strings[start_index])
1829                    return start_index + 1
1830
1831                # if there is an explicit argument, try to match the
1832                # optional's string arguments to only this
1833                if explicit_arg is not None:
1834                    arg_count = match_argument(action, 'A')
1835
1836                    # if the action is a single-dash option and takes no
1837                    # arguments, try to parse more single-dash options out
1838                    # of the tail of the option string
1839                    chars = self.prefix_chars
1840                    if arg_count == 0 and option_string[1] not in chars:
1841                        action_tuples.append((action, [], option_string))
1842                        char = option_string[0]
1843                        option_string = char + explicit_arg[0]
1844                        new_explicit_arg = explicit_arg[1:] or None
1845                        optionals_map = self._option_string_actions
1846                        if option_string in optionals_map:
1847                            action = optionals_map[option_string]
1848                            explicit_arg = new_explicit_arg
1849                        else:
1850                            msg = _('ignored explicit argument %r')
1851                            raise ArgumentError(action, msg % explicit_arg)
1852
1853                    # if the action expect exactly one argument, we've
1854                    # successfully matched the option; exit the loop
1855                    elif arg_count == 1:
1856                        stop = start_index + 1
1857                        args = [explicit_arg]
1858                        action_tuples.append((action, args, option_string))
1859                        break
1860
1861                    # error if a double-dash option did not use the
1862                    # explicit argument
1863                    else:
1864                        msg = _('ignored explicit argument %r')
1865                        raise ArgumentError(action, msg % explicit_arg)
1866
1867                # if there is no explicit argument, try to match the
1868                # optional's string arguments with the following strings
1869                # if successful, exit the loop
1870                else:
1871                    start = start_index + 1
1872                    selected_patterns = arg_strings_pattern[start:]
1873                    arg_count = match_argument(action, selected_patterns)
1874                    stop = start + arg_count
1875                    args = arg_strings[start:stop]
1876                    action_tuples.append((action, args, option_string))
1877                    break
1878
1879            # add the Optional to the list and return the index at which
1880            # the Optional's string args stopped
1881            assert action_tuples
1882            for action, args, option_string in action_tuples:
1883                take_action(action, args, option_string)
1884            return stop
1885
1886        # the list of Positionals left to be parsed; this is modified
1887        # by consume_positionals()
1888        positionals = self._get_positional_actions()
1889
1890        # function to convert arg_strings into positional actions
1891        def consume_positionals(start_index):
1892            # match as many Positionals as possible
1893            match_partial = self._match_arguments_partial
1894            selected_pattern = arg_strings_pattern[start_index:]
1895            arg_counts = match_partial(positionals, selected_pattern)
1896
1897            # slice off the appropriate arg strings for each Positional
1898            # and add the Positional and its args to the list
1899            for action, arg_count in zip(positionals, arg_counts):
1900                args = arg_strings[start_index: start_index + arg_count]
1901                start_index += arg_count
1902                take_action(action, args)
1903
1904            # slice off the Positionals that we just parsed and return the
1905            # index at which the Positionals' string args stopped
1906            positionals[:] = positionals[len(arg_counts):]
1907            return start_index
1908
1909        # consume Positionals and Optionals alternately, until we have
1910        # passed the last option string
1911        extras = []
1912        start_index = 0
1913        if option_string_indices:
1914            max_option_string_index = max(option_string_indices)
1915        else:
1916            max_option_string_index = -1
1917        while start_index <= max_option_string_index:
1918
1919            # consume any Positionals preceding the next option
1920            next_option_string_index = min([
1921                index
1922                for index in option_string_indices
1923                if index >= start_index])
1924            if start_index != next_option_string_index:
1925                positionals_end_index = consume_positionals(start_index)
1926
1927                # only try to parse the next optional if we didn't consume
1928                # the option string during the positionals parsing
1929                if positionals_end_index > start_index:
1930                    start_index = positionals_end_index
1931                    continue
1932                else:
1933                    start_index = positionals_end_index
1934
1935            # if we consumed all the positionals we could and we're not
1936            # at the index of an option string, there were extra arguments
1937            if start_index not in option_string_indices:
1938                strings = arg_strings[start_index:next_option_string_index]
1939                extras.extend(strings)
1940                start_index = next_option_string_index
1941
1942            # consume the next optional and any arguments for it
1943            start_index = consume_optional(start_index)
1944
1945        # consume any positionals following the last Optional
1946        stop_index = consume_positionals(start_index)
1947
1948        # if we didn't consume all the argument strings, there were extras
1949        extras.extend(arg_strings[stop_index:])
1950
1951        # make sure all required actions were present and also convert
1952        # action defaults which were not given as arguments
1953        required_actions = []
1954        for action in self._actions:
1955            if action not in seen_actions:
1956                if action.required:
1957                    required_actions.append(_get_action_name(action))
1958                else:
1959                    # Convert action default now instead of doing it before
1960                    # parsing arguments to avoid calling convert functions
1961                    # twice (which may fail) if the argument was given, but
1962                    # only if it was defined already in the namespace
1963                    if (action.default is not None and
1964                        hasattr(namespace, action.dest) and
1965                        action.default is getattr(namespace, action.dest)):
1966                        setattr(namespace, action.dest,
1967                                self._get_value(action, action.default))
1968
1969        if required_actions:
1970            self.error(_('the following arguments are required: %s') %
1971                       ', '.join(required_actions))
1972
1973        # make sure all required groups had one option present
1974        for group in self._mutually_exclusive_groups:
1975            if group.required:
1976                for action in group._group_actions:
1977                    if action in seen_non_default_actions:
1978                        break
1979
1980                # if no actions were used, report the error
1981                else:
1982                    names = [_get_action_name(action)
1983                             for action in group._group_actions
1984                             if action.help is not SUPPRESS]
1985                    msg = _('one of the arguments %s is required')
1986                    self.error(msg % ' '.join(names))
1987
1988        # return the updated namespace and the extra arguments
1989        return namespace, extras
1990
1991    def _read_args_from_files(self, arg_strings):
1992        # expand arguments referencing files
1993        new_arg_strings = []
1994        for arg_string in arg_strings:
1995
1996            # for regular arguments, just add them back into the list
1997            if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
1998                new_arg_strings.append(arg_string)
1999
2000            # replace arguments referencing files with the file content
2001            else:
2002                try:
2003                    args_file = open(arg_string[1:])
2004                    try:
2005                        arg_strings = []
2006                        for arg_line in args_file.read().splitlines():
2007                            for arg in self.convert_arg_line_to_args(arg_line):
2008                                arg_strings.append(arg)
2009                        arg_strings = self._read_args_from_files(arg_strings)
2010                        new_arg_strings.extend(arg_strings)
2011                    finally:
2012                        args_file.close()
2013                except IOError:
2014                    err = _sys.exc_info()[1]
2015                    self.error(str(err))
2016
2017        # return the modified argument list
2018        return new_arg_strings
2019
2020    def convert_arg_line_to_args(self, arg_line):
2021        return [arg_line]
2022
2023    def _match_argument(self, action, arg_strings_pattern):
2024        # match the pattern for this action to the arg strings
2025        nargs_pattern = self._get_nargs_pattern(action)
2026        match = _re.match(nargs_pattern, arg_strings_pattern)
2027
2028        # raise an exception if we weren't able to find a match
2029        if match is None:
2030            nargs_errors = {
2031                None: _('expected one argument'),
2032                OPTIONAL: _('expected at most one argument'),
2033                ONE_OR_MORE: _('expected at least one argument'),
2034            }
2035            default = ngettext('expected %s argument',
2036                               'expected %s arguments',
2037                               action.nargs) % action.nargs
2038            msg = nargs_errors.get(action.nargs, default)
2039            raise ArgumentError(action, msg)
2040
2041        # return the number of arguments matched
2042        return len(match.group(1))
2043
2044    def _match_arguments_partial(self, actions, arg_strings_pattern):
2045        # progressively shorten the actions list by slicing off the
2046        # final actions until we find a match
2047        result = []
2048        for i in range(len(actions), 0, -1):
2049            actions_slice = actions[:i]
2050            pattern = ''.join([self._get_nargs_pattern(action)
2051                               for action in actions_slice])
2052            match = _re.match(pattern, arg_strings_pattern)
2053            if match is not None:
2054                result.extend([len(string) for string in match.groups()])
2055                break
2056
2057        # return the list of arg string counts
2058        return result
2059
2060    def _parse_optional(self, arg_string):
2061        # if it's an empty string, it was meant to be a positional
2062        if not arg_string:
2063            return None
2064
2065        # if it doesn't start with a prefix, it was meant to be positional
2066        if not arg_string[0] in self.prefix_chars:
2067            return None
2068
2069        # if the option string is present in the parser, return the action
2070        if arg_string in self._option_string_actions:
2071            action = self._option_string_actions[arg_string]
2072            return action, arg_string, None
2073
2074        # if it's just a single character, it was meant to be positional
2075        if len(arg_string) == 1:
2076            return None
2077
2078        # if the option string before the "=" is present, return the action
2079        if '=' in arg_string:
2080            option_string, explicit_arg = arg_string.split('=', 1)
2081            if option_string in self._option_string_actions:
2082                action = self._option_string_actions[option_string]
2083                return action, option_string, explicit_arg
2084
2085        # search through all possible prefixes of the option string
2086        # and all actions in the parser for possible interpretations
2087        option_tuples = self._get_option_tuples(arg_string)
2088
2089        # if multiple actions match, the option string was ambiguous
2090        if len(option_tuples) > 1:
2091            options = ', '.join([option_string
2092                for action, option_string, explicit_arg in option_tuples])
2093            args = {'option': arg_string, 'matches': options}
2094            msg = _('ambiguous option: %(option)s could match %(matches)s')
2095            self.error(msg % args)
2096
2097        # if exactly one action matched, this segmentation is good,
2098        # so return the parsed action
2099        elif len(option_tuples) == 1:
2100            option_tuple, = option_tuples
2101            return option_tuple
2102
2103        # if it was not found as an option, but it looks like a negative
2104        # number, it was meant to be positional
2105        # unless there are negative-number-like options
2106        if self._negative_number_matcher.match(arg_string):
2107            if not self._has_negative_number_optionals:
2108                return None
2109
2110        # if it contains a space, it was meant to be a positional
2111        if ' ' in arg_string:
2112            return None
2113
2114        # it was meant to be an optional but there is no such option
2115        # in this parser (though it might be a valid option in a subparser)
2116        return None, arg_string, None
2117
2118    def _get_option_tuples(self, option_string):
2119        result = []
2120
2121        # option strings starting with two prefix characters are only
2122        # split at the '='
2123        chars = self.prefix_chars
2124        if option_string[0] in chars and option_string[1] in chars:
2125            if '=' in option_string:
2126                option_prefix, explicit_arg = option_string.split('=', 1)
2127            else:
2128                option_prefix = option_string
2129                explicit_arg = None
2130            for option_string in self._option_string_actions:
2131                if option_string.startswith(option_prefix):
2132                    action = self._option_string_actions[option_string]
2133                    tup = action, option_string, explicit_arg
2134                    result.append(tup)
2135
2136        # single character options can be concatenated with their arguments
2137        # but multiple character options always have to have their argument
2138        # separate
2139        elif option_string[0] in chars and option_string[1] not in chars:
2140            option_prefix = option_string
2141            explicit_arg = None
2142            short_option_prefix = option_string[:2]
2143            short_explicit_arg = option_string[2:]
2144
2145            for option_string in self._option_string_actions:
2146                if option_string == short_option_prefix:
2147                    action = self._option_string_actions[option_string]
2148                    tup = action, option_string, short_explicit_arg
2149                    result.append(tup)
2150                elif option_string.startswith(option_prefix):
2151                    action = self._option_string_actions[option_string]
2152                    tup = action, option_string, explicit_arg
2153                    result.append(tup)
2154
2155        # shouldn't ever get here
2156        else:
2157            self.error(_('unexpected option string: %s') % option_string)
2158
2159        # return the collected option tuples
2160        return result
2161
2162    def _get_nargs_pattern(self, action):
2163        # in all examples below, we have to allow for '--' args
2164        # which are represented as '-' in the pattern
2165        nargs = action.nargs
2166
2167        # the default (None) is assumed to be a single argument
2168        if nargs is None:
2169            nargs_pattern = '(-*A-*)'
2170
2171        # allow zero or one arguments
2172        elif nargs == OPTIONAL:
2173            nargs_pattern = '(-*A?-*)'
2174
2175        # allow zero or more arguments
2176        elif nargs == ZERO_OR_MORE:
2177            nargs_pattern = '(-*[A-]*)'
2178
2179        # allow one or more arguments
2180        elif nargs == ONE_OR_MORE:
2181            nargs_pattern = '(-*A[A-]*)'
2182
2183        # allow any number of options or arguments
2184        elif nargs == REMAINDER:
2185            nargs_pattern = '([-AO]*)'
2186
2187        # allow one argument followed by any number of options or arguments
2188        elif nargs == PARSER:
2189            nargs_pattern = '(-*A[-AO]*)'
2190
2191        # all others should be integers
2192        else:
2193            nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2194
2195        # if this is an optional action, -- is not allowed
2196        if action.option_strings:
2197            nargs_pattern = nargs_pattern.replace('-*', '')
2198            nargs_pattern = nargs_pattern.replace('-', '')
2199
2200        # return the pattern
2201        return nargs_pattern
2202
2203    # ========================
2204    # Value conversion methods
2205    # ========================
2206    def _get_values(self, action, arg_strings):
2207        # for everything but PARSER, REMAINDER args, strip out first '--'
2208        if action.nargs not in [PARSER, REMAINDER]:
2209            try:
2210                arg_strings.remove('--')
2211            except ValueError:
2212                pass
2213
2214        # optional argument produces a default when not present
2215        if not arg_strings and action.nargs == OPTIONAL:
2216            if action.option_strings:
2217                value = action.const
2218            else:
2219                value = action.default
2220            if isinstance(value, str):
2221                value = self._get_value(action, value)
2222                self._check_value(action, value)
2223
2224        # when nargs='*' on a positional, if there were no command-line
2225        # args, use the default if it is anything other than None
2226        elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2227              not action.option_strings):
2228            if action.default is not None:
2229                value = action.default
2230            else:
2231                value = arg_strings
2232            self._check_value(action, value)
2233
2234        # single argument or optional argument produces a single value
2235        elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2236            arg_string, = arg_strings
2237            value = self._get_value(action, arg_string)
2238            self._check_value(action, value)
2239
2240        # REMAINDER arguments convert all values, checking none
2241        elif action.nargs == REMAINDER:
2242            value = [self._get_value(action, v) for v in arg_strings]
2243
2244        # PARSER arguments convert all values, but check only the first
2245        elif action.nargs == PARSER:
2246            value = [self._get_value(action, v) for v in arg_strings]
2247            self._check_value(action, value[0])
2248
2249        # all other types of nargs produce a list
2250        else:
2251            value = [self._get_value(action, v) for v in arg_strings]
2252            for v in value:
2253                self._check_value(action, v)
2254
2255        # return the converted value
2256        return value
2257
2258    def _get_value(self, action, arg_string):
2259        type_func = self._registry_get('type', action.type, action.type)
2260        if not callable(type_func):
2261            msg = _('%r is not callable')
2262            raise ArgumentError(action, msg % type_func)
2263
2264        # convert the value to the appropriate type
2265        try:
2266            result = type_func(arg_string)
2267
2268        # ArgumentTypeErrors indicate errors
2269        except ArgumentTypeError:
2270            name = getattr(action.type, '__name__', repr(action.type))
2271            msg = str(_sys.exc_info()[1])
2272            raise ArgumentError(action, msg)
2273
2274        # TypeErrors or ValueErrors also indicate errors
2275        except (TypeError, ValueError):
2276            name = getattr(action.type, '__name__', repr(action.type))
2277            args = {'type': name, 'value': arg_string}
2278            msg = _('invalid %(type)s value: %(value)r')
2279            raise ArgumentError(action, msg % args)
2280
2281        # return the converted value
2282        return result
2283
2284    def _check_value(self, action, value):
2285        # converted value must be one of the choices (if specified)
2286        if action.choices is not None and value not in action.choices:
2287            args = {'value': value,
2288                    'choices': ', '.join(map(repr, action.choices))}
2289            msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2290            raise ArgumentError(action, msg % args)
2291
2292    # =======================
2293    # Help-formatting methods
2294    # =======================
2295    def format_usage(self):
2296        formatter = self._get_formatter()
2297        formatter.add_usage(self.usage, self._actions,
2298                            self._mutually_exclusive_groups)
2299        return formatter.format_help()
2300
2301    def format_help(self):
2302        formatter = self._get_formatter()
2303
2304        # usage
2305        formatter.add_usage(self.usage, self._actions,
2306                            self._mutually_exclusive_groups)
2307
2308        # description
2309        formatter.add_text(self.description)
2310
2311        # positionals, optionals and user-defined groups
2312        for action_group in self._action_groups:
2313            formatter.start_section(action_group.title)
2314            formatter.add_text(action_group.description)
2315            formatter.add_arguments(action_group._group_actions)
2316            formatter.end_section()
2317
2318        # epilog
2319        formatter.add_text(self.epilog)
2320
2321        # determine help from format above
2322        return formatter.format_help()
2323
2324    def _get_formatter(self):
2325        return self.formatter_class(prog=self.prog)
2326
2327    # =====================
2328    # Help-printing methods
2329    # =====================
2330    def print_usage(self, file=None):
2331        if file is None:
2332            file = _sys.stdout
2333        self._print_message(self.format_usage(), file)
2334
2335    def print_help(self, file=None):
2336        if file is None:
2337            file = _sys.stdout
2338        self._print_message(self.format_help(), file)
2339
2340    def _print_message(self, message, file=None):
2341        if message:
2342            if file is None:
2343                file = _sys.stderr
2344            file.write(message)
2345
2346    # ===============
2347    # Exiting methods
2348    # ===============
2349    def exit(self, status=0, message=None):
2350        if message:
2351            self._print_message(message, _sys.stderr)
2352        _sys.exit(status)
2353
2354    def error(self, message):
2355        """error(message: string)
2356
2357        Prints a usage message incorporating the message to stderr and
2358        exits.
2359
2360        If you override this in a subclass, it should not return -- it
2361        should either exit or raise an exception.
2362        """
2363        self.print_usage(_sys.stderr)
2364        args = {'prog': self.prog, 'message': message}
2365        self.exit(2, _('%(prog)s: error: %(message)s\n') % args)
2366