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