home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Calibre / calibre-0.8.18.msi / file_262 / argparse.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-09-09  |  50.2 KB  |  1,646 lines

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