NovaBryan/EVE_Dump
Log | Files | 📦 下载最新源码 (.zip) | Refs | README

argparse.py (59437B)


      1 #Embedded file name: C:\BuildAgent\work\20d73f1b24eed06e\eve\release\V24.01\carbon\common\stdlib\argparse.py
      2 __version__ = '1.1'
      3 __all__ = ['ArgumentParser',
      4  'ArgumentError',
      5  'ArgumentTypeError',
      6  'FileType',
      7  'HelpFormatter',
      8  'ArgumentDefaultsHelpFormatter',
      9  'RawDescriptionHelpFormatter',
     10  'RawTextHelpFormatter',
     11  'Namespace',
     12  'Action',
     13  'ONE_OR_MORE',
     14  'OPTIONAL',
     15  'PARSER',
     16  'REMAINDER',
     17  'SUPPRESS',
     18  'ZERO_OR_MORE']
     19 import copy as _copy
     20 import os as _os
     21 import re as _re
     22 import sys as _sys
     23 import textwrap as _textwrap
     24 from gettext import gettext as _
     25 
     26 def _callable(obj):
     27     return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
     28 
     29 
     30 SUPPRESS = '==SUPPRESS=='
     31 OPTIONAL = '?'
     32 ZERO_OR_MORE = '*'
     33 ONE_OR_MORE = '+'
     34 PARSER = 'A...'
     35 REMAINDER = '...'
     36 _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
     37 
     38 class _AttributeHolder(object):
     39 
     40     def __repr__(self):
     41         type_name = type(self).__name__
     42         arg_strings = []
     43         for arg in self._get_args():
     44             arg_strings.append(repr(arg))
     45 
     46         for name, value in self._get_kwargs():
     47             arg_strings.append('%s=%r' % (name, value))
     48 
     49         return '%s(%s)' % (type_name, ', '.join(arg_strings))
     50 
     51     def _get_kwargs(self):
     52         return sorted(self.__dict__.items())
     53 
     54     def _get_args(self):
     55         return []
     56 
     57 
     58 def _ensure_value(namespace, name, value):
     59     if getattr(namespace, name, None) is None:
     60         setattr(namespace, name, value)
     61     return getattr(namespace, name)
     62 
     63 
     64 class HelpFormatter(object):
     65 
     66     def __init__(self, prog, indent_increment = 2, max_help_position = 24, width = None):
     67         if width is None:
     68             try:
     69                 width = int(_os.environ['COLUMNS'])
     70             except (KeyError, ValueError):
     71                 width = 80
     72 
     73             width -= 2
     74         self._prog = prog
     75         self._indent_increment = indent_increment
     76         self._max_help_position = max_help_position
     77         self._width = width
     78         self._current_indent = 0
     79         self._level = 0
     80         self._action_max_length = 0
     81         self._root_section = self._Section(self, None)
     82         self._current_section = self._root_section
     83         self._whitespace_matcher = _re.compile('\\s+')
     84         self._long_break_matcher = _re.compile('\\n\\n\\n+')
     85 
     86     def _indent(self):
     87         self._current_indent += self._indent_increment
     88         self._level += 1
     89 
     90     def _dedent(self):
     91         self._current_indent -= self._indent_increment
     92         self._level -= 1
     93 
     94     class _Section(object):
     95 
     96         def __init__(self, formatter, parent, heading = None):
     97             self.formatter = formatter
     98             self.parent = parent
     99             self.heading = heading
    100             self.items = []
    101 
    102         def format_help(self):
    103             if self.parent is not None:
    104                 self.formatter._indent()
    105             join = self.formatter._join_parts
    106             for func, args in self.items:
    107                 func(*args)
    108 
    109             item_help = join([ func(*args) for func, args in self.items ])
    110             if self.parent is not None:
    111                 self.formatter._dedent()
    112             if not item_help:
    113                 return ''
    114             if self.heading is not SUPPRESS and self.heading is not None:
    115                 current_indent = self.formatter._current_indent
    116                 heading = '%*s%s:\n' % (current_indent, '', self.heading)
    117             else:
    118                 heading = ''
    119             return join(['\n',
    120              heading,
    121              item_help,
    122              '\n'])
    123 
    124     def _add_item(self, func, args):
    125         self._current_section.items.append((func, args))
    126 
    127     def start_section(self, heading):
    128         self._indent()
    129         section = self._Section(self, self._current_section, heading)
    130         self._add_item(section.format_help, [])
    131         self._current_section = section
    132 
    133     def end_section(self):
    134         self._current_section = self._current_section.parent
    135         self._dedent()
    136 
    137     def add_text(self, text):
    138         if text is not SUPPRESS and text is not None:
    139             self._add_item(self._format_text, [text])
    140 
    141     def add_usage(self, usage, actions, groups, prefix = None):
    142         if usage is not SUPPRESS:
    143             args = (usage,
    144              actions,
    145              groups,
    146              prefix)
    147             self._add_item(self._format_usage, args)
    148 
    149     def add_argument(self, action):
    150         if action.help is not SUPPRESS:
    151             get_invocation = self._format_action_invocation
    152             invocations = [get_invocation(action)]
    153             for subaction in self._iter_indented_subactions(action):
    154                 invocations.append(get_invocation(subaction))
    155 
    156             invocation_length = max([ len(s) for s in invocations ])
    157             action_length = invocation_length + self._current_indent
    158             self._action_max_length = max(self._action_max_length, action_length)
    159             self._add_item(self._format_action, [action])
    160 
    161     def add_arguments(self, actions):
    162         for action in actions:
    163             self.add_argument(action)
    164 
    165     def format_help(self):
    166         help = self._root_section.format_help()
    167         if help:
    168             help = self._long_break_matcher.sub('\n\n', help)
    169             help = help.strip('\n') + '\n'
    170         return help
    171 
    172     def _join_parts(self, part_strings):
    173         return ''.join([ part for part in part_strings if part and part is not SUPPRESS ])
    174 
    175     def _format_usage(self, usage, actions, groups, prefix):
    176         if prefix is None:
    177             prefix = _('usage: ')
    178         if usage is not None:
    179             usage = usage % dict(prog=self._prog)
    180         elif usage is None and not actions:
    181             usage = '%(prog)s' % dict(prog=self._prog)
    182         elif usage is None:
    183             prog = '%(prog)s' % dict(prog=self._prog)
    184             optionals = []
    185             positionals = []
    186             for action in actions:
    187                 if action.option_strings:
    188                     optionals.append(action)
    189                 else:
    190                     positionals.append(action)
    191 
    192             format = self._format_actions_usage
    193             action_usage = format(optionals + positionals, groups)
    194             usage = ' '.join([ s for s in [prog, action_usage] if s ])
    195             text_width = self._width - self._current_indent
    196             if len(prefix) + len(usage) > text_width:
    197                 part_regexp = '\\(.*?\\)+|\\[.*?\\]+|\\S+'
    198                 opt_usage = format(optionals, groups)
    199                 pos_usage = format(positionals, groups)
    200                 opt_parts = _re.findall(part_regexp, opt_usage)
    201                 pos_parts = _re.findall(part_regexp, pos_usage)
    202 
    203                 def get_lines(parts, indent, prefix = None):
    204                     lines = []
    205                     line = []
    206                     if prefix is not None:
    207                         line_len = len(prefix) - 1
    208                     else:
    209                         line_len = len(indent) - 1
    210                     for part in parts:
    211                         if line_len + 1 + len(part) > text_width:
    212                             lines.append(indent + ' '.join(line))
    213                             line = []
    214                             line_len = len(indent) - 1
    215                         line.append(part)
    216                         line_len += len(part) + 1
    217 
    218                     if line:
    219                         lines.append(indent + ' '.join(line))
    220                     if prefix is not None:
    221                         lines[0] = lines[0][len(indent):]
    222                     return lines
    223 
    224                 if len(prefix) + len(prog) <= 0.75 * text_width:
    225                     indent = ' ' * (len(prefix) + len(prog) + 1)
    226                     if opt_parts:
    227                         lines = get_lines([prog] + opt_parts, indent, prefix)
    228                         lines.extend(get_lines(pos_parts, indent))
    229                     elif pos_parts:
    230                         lines = get_lines([prog] + pos_parts, indent, prefix)
    231                     else:
    232                         lines = [prog]
    233                 else:
    234                     indent = ' ' * len(prefix)
    235                     parts = opt_parts + pos_parts
    236                     lines = get_lines(parts, indent)
    237                     if len(lines) > 1:
    238                         lines = []
    239                         lines.extend(get_lines(opt_parts, indent))
    240                         lines.extend(get_lines(pos_parts, indent))
    241                     lines = [prog] + lines
    242                 usage = '\n'.join(lines)
    243         return '%s%s\n\n' % (prefix, usage)
    244 
    245     def _format_actions_usage(self, actions, groups):
    246         group_actions = set()
    247         inserts = {}
    248         for group in groups:
    249             try:
    250                 start = actions.index(group._group_actions[0])
    251             except ValueError:
    252                 continue
    253             else:
    254                 end = start + len(group._group_actions)
    255                 if actions[start:end] == group._group_actions:
    256                     for action in group._group_actions:
    257                         group_actions.add(action)
    258 
    259                     if not group.required:
    260                         if start in inserts:
    261                             inserts[start] += ' ['
    262                         else:
    263                             inserts[start] = '['
    264                         inserts[end] = ']'
    265                     else:
    266                         if start in inserts:
    267                             inserts[start] += ' ('
    268                         else:
    269                             inserts[start] = '('
    270                         inserts[end] = ')'
    271                     for i in range(start + 1, end):
    272                         inserts[i] = '|'
    273 
    274         parts = []
    275         for i, action in enumerate(actions):
    276             if action.help is SUPPRESS:
    277                 parts.append(None)
    278                 if inserts.get(i) == '|':
    279                     inserts.pop(i)
    280                 elif inserts.get(i + 1) == '|':
    281                     inserts.pop(i + 1)
    282             elif not action.option_strings:
    283                 part = self._format_args(action, action.dest)
    284                 if action in group_actions:
    285                     if part[0] == '[' and part[-1] == ']':
    286                         part = part[1:-1]
    287                 parts.append(part)
    288             else:
    289                 option_string = action.option_strings[0]
    290                 if action.nargs == 0:
    291                     part = '%s' % option_string
    292                 else:
    293                     default = action.dest.upper()
    294                     args_string = self._format_args(action, default)
    295                     part = '%s %s' % (option_string, args_string)
    296                 if not action.required and action not in group_actions:
    297                     part = '[%s]' % part
    298                 parts.append(part)
    299 
    300         for i in sorted(inserts, reverse=True):
    301             parts[i:i] = [inserts[i]]
    302 
    303         text = ' '.join([ item for item in parts if item is not None ])
    304         open = '[\\[(]'
    305         close = '[\\])]'
    306         text = _re.sub('(%s) ' % open, '\\1', text)
    307         text = _re.sub(' (%s)' % close, '\\1', text)
    308         text = _re.sub('%s *%s' % (open, close), '', text)
    309         text = _re.sub('\\(([^|]*)\\)', '\\1', text)
    310         text = text.strip()
    311         return text
    312 
    313     def _format_text(self, text):
    314         if '%(prog)' in text:
    315             text = text % dict(prog=self._prog)
    316         text_width = self._width - self._current_indent
    317         indent = ' ' * self._current_indent
    318         return self._fill_text(text, text_width, indent) + '\n\n'
    319 
    320     def _format_action(self, action):
    321         help_position = min(self._action_max_length + 2, self._max_help_position)
    322         help_width = self._width - help_position
    323         action_width = help_position - self._current_indent - 2
    324         action_header = self._format_action_invocation(action)
    325         if not action.help:
    326             tup = (self._current_indent, '', action_header)
    327             action_header = '%*s%s\n' % tup
    328         elif len(action_header) <= action_width:
    329             tup = (self._current_indent,
    330              '',
    331              action_width,
    332              action_header)
    333             action_header = '%*s%-*s  ' % tup
    334             indent_first = 0
    335         else:
    336             tup = (self._current_indent, '', action_header)
    337             action_header = '%*s%s\n' % tup
    338             indent_first = help_position
    339         parts = [action_header]
    340         if action.help:
    341             help_text = self._expand_help(action)
    342             help_lines = self._split_lines(help_text, help_width)
    343             parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
    344             for line in help_lines[1:]:
    345                 parts.append('%*s%s\n' % (help_position, '', line))
    346 
    347         elif not action_header.endswith('\n'):
    348             parts.append('\n')
    349         for subaction in self._iter_indented_subactions(action):
    350             parts.append(self._format_action(subaction))
    351 
    352         return self._join_parts(parts)
    353 
    354     def _format_action_invocation(self, action):
    355         if not action.option_strings:
    356             metavar, = self._metavar_formatter(action, action.dest)(1)
    357             return metavar
    358         else:
    359             parts = []
    360             if action.nargs == 0:
    361                 parts.extend(action.option_strings)
    362             else:
    363                 default = action.dest.upper()
    364                 args_string = self._format_args(action, default)
    365                 for option_string in action.option_strings:
    366                     parts.append('%s %s' % (option_string, args_string))
    367 
    368             return ', '.join(parts)
    369 
    370     def _metavar_formatter(self, action, default_metavar):
    371         if action.metavar is not None:
    372             result = action.metavar
    373         elif action.choices is not None:
    374             choice_strs = [ str(choice) for choice in action.choices ]
    375             result = '{%s}' % ','.join(choice_strs)
    376         else:
    377             result = default_metavar
    378 
    379         def format(tuple_size):
    380             if isinstance(result, tuple):
    381                 return result
    382             else:
    383                 return (result,) * tuple_size
    384 
    385         return format
    386 
    387     def _format_args(self, action, default_metavar):
    388         get_metavar = self._metavar_formatter(action, default_metavar)
    389         if action.nargs is None:
    390             result = '%s' % get_metavar(1)
    391         elif action.nargs == OPTIONAL:
    392             result = '[%s]' % get_metavar(1)
    393         elif action.nargs == ZERO_OR_MORE:
    394             result = '[%s [%s ...]]' % get_metavar(2)
    395         elif action.nargs == ONE_OR_MORE:
    396             result = '%s [%s ...]' % get_metavar(2)
    397         elif action.nargs == REMAINDER:
    398             result = '...'
    399         elif action.nargs == PARSER:
    400             result = '%s ...' % get_metavar(1)
    401         else:
    402             formats = [ '%s' for _ in range(action.nargs) ]
    403             result = ' '.join(formats) % get_metavar(action.nargs)
    404         return result
    405 
    406     def _expand_help(self, action):
    407         params = dict(vars(action), prog=self._prog)
    408         for name in list(params):
    409             if params[name] is SUPPRESS:
    410                 del params[name]
    411 
    412         for name in list(params):
    413             if hasattr(params[name], '__name__'):
    414                 params[name] = params[name].__name__
    415 
    416         if params.get('choices') is not None:
    417             choices_str = ', '.join([ str(c) for c in params['choices'] ])
    418             params['choices'] = choices_str
    419         return self._get_help_string(action) % params
    420 
    421     def _iter_indented_subactions(self, action):
    422         try:
    423             get_subactions = action._get_subactions
    424         except AttributeError:
    425             pass
    426         else:
    427             self._indent()
    428             for subaction in get_subactions():
    429                 yield subaction
    430 
    431             self._dedent()
    432 
    433     def _split_lines(self, text, width):
    434         text = self._whitespace_matcher.sub(' ', text).strip()
    435         return _textwrap.wrap(text, width)
    436 
    437     def _fill_text(self, text, width, indent):
    438         text = self._whitespace_matcher.sub(' ', text).strip()
    439         return _textwrap.fill(text, width, initial_indent=indent, subsequent_indent=indent)
    440 
    441     def _get_help_string(self, action):
    442         return action.help
    443 
    444 
    445 class RawDescriptionHelpFormatter(HelpFormatter):
    446 
    447     def _fill_text(self, text, width, indent):
    448         return ''.join([ indent + line for line in text.splitlines(True) ])
    449 
    450 
    451 class RawTextHelpFormatter(RawDescriptionHelpFormatter):
    452 
    453     def _split_lines(self, text, width):
    454         return text.splitlines()
    455 
    456 
    457 class ArgumentDefaultsHelpFormatter(HelpFormatter):
    458 
    459     def _get_help_string(self, action):
    460         help = action.help
    461         if '%(default)' not in action.help:
    462             if action.default is not SUPPRESS:
    463                 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
    464                 if action.option_strings or action.nargs in defaulting_nargs:
    465                     help += ' (default: %(default)s)'
    466         return help
    467 
    468 
    469 def _get_action_name(argument):
    470     if argument is None:
    471         return
    472     elif argument.option_strings:
    473         return '/'.join(argument.option_strings)
    474     elif argument.metavar not in (None, SUPPRESS):
    475         return argument.metavar
    476     elif argument.dest not in (None, SUPPRESS):
    477         return argument.dest
    478     else:
    479         return
    480 
    481 
    482 class ArgumentError(Exception):
    483 
    484     def __init__(self, argument, message):
    485         self.argument_name = _get_action_name(argument)
    486         self.message = message
    487 
    488     def __str__(self):
    489         if self.argument_name is None:
    490             format = '%(message)s'
    491         else:
    492             format = 'argument %(argument_name)s: %(message)s'
    493         return format % dict(message=self.message, argument_name=self.argument_name)
    494 
    495 
    496 class ArgumentTypeError(Exception):
    497     pass
    498 
    499 
    500 class Action(_AttributeHolder):
    501 
    502     def __init__(self, option_strings, dest, nargs = None, const = None, default = None, type = None, choices = None, required = False, help = None, metavar = None):
    503         self.option_strings = option_strings
    504         self.dest = dest
    505         self.nargs = nargs
    506         self.const = const
    507         self.default = default
    508         self.type = type
    509         self.choices = choices
    510         self.required = required
    511         self.help = help
    512         self.metavar = metavar
    513 
    514     def _get_kwargs(self):
    515         names = ['option_strings',
    516          'dest',
    517          'nargs',
    518          'const',
    519          'default',
    520          'type',
    521          'choices',
    522          'help',
    523          'metavar']
    524         return [ (name, getattr(self, name)) for name in names ]
    525 
    526     def __call__(self, parser, namespace, values, option_string = None):
    527         raise NotImplementedError(_('.__call__() not defined'))
    528 
    529 
    530 class _StoreAction(Action):
    531 
    532     def __init__(self, option_strings, dest, nargs = None, const = None, default = None, type = None, choices = None, required = False, help = None, metavar = None):
    533         if nargs == 0:
    534             raise ValueError('nargs for store actions must be > 0; if you have nothing to store, actions such as store true or store const may be more appropriate')
    535         if const is not None and nargs != OPTIONAL:
    536             raise ValueError('nargs must be %r to supply const' % OPTIONAL)
    537         super(_StoreAction, self).__init__(option_strings=option_strings, dest=dest, nargs=nargs, const=const, default=default, type=type, choices=choices, required=required, help=help, metavar=metavar)
    538 
    539     def __call__(self, parser, namespace, values, option_string = None):
    540         setattr(namespace, self.dest, values)
    541 
    542 
    543 class _StoreConstAction(Action):
    544 
    545     def __init__(self, option_strings, dest, const, default = None, required = False, help = None, metavar = None):
    546         super(_StoreConstAction, self).__init__(option_strings=option_strings, dest=dest, nargs=0, const=const, default=default, required=required, help=help)
    547 
    548     def __call__(self, parser, namespace, values, option_string = None):
    549         setattr(namespace, self.dest, self.const)
    550 
    551 
    552 class _StoreTrueAction(_StoreConstAction):
    553 
    554     def __init__(self, option_strings, dest, default = False, required = False, help = None):
    555         super(_StoreTrueAction, self).__init__(option_strings=option_strings, dest=dest, const=True, default=default, required=required, help=help)
    556 
    557 
    558 class _StoreFalseAction(_StoreConstAction):
    559 
    560     def __init__(self, option_strings, dest, default = True, required = False, help = None):
    561         super(_StoreFalseAction, self).__init__(option_strings=option_strings, dest=dest, const=False, default=default, required=required, help=help)
    562 
    563 
    564 class _AppendAction(Action):
    565 
    566     def __init__(self, option_strings, dest, nargs = None, const = None, default = None, type = None, choices = None, required = False, help = None, metavar = None):
    567         if nargs == 0:
    568             raise ValueError('nargs for append actions must be > 0; if arg strings are not supplying the value to append, the append const action may be more appropriate')
    569         if const is not None and nargs != OPTIONAL:
    570             raise ValueError('nargs must be %r to supply const' % OPTIONAL)
    571         super(_AppendAction, self).__init__(option_strings=option_strings, dest=dest, nargs=nargs, const=const, default=default, type=type, choices=choices, required=required, help=help, metavar=metavar)
    572 
    573     def __call__(self, parser, namespace, values, option_string = None):
    574         items = _copy.copy(_ensure_value(namespace, self.dest, []))
    575         items.append(values)
    576         setattr(namespace, self.dest, items)
    577 
    578 
    579 class _AppendConstAction(Action):
    580 
    581     def __init__(self, option_strings, dest, const, default = None, required = False, help = None, metavar = None):
    582         super(_AppendConstAction, self).__init__(option_strings=option_strings, dest=dest, nargs=0, const=const, default=default, required=required, help=help, metavar=metavar)
    583 
    584     def __call__(self, parser, namespace, values, option_string = None):
    585         items = _copy.copy(_ensure_value(namespace, self.dest, []))
    586         items.append(self.const)
    587         setattr(namespace, self.dest, items)
    588 
    589 
    590 class _CountAction(Action):
    591 
    592     def __init__(self, option_strings, dest, default = None, required = False, help = None):
    593         super(_CountAction, self).__init__(option_strings=option_strings, dest=dest, nargs=0, default=default, required=required, help=help)
    594 
    595     def __call__(self, parser, namespace, values, option_string = None):
    596         new_count = _ensure_value(namespace, self.dest, 0) + 1
    597         setattr(namespace, self.dest, new_count)
    598 
    599 
    600 class _HelpAction(Action):
    601 
    602     def __init__(self, option_strings, dest = SUPPRESS, default = SUPPRESS, help = None):
    603         super(_HelpAction, self).__init__(option_strings=option_strings, dest=dest, default=default, nargs=0, help=help)
    604 
    605     def __call__(self, parser, namespace, values, option_string = None):
    606         parser.print_help()
    607         parser.exit()
    608 
    609 
    610 class _VersionAction(Action):
    611 
    612     def __init__(self, option_strings, version = None, dest = SUPPRESS, default = SUPPRESS, help = "show program's version number and exit"):
    613         super(_VersionAction, self).__init__(option_strings=option_strings, dest=dest, default=default, nargs=0, help=help)
    614         self.version = version
    615 
    616     def __call__(self, parser, namespace, values, option_string = None):
    617         version = self.version
    618         if version is None:
    619             version = parser.version
    620         formatter = parser._get_formatter()
    621         formatter.add_text(version)
    622         parser.exit(message=formatter.format_help())
    623 
    624 
    625 class _SubParsersAction(Action):
    626 
    627     class _ChoicesPseudoAction(Action):
    628 
    629         def __init__(self, name, help):
    630             sup = super(_SubParsersAction._ChoicesPseudoAction, self)
    631             sup.__init__(option_strings=[], dest=name, help=help)
    632 
    633     def __init__(self, option_strings, prog, parser_class, dest = SUPPRESS, help = None, metavar = None):
    634         self._prog_prefix = prog
    635         self._parser_class = parser_class
    636         self._name_parser_map = {}
    637         self._choices_actions = []
    638         super(_SubParsersAction, self).__init__(option_strings=option_strings, dest=dest, nargs=PARSER, choices=self._name_parser_map, help=help, metavar=metavar)
    639 
    640     def add_parser(self, name, **kwargs):
    641         if kwargs.get('prog') is None:
    642             kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
    643         if 'help' in kwargs:
    644             help = kwargs.pop('help')
    645             choice_action = self._ChoicesPseudoAction(name, help)
    646             self._choices_actions.append(choice_action)
    647         parser = self._parser_class(**kwargs)
    648         self._name_parser_map[name] = parser
    649         return parser
    650 
    651     def _get_subactions(self):
    652         return self._choices_actions
    653 
    654     def __call__(self, parser, namespace, values, option_string = None):
    655         parser_name = values[0]
    656         arg_strings = values[1:]
    657         if self.dest is not SUPPRESS:
    658             setattr(namespace, self.dest, parser_name)
    659         try:
    660             parser = self._name_parser_map[parser_name]
    661         except KeyError:
    662             tup = (parser_name, ', '.join(self._name_parser_map))
    663             msg = _('unknown parser %r (choices: %s)' % tup)
    664             raise ArgumentError(self, msg)
    665 
    666         namespace, arg_strings = parser.parse_known_args(arg_strings, namespace)
    667         if arg_strings:
    668             vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
    669             getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
    670 
    671 
    672 class FileType(object):
    673 
    674     def __init__(self, mode = 'r', bufsize = None):
    675         self._mode = mode
    676         self._bufsize = bufsize
    677 
    678     def __call__(self, string):
    679         if string == '-':
    680             if 'r' in self._mode:
    681                 return _sys.stdin
    682             if 'w' in self._mode:
    683                 return _sys.stdout
    684             msg = _('argument "-" with mode %r' % self._mode)
    685             raise ValueError(msg)
    686         if self._bufsize:
    687             return open(string, self._mode, self._bufsize)
    688         else:
    689             return open(string, self._mode)
    690 
    691     def __repr__(self):
    692         args = [self._mode, self._bufsize]
    693         args_str = ', '.join([ repr(arg) for arg in args if arg is not None ])
    694         return '%s(%s)' % (type(self).__name__, args_str)
    695 
    696 
    697 class Namespace(_AttributeHolder):
    698 
    699     def __init__(self, **kwargs):
    700         for name in kwargs:
    701             setattr(self, name, kwargs[name])
    702 
    703     __hash__ = None
    704 
    705     def __eq__(self, other):
    706         return vars(self) == vars(other)
    707 
    708     def __ne__(self, other):
    709         return not self == other
    710 
    711     def __contains__(self, key):
    712         return key in self.__dict__
    713 
    714 
    715 class _ActionsContainer(object):
    716 
    717     def __init__(self, description, prefix_chars, argument_default, conflict_handler):
    718         super(_ActionsContainer, self).__init__()
    719         self.description = description
    720         self.argument_default = argument_default
    721         self.prefix_chars = prefix_chars
    722         self.conflict_handler = conflict_handler
    723         self._registries = {}
    724         self.register('action', None, _StoreAction)
    725         self.register('action', 'store', _StoreAction)
    726         self.register('action', 'store_const', _StoreConstAction)
    727         self.register('action', 'store_true', _StoreTrueAction)
    728         self.register('action', 'store_false', _StoreFalseAction)
    729         self.register('action', 'append', _AppendAction)
    730         self.register('action', 'append_const', _AppendConstAction)
    731         self.register('action', 'count', _CountAction)
    732         self.register('action', 'help', _HelpAction)
    733         self.register('action', 'version', _VersionAction)
    734         self.register('action', 'parsers', _SubParsersAction)
    735         self._get_handler()
    736         self._actions = []
    737         self._option_string_actions = {}
    738         self._action_groups = []
    739         self._mutually_exclusive_groups = []
    740         self._defaults = {}
    741         self._negative_number_matcher = _re.compile('^-\\d+$|^-\\d*\\.\\d+$')
    742         self._has_negative_number_optionals = []
    743 
    744     def register(self, registry_name, value, object):
    745         registry = self._registries.setdefault(registry_name, {})
    746         registry[value] = object
    747 
    748     def _registry_get(self, registry_name, value, default = None):
    749         return self._registries[registry_name].get(value, default)
    750 
    751     def set_defaults(self, **kwargs):
    752         self._defaults.update(kwargs)
    753         for action in self._actions:
    754             if action.dest in kwargs:
    755                 action.default = kwargs[action.dest]
    756 
    757     def get_default(self, dest):
    758         for action in self._actions:
    759             if action.dest == dest and action.default is not None:
    760                 return action.default
    761 
    762         return self._defaults.get(dest, None)
    763 
    764     def add_argument(self, *args, **kwargs):
    765         chars = self.prefix_chars
    766         if not args or len(args) == 1 and args[0][0] not in chars:
    767             if args and 'dest' in kwargs:
    768                 raise ValueError('dest supplied twice for positional argument')
    769             kwargs = self._get_positional_kwargs(*args, **kwargs)
    770         else:
    771             kwargs = self._get_optional_kwargs(*args, **kwargs)
    772         if 'default' not in kwargs:
    773             dest = kwargs['dest']
    774             if dest in self._defaults:
    775                 kwargs['default'] = self._defaults[dest]
    776             elif self.argument_default is not None:
    777                 kwargs['default'] = self.argument_default
    778         action_class = self._pop_action_class(kwargs)
    779         if not _callable(action_class):
    780             raise ValueError('unknown action "%s"' % action_class)
    781         action = action_class(**kwargs)
    782         type_func = self._registry_get('type', action.type, action.type)
    783         if not _callable(type_func):
    784             raise ValueError('%r is not callable' % type_func)
    785         return self._add_action(action)
    786 
    787     def add_argument_group(self, *args, **kwargs):
    788         group = _ArgumentGroup(self, *args, **kwargs)
    789         self._action_groups.append(group)
    790         return group
    791 
    792     def add_mutually_exclusive_group(self, **kwargs):
    793         group = _MutuallyExclusiveGroup(self, **kwargs)
    794         self._mutually_exclusive_groups.append(group)
    795         return group
    796 
    797     def _add_action(self, action):
    798         self._check_conflict(action)
    799         self._actions.append(action)
    800         action.container = self
    801         for option_string in action.option_strings:
    802             self._option_string_actions[option_string] = action
    803 
    804         for option_string in action.option_strings:
    805             if self._negative_number_matcher.match(option_string):
    806                 if not self._has_negative_number_optionals:
    807                     self._has_negative_number_optionals.append(True)
    808 
    809         return action
    810 
    811     def _remove_action(self, action):
    812         self._actions.remove(action)
    813 
    814     def _add_container_actions(self, container):
    815         title_group_map = {}
    816         for group in self._action_groups:
    817             if group.title in title_group_map:
    818                 msg = _('cannot merge actions - two groups are named %r')
    819                 raise ValueError(msg % group.title)
    820             title_group_map[group.title] = group
    821 
    822         group_map = {}
    823         for group in container._action_groups:
    824             if group.title not in title_group_map:
    825                 title_group_map[group.title] = self.add_argument_group(title=group.title, description=group.description, conflict_handler=group.conflict_handler)
    826             for action in group._group_actions:
    827                 group_map[action] = title_group_map[group.title]
    828 
    829         for group in container._mutually_exclusive_groups:
    830             mutex_group = self.add_mutually_exclusive_group(required=group.required)
    831             for action in group._group_actions:
    832                 group_map[action] = mutex_group
    833 
    834         for action in container._actions:
    835             group_map.get(action, self)._add_action(action)
    836 
    837     def _get_positional_kwargs(self, dest, **kwargs):
    838         if 'required' in kwargs:
    839             msg = _("'required' is an invalid argument for positionals")
    840             raise TypeError(msg)
    841         if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
    842             kwargs['required'] = True
    843         if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
    844             kwargs['required'] = True
    845         return dict(kwargs, dest=dest, option_strings=[])
    846 
    847     def _get_optional_kwargs(self, *args, **kwargs):
    848         option_strings = []
    849         long_option_strings = []
    850         for option_string in args:
    851             if option_string[0] not in self.prefix_chars:
    852                 msg = _('invalid option string %r: must start with a character %r')
    853                 tup = (option_string, self.prefix_chars)
    854                 raise ValueError(msg % tup)
    855             option_strings.append(option_string)
    856             if option_string[0] in self.prefix_chars:
    857                 if len(option_string) > 1:
    858                     if option_string[1] in self.prefix_chars:
    859                         long_option_strings.append(option_string)
    860 
    861         dest = kwargs.pop('dest', None)
    862         if dest is None:
    863             if long_option_strings:
    864                 dest_option_string = long_option_strings[0]
    865             else:
    866                 dest_option_string = option_strings[0]
    867             dest = dest_option_string.lstrip(self.prefix_chars)
    868             if not dest:
    869                 msg = _('dest= is required for options like %r')
    870                 raise ValueError(msg % option_string)
    871             dest = dest.replace('-', '_')
    872         return dict(kwargs, dest=dest, option_strings=option_strings)
    873 
    874     def _pop_action_class(self, kwargs, default = None):
    875         action = kwargs.pop('action', default)
    876         return self._registry_get('action', action, action)
    877 
    878     def _get_handler(self):
    879         handler_func_name = '_handle_conflict_%s' % self.conflict_handler
    880         try:
    881             return getattr(self, handler_func_name)
    882         except AttributeError:
    883             msg = _('invalid conflict_resolution value: %r')
    884             raise ValueError(msg % self.conflict_handler)
    885 
    886     def _check_conflict(self, action):
    887         confl_optionals = []
    888         for option_string in action.option_strings:
    889             if option_string in self._option_string_actions:
    890                 confl_optional = self._option_string_actions[option_string]
    891                 confl_optionals.append((option_string, confl_optional))
    892 
    893         if confl_optionals:
    894             conflict_handler = self._get_handler()
    895             conflict_handler(action, confl_optionals)
    896 
    897     def _handle_conflict_error(self, action, conflicting_actions):
    898         message = _('conflicting option string(s): %s')
    899         conflict_string = ', '.join([ option_string for option_string, action in conflicting_actions ])
    900         raise ArgumentError(action, message % conflict_string)
    901 
    902     def _handle_conflict_resolve(self, action, conflicting_actions):
    903         for option_string, action in conflicting_actions:
    904             action.option_strings.remove(option_string)
    905             self._option_string_actions.pop(option_string, None)
    906             if not action.option_strings:
    907                 action.container._remove_action(action)
    908 
    909 
    910 class _ArgumentGroup(_ActionsContainer):
    911 
    912     def __init__(self, container, title = None, description = None, **kwargs):
    913         update = kwargs.setdefault
    914         update('conflict_handler', container.conflict_handler)
    915         update('prefix_chars', container.prefix_chars)
    916         update('argument_default', container.argument_default)
    917         super_init = super(_ArgumentGroup, self).__init__
    918         super_init(description=description, **kwargs)
    919         self.title = title
    920         self._group_actions = []
    921         self._registries = container._registries
    922         self._actions = container._actions
    923         self._option_string_actions = container._option_string_actions
    924         self._defaults = container._defaults
    925         self._has_negative_number_optionals = container._has_negative_number_optionals
    926 
    927     def _add_action(self, action):
    928         action = super(_ArgumentGroup, self)._add_action(action)
    929         self._group_actions.append(action)
    930         return action
    931 
    932     def _remove_action(self, action):
    933         super(_ArgumentGroup, self)._remove_action(action)
    934         self._group_actions.remove(action)
    935 
    936 
    937 class _MutuallyExclusiveGroup(_ArgumentGroup):
    938 
    939     def __init__(self, container, required = False):
    940         super(_MutuallyExclusiveGroup, self).__init__(container)
    941         self.required = required
    942         self._container = container
    943 
    944     def _add_action(self, action):
    945         if action.required:
    946             msg = _('mutually exclusive arguments must be optional')
    947             raise ValueError(msg)
    948         action = self._container._add_action(action)
    949         self._group_actions.append(action)
    950         return action
    951 
    952     def _remove_action(self, action):
    953         self._container._remove_action(action)
    954         self._group_actions.remove(action)
    955 
    956 
    957 class ArgumentParser(_AttributeHolder, _ActionsContainer):
    958 
    959     def __init__(self, prog = None, usage = None, description = None, epilog = None, version = None, parents = [], formatter_class = HelpFormatter, prefix_chars = '-', fromfile_prefix_chars = None, argument_default = None, conflict_handler = 'error', add_help = True):
    960         if version is not None:
    961             import warnings
    962             warnings.warn('The "version" argument to ArgumentParser is deprecated. Please use "add_argument(..., action=\'version\', version="N", ...)" instead', DeprecationWarning)
    963         superinit = super(ArgumentParser, self).__init__
    964         superinit(description=description, prefix_chars=prefix_chars, argument_default=argument_default, conflict_handler=conflict_handler)
    965         if prog is None:
    966             prog = _os.path.basename(_sys.argv[0])
    967         self.prog = prog
    968         self.usage = usage
    969         self.epilog = epilog
    970         self.version = version
    971         self.formatter_class = formatter_class
    972         self.fromfile_prefix_chars = fromfile_prefix_chars
    973         self.add_help = add_help
    974         add_group = self.add_argument_group
    975         self._positionals = add_group(_('positional arguments'))
    976         self._optionals = add_group(_('optional arguments'))
    977         self._subparsers = None
    978 
    979         def identity(string):
    980             return string
    981 
    982         self.register('type', None, identity)
    983         default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
    984         if self.add_help:
    985             self.add_argument(default_prefix + 'h', default_prefix * 2 + 'help', action='help', default=SUPPRESS, help=_('show this help message and exit'))
    986         if self.version:
    987             self.add_argument(default_prefix + 'v', default_prefix * 2 + 'version', action='version', default=SUPPRESS, version=self.version, help=_("show program's version number and exit"))
    988         for parent in parents:
    989             self._add_container_actions(parent)
    990             try:
    991                 defaults = parent._defaults
    992             except AttributeError:
    993                 pass
    994             else:
    995                 self._defaults.update(defaults)
    996 
    997     def _get_kwargs(self):
    998         names = ['prog',
    999          'usage',
   1000          'description',
   1001          'version',
   1002          'formatter_class',
   1003          'conflict_handler',
   1004          'add_help']
   1005         return [ (name, getattr(self, name)) for name in names ]
   1006 
   1007     def add_subparsers(self, **kwargs):
   1008         if self._subparsers is not None:
   1009             self.error(_('cannot have multiple subparser arguments'))
   1010         kwargs.setdefault('parser_class', type(self))
   1011         if 'title' in kwargs or 'description' in kwargs:
   1012             title = _(kwargs.pop('title', 'subcommands'))
   1013             description = _(kwargs.pop('description', None))
   1014             self._subparsers = self.add_argument_group(title, description)
   1015         else:
   1016             self._subparsers = self._positionals
   1017         if kwargs.get('prog') is None:
   1018             formatter = self._get_formatter()
   1019             positionals = self._get_positional_actions()
   1020             groups = self._mutually_exclusive_groups
   1021             formatter.add_usage(self.usage, positionals, groups, '')
   1022             kwargs['prog'] = formatter.format_help().strip()
   1023         parsers_class = self._pop_action_class(kwargs, 'parsers')
   1024         action = parsers_class(option_strings=[], **kwargs)
   1025         self._subparsers._add_action(action)
   1026         return action
   1027 
   1028     def _add_action(self, action):
   1029         if action.option_strings:
   1030             self._optionals._add_action(action)
   1031         else:
   1032             self._positionals._add_action(action)
   1033         return action
   1034 
   1035     def _get_optional_actions(self):
   1036         return [ action for action in self._actions if action.option_strings ]
   1037 
   1038     def _get_positional_actions(self):
   1039         return [ action for action in self._actions if not action.option_strings ]
   1040 
   1041     def parse_args(self, args = None, namespace = None):
   1042         args, argv = self.parse_known_args(args, namespace)
   1043         if argv:
   1044             msg = _('unrecognized arguments: %s')
   1045             self.error(msg % ' '.join(argv))
   1046         return args
   1047 
   1048     def parse_known_args(self, args = None, namespace = None):
   1049         if args is None:
   1050             args = _sys.argv[1:]
   1051         if namespace is None:
   1052             namespace = Namespace()
   1053         for action in self._actions:
   1054             if action.dest is not SUPPRESS:
   1055                 if not hasattr(namespace, action.dest):
   1056                     if action.default is not SUPPRESS:
   1057                         default = action.default
   1058                         if isinstance(action.default, basestring):
   1059                             default = self._get_value(action, default)
   1060                         setattr(namespace, action.dest, default)
   1061 
   1062         for dest in self._defaults:
   1063             if not hasattr(namespace, dest):
   1064                 setattr(namespace, dest, self._defaults[dest])
   1065 
   1066         try:
   1067             namespace, args = self._parse_known_args(args, namespace)
   1068             if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
   1069                 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
   1070                 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
   1071             return (namespace, args)
   1072         except ArgumentError:
   1073             err = _sys.exc_info()[1]
   1074             self.error(str(err))
   1075 
   1076     def _parse_known_args(self, arg_strings, namespace):
   1077         if self.fromfile_prefix_chars is not None:
   1078             arg_strings = self._read_args_from_files(arg_strings)
   1079         action_conflicts = {}
   1080         for mutex_group in self._mutually_exclusive_groups:
   1081             group_actions = mutex_group._group_actions
   1082             for i, mutex_action in enumerate(mutex_group._group_actions):
   1083                 conflicts = action_conflicts.setdefault(mutex_action, [])
   1084                 conflicts.extend(group_actions[:i])
   1085                 conflicts.extend(group_actions[i + 1:])
   1086 
   1087         option_string_indices = {}
   1088         arg_string_pattern_parts = []
   1089         arg_strings_iter = iter(arg_strings)
   1090         for i, arg_string in enumerate(arg_strings_iter):
   1091             if arg_string == '--':
   1092                 arg_string_pattern_parts.append('-')
   1093                 for arg_string in arg_strings_iter:
   1094                     arg_string_pattern_parts.append('A')
   1095 
   1096             else:
   1097                 option_tuple = self._parse_optional(arg_string)
   1098                 if option_tuple is None:
   1099                     pattern = 'A'
   1100                 else:
   1101                     option_string_indices[i] = option_tuple
   1102                     pattern = 'O'
   1103                 arg_string_pattern_parts.append(pattern)
   1104 
   1105         arg_strings_pattern = ''.join(arg_string_pattern_parts)
   1106         seen_actions = set()
   1107         seen_non_default_actions = set()
   1108 
   1109         def take_action(action, argument_strings, option_string = None):
   1110             seen_actions.add(action)
   1111             argument_values = self._get_values(action, argument_strings)
   1112             if argument_values is not action.default:
   1113                 seen_non_default_actions.add(action)
   1114                 for conflict_action in action_conflicts.get(action, []):
   1115                     if conflict_action in seen_non_default_actions:
   1116                         msg = _('not allowed with argument %s')
   1117                         action_name = _get_action_name(conflict_action)
   1118                         raise ArgumentError(action, msg % action_name)
   1119 
   1120             if argument_values is not SUPPRESS:
   1121                 action(self, namespace, argument_values, option_string)
   1122 
   1123         def consume_optional(start_index):
   1124             option_tuple = option_string_indices[start_index]
   1125             action, option_string, explicit_arg = option_tuple
   1126             match_argument = self._match_argument
   1127             action_tuples = []
   1128             while True:
   1129                 if action is None:
   1130                     extras.append(arg_strings[start_index])
   1131                     return start_index + 1
   1132                 if explicit_arg is not None:
   1133                     arg_count = match_argument(action, 'A')
   1134                     chars = self.prefix_chars
   1135                     if arg_count == 0 and option_string[1] not in chars:
   1136                         action_tuples.append((action, [], option_string))
   1137                         char = option_string[0]
   1138                         option_string = char + explicit_arg[0]
   1139                         new_explicit_arg = explicit_arg[1:] or None
   1140                         optionals_map = self._option_string_actions
   1141                         if option_string in optionals_map:
   1142                             action = optionals_map[option_string]
   1143                             explicit_arg = new_explicit_arg
   1144                         else:
   1145                             msg = _('ignored explicit argument %r')
   1146                             raise ArgumentError(action, msg % explicit_arg)
   1147                     elif arg_count == 1:
   1148                         stop = start_index + 1
   1149                         args = [explicit_arg]
   1150                         action_tuples.append((action, args, option_string))
   1151                         break
   1152                     else:
   1153                         msg = _('ignored explicit argument %r')
   1154                         raise ArgumentError(action, msg % explicit_arg)
   1155                 else:
   1156                     start = start_index + 1
   1157                     selected_patterns = arg_strings_pattern[start:]
   1158                     arg_count = match_argument(action, selected_patterns)
   1159                     stop = start + arg_count
   1160                     args = arg_strings[start:stop]
   1161                     action_tuples.append((action, args, option_string))
   1162                     break
   1163 
   1164             for action, args, option_string in action_tuples:
   1165                 take_action(action, args, option_string)
   1166 
   1167             return stop
   1168 
   1169         positionals = self._get_positional_actions()
   1170 
   1171         def consume_positionals(start_index):
   1172             match_partial = self._match_arguments_partial
   1173             selected_pattern = arg_strings_pattern[start_index:]
   1174             arg_counts = match_partial(positionals, selected_pattern)
   1175             for action, arg_count in zip(positionals, arg_counts):
   1176                 args = arg_strings[start_index:start_index + arg_count]
   1177                 start_index += arg_count
   1178                 take_action(action, args)
   1179 
   1180             positionals[:] = positionals[len(arg_counts):]
   1181             return start_index
   1182 
   1183         extras = []
   1184         start_index = 0
   1185         if option_string_indices:
   1186             max_option_string_index = max(option_string_indices)
   1187         else:
   1188             max_option_string_index = -1
   1189         while start_index <= max_option_string_index:
   1190             next_option_string_index = min([ index for index in option_string_indices if index >= start_index ])
   1191             if start_index != next_option_string_index:
   1192                 positionals_end_index = consume_positionals(start_index)
   1193                 if positionals_end_index > start_index:
   1194                     start_index = positionals_end_index
   1195                     continue
   1196                 else:
   1197                     start_index = positionals_end_index
   1198             if start_index not in option_string_indices:
   1199                 strings = arg_strings[start_index:next_option_string_index]
   1200                 extras.extend(strings)
   1201                 start_index = next_option_string_index
   1202             start_index = consume_optional(start_index)
   1203 
   1204         stop_index = consume_positionals(start_index)
   1205         extras.extend(arg_strings[stop_index:])
   1206         if positionals:
   1207             self.error(_('too few arguments'))
   1208         for action in self._actions:
   1209             if action.required:
   1210                 if action not in seen_actions:
   1211                     name = _get_action_name(action)
   1212                     self.error(_('argument %s is required') % name)
   1213 
   1214         for group in self._mutually_exclusive_groups:
   1215             if group.required:
   1216                 for action in group._group_actions:
   1217                     if action in seen_non_default_actions:
   1218                         break
   1219                 else:
   1220                     names = [ _get_action_name(action) for action in group._group_actions if action.help is not SUPPRESS ]
   1221                     msg = _('one of the arguments %s is required')
   1222                     self.error(msg % ' '.join(names))
   1223 
   1224         return (namespace, extras)
   1225 
   1226     def _read_args_from_files(self, arg_strings):
   1227         new_arg_strings = []
   1228         for arg_string in arg_strings:
   1229             if arg_string[0] not in self.fromfile_prefix_chars:
   1230                 new_arg_strings.append(arg_string)
   1231             else:
   1232                 try:
   1233                     args_file = open(arg_string[1:])
   1234                     try:
   1235                         arg_strings = []
   1236                         for arg_line in args_file.read().splitlines():
   1237                             for arg in self.convert_arg_line_to_args(arg_line):
   1238                                 arg_strings.append(arg)
   1239 
   1240                         arg_strings = self._read_args_from_files(arg_strings)
   1241                         new_arg_strings.extend(arg_strings)
   1242                     finally:
   1243                         args_file.close()
   1244 
   1245                 except IOError:
   1246                     err = _sys.exc_info()[1]
   1247                     self.error(str(err))
   1248 
   1249         return new_arg_strings
   1250 
   1251     def convert_arg_line_to_args(self, arg_line):
   1252         return [arg_line]
   1253 
   1254     def _match_argument(self, action, arg_strings_pattern):
   1255         nargs_pattern = self._get_nargs_pattern(action)
   1256         match = _re.match(nargs_pattern, arg_strings_pattern)
   1257         if match is None:
   1258             nargs_errors = {None: _('expected one argument'),
   1259              OPTIONAL: _('expected at most one argument'),
   1260              ONE_OR_MORE: _('expected at least one argument')}
   1261             default = _('expected %s argument(s)') % action.nargs
   1262             msg = nargs_errors.get(action.nargs, default)
   1263             raise ArgumentError(action, msg)
   1264         return len(match.group(1))
   1265 
   1266     def _match_arguments_partial(self, actions, arg_strings_pattern):
   1267         result = []
   1268         for i in range(len(actions), 0, -1):
   1269             actions_slice = actions[:i]
   1270             pattern = ''.join([ self._get_nargs_pattern(action) for action in actions_slice ])
   1271             match = _re.match(pattern, arg_strings_pattern)
   1272             if match is not None:
   1273                 result.extend([ len(string) for string in match.groups() ])
   1274                 break
   1275 
   1276         return result
   1277 
   1278     def _parse_optional(self, arg_string):
   1279         if not arg_string:
   1280             return None
   1281         if arg_string[0] not in self.prefix_chars:
   1282             return None
   1283         if arg_string in self._option_string_actions:
   1284             action = self._option_string_actions[arg_string]
   1285             return (action, arg_string, None)
   1286         if len(arg_string) == 1:
   1287             return None
   1288         if '=' in arg_string:
   1289             option_string, explicit_arg = arg_string.split('=', 1)
   1290             if option_string in self._option_string_actions:
   1291                 action = self._option_string_actions[option_string]
   1292                 return (action, option_string, explicit_arg)
   1293         option_tuples = self._get_option_tuples(arg_string)
   1294         if len(option_tuples) > 1:
   1295             options = ', '.join([ option_string for action, option_string, explicit_arg in option_tuples ])
   1296             tup = (arg_string, options)
   1297             self.error(_('ambiguous option: %s could match %s') % tup)
   1298         elif len(option_tuples) == 1:
   1299             option_tuple, = option_tuples
   1300             return option_tuple
   1301         if self._negative_number_matcher.match(arg_string):
   1302             if not self._has_negative_number_optionals:
   1303                 return None
   1304         if ' ' in arg_string:
   1305             return None
   1306         return (None, arg_string, None)
   1307 
   1308     def _get_option_tuples(self, option_string):
   1309         result = []
   1310         chars = self.prefix_chars
   1311         if option_string[0] in chars and option_string[1] in chars:
   1312             if '=' in option_string:
   1313                 option_prefix, explicit_arg = option_string.split('=', 1)
   1314             else:
   1315                 option_prefix = option_string
   1316                 explicit_arg = None
   1317             for option_string in self._option_string_actions:
   1318                 if option_string.startswith(option_prefix):
   1319                     action = self._option_string_actions[option_string]
   1320                     tup = (action, option_string, explicit_arg)
   1321                     result.append(tup)
   1322 
   1323         elif option_string[0] in chars and option_string[1] not in chars:
   1324             option_prefix = option_string
   1325             explicit_arg = None
   1326             short_option_prefix = option_string[:2]
   1327             short_explicit_arg = option_string[2:]
   1328             for option_string in self._option_string_actions:
   1329                 if option_string == short_option_prefix:
   1330                     action = self._option_string_actions[option_string]
   1331                     tup = (action, option_string, short_explicit_arg)
   1332                     result.append(tup)
   1333                 elif option_string.startswith(option_prefix):
   1334                     action = self._option_string_actions[option_string]
   1335                     tup = (action, option_string, explicit_arg)
   1336                     result.append(tup)
   1337 
   1338         else:
   1339             self.error(_('unexpected option string: %s') % option_string)
   1340         return result
   1341 
   1342     def _get_nargs_pattern(self, action):
   1343         nargs = action.nargs
   1344         if nargs is None:
   1345             nargs_pattern = '(-*A-*)'
   1346         elif nargs == OPTIONAL:
   1347             nargs_pattern = '(-*A?-*)'
   1348         elif nargs == ZERO_OR_MORE:
   1349             nargs_pattern = '(-*[A-]*)'
   1350         elif nargs == ONE_OR_MORE:
   1351             nargs_pattern = '(-*A[A-]*)'
   1352         elif nargs == REMAINDER:
   1353             nargs_pattern = '([-AO]*)'
   1354         elif nargs == PARSER:
   1355             nargs_pattern = '(-*A[-AO]*)'
   1356         else:
   1357             nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
   1358         if action.option_strings:
   1359             nargs_pattern = nargs_pattern.replace('-*', '')
   1360             nargs_pattern = nargs_pattern.replace('-', '')
   1361         return nargs_pattern
   1362 
   1363     def _get_values(self, action, arg_strings):
   1364         if action.nargs not in [PARSER, REMAINDER]:
   1365             arg_strings = [ s for s in arg_strings if s != '--' ]
   1366         if not arg_strings and action.nargs == OPTIONAL:
   1367             if action.option_strings:
   1368                 value = action.const
   1369             else:
   1370                 value = action.default
   1371             if isinstance(value, basestring):
   1372                 value = self._get_value(action, value)
   1373                 self._check_value(action, value)
   1374         elif not arg_strings and action.nargs == ZERO_OR_MORE and not action.option_strings:
   1375             if action.default is not None:
   1376                 value = action.default
   1377             else:
   1378                 value = arg_strings
   1379             self._check_value(action, value)
   1380         elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
   1381             arg_string, = arg_strings
   1382             value = self._get_value(action, arg_string)
   1383             self._check_value(action, value)
   1384         elif action.nargs == REMAINDER:
   1385             value = [ self._get_value(action, v) for v in arg_strings ]
   1386         elif action.nargs == PARSER:
   1387             value = [ self._get_value(action, v) for v in arg_strings ]
   1388             self._check_value(action, value[0])
   1389         else:
   1390             value = [ self._get_value(action, v) for v in arg_strings ]
   1391             for v in value:
   1392                 self._check_value(action, v)
   1393 
   1394         return value
   1395 
   1396     def _get_value(self, action, arg_string):
   1397         type_func = self._registry_get('type', action.type, action.type)
   1398         if not _callable(type_func):
   1399             msg = _('%r is not callable')
   1400             raise ArgumentError(action, msg % type_func)
   1401         try:
   1402             result = type_func(arg_string)
   1403         except ArgumentTypeError:
   1404             name = getattr(action.type, '__name__', repr(action.type))
   1405             msg = str(_sys.exc_info()[1])
   1406             raise ArgumentError(action, msg)
   1407         except (TypeError, ValueError):
   1408             name = getattr(action.type, '__name__', repr(action.type))
   1409             msg = _('invalid %s value: %r')
   1410             raise ArgumentError(action, msg % (name, arg_string))
   1411 
   1412         return result
   1413 
   1414     def _check_value(self, action, value):
   1415         if action.choices is not None and value not in action.choices:
   1416             tup = (value, ', '.join(map(repr, action.choices)))
   1417             msg = _('invalid choice: %r (choose from %s)') % tup
   1418             raise ArgumentError(action, msg)
   1419 
   1420     def format_usage(self):
   1421         formatter = self._get_formatter()
   1422         formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)
   1423         return formatter.format_help()
   1424 
   1425     def format_help(self):
   1426         formatter = self._get_formatter()
   1427         formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)
   1428         formatter.add_text(self.description)
   1429         for action_group in self._action_groups:
   1430             formatter.start_section(action_group.title)
   1431             formatter.add_text(action_group.description)
   1432             formatter.add_arguments(action_group._group_actions)
   1433             formatter.end_section()
   1434 
   1435         formatter.add_text(self.epilog)
   1436         return formatter.format_help()
   1437 
   1438     def format_version(self):
   1439         import warnings
   1440         warnings.warn('The format_version method is deprecated -- the "version" argument to ArgumentParser is no longer supported.', DeprecationWarning)
   1441         formatter = self._get_formatter()
   1442         formatter.add_text(self.version)
   1443         return formatter.format_help()
   1444 
   1445     def _get_formatter(self):
   1446         return self.formatter_class(prog=self.prog)
   1447 
   1448     def print_usage(self, file = None):
   1449         if file is None:
   1450             file = _sys.stdout
   1451         self._print_message(self.format_usage(), file)
   1452 
   1453     def print_help(self, file = None):
   1454         if file is None:
   1455             file = _sys.stdout
   1456         self._print_message(self.format_help(), file)
   1457 
   1458     def print_version(self, file = None):
   1459         import warnings
   1460         warnings.warn('The print_version method is deprecated -- the "version" argument to ArgumentParser is no longer supported.', DeprecationWarning)
   1461         self._print_message(self.format_version(), file)
   1462 
   1463     def _print_message(self, message, file = None):
   1464         if message:
   1465             if file is None:
   1466                 file = _sys.stderr
   1467             file.write(message)
   1468 
   1469     def exit(self, status = 0, message = None):
   1470         if message:
   1471             self._print_message(message, _sys.stderr)
   1472         _sys.exit(status)
   1473 
   1474     def error(self, message):
   1475         self.print_usage(_sys.stderr)
   1476         self.exit(2, _('%s: error: %s\n') % (self.prog, message))