home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 May / maximum-cd-2010-05.iso / DiscContents / boxee-0.9.20.10711.exe / system / python / Lib / optparse.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-07-20  |  45.8 KB  |  1,405 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.4)
  3.  
  4. """optparse - a powerful, extensible, and easy-to-use option parser.
  5.  
  6. By Greg Ward <gward@python.net>
  7.  
  8. Originally distributed as Optik; see http://optik.sourceforge.net/ .
  9.  
  10. If you have problems with this module, please do not file bugs,
  11. patches, or feature requests with Python; instead, use Optik's
  12. SourceForge project page:
  13.   http://sourceforge.net/projects/optik
  14.  
  15. For support, use the optik-users@lists.sourceforge.net mailing list
  16. (http://lists.sourceforge.net/lists/listinfo/optik-users).
  17. """
  18. __version__ = '1.5a2'
  19. __all__ = [
  20.     'Option',
  21.     'SUPPRESS_HELP',
  22.     'SUPPRESS_USAGE',
  23.     'Values',
  24.     'OptionContainer',
  25.     'OptionGroup',
  26.     'OptionParser',
  27.     'HelpFormatter',
  28.     'IndentedHelpFormatter',
  29.     'TitledHelpFormatter',
  30.     'OptParseError',
  31.     'OptionError',
  32.     'OptionConflictError',
  33.     'OptionValueError',
  34.     'BadOptionError']
  35. __copyright__ = '\nCopyright (c) 2001-2004 Gregory P. Ward.  All rights reserved.\nCopyright (c) 2002-2004 Python Software Foundation.  All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n  * Redistributions of source code must retain the above copyright\n    notice, this list of conditions and the following disclaimer.\n\n  * Redistributions in binary form must reproduce the above copyright\n    notice, this list of conditions and the following disclaimer in the\n    documentation and/or other materials provided with the distribution.\n\n  * Neither the name of the author nor the names of its\n    contributors may be used to endorse or promote products derived from\n    this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS\nIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR\nCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\nEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n'
  36. import sys
  37. import os
  38. import types
  39. import textwrap
  40. from gettext import gettext as _
  41.  
  42. def _repr(self):
  43.     return '<%s at 0x%x: %s>' % (self.__class__.__name__, id(self), self)
  44.  
  45.  
  46. class OptParseError(Exception):
  47.     
  48.     def __init__(self, msg):
  49.         self.msg = msg
  50.  
  51.     
  52.     def __str__(self):
  53.         return self.msg
  54.  
  55.  
  56.  
  57. class OptionError(OptParseError):
  58.     '''
  59.     Raised if an Option instance is created with invalid or
  60.     inconsistent arguments.
  61.     '''
  62.     
  63.     def __init__(self, msg, option):
  64.         self.msg = msg
  65.         self.option_id = str(option)
  66.  
  67.     
  68.     def __str__(self):
  69.         if self.option_id:
  70.             return 'option %s: %s' % (self.option_id, self.msg)
  71.         else:
  72.             return self.msg
  73.  
  74.  
  75.  
  76. class OptionConflictError(OptionError):
  77.     '''
  78.     Raised if conflicting options are added to an OptionParser.
  79.     '''
  80.     pass
  81.  
  82.  
  83. class OptionValueError(OptParseError):
  84.     '''
  85.     Raised if an invalid option value is encountered on the command
  86.     line.
  87.     '''
  88.     pass
  89.  
  90.  
  91. class BadOptionError(OptParseError):
  92.     '''
  93.     Raised if an invalid or ambiguous option is seen on the command-line.
  94.     '''
  95.     pass
  96.  
  97.  
  98. class HelpFormatter:
  99.     '''
  100.     Abstract base class for formatting option help.  OptionParser
  101.     instances should use one of the HelpFormatter subclasses for
  102.     formatting help; by default IndentedHelpFormatter is used.
  103.  
  104.     Instance attributes:
  105.       parser : OptionParser
  106.         the controlling OptionParser instance
  107.       indent_increment : int
  108.         the number of columns to indent per nesting level
  109.       max_help_position : int
  110.         the maximum starting column for option help text
  111.       help_position : int
  112.         the calculated starting column for option help text;
  113.         initially the same as the maximum
  114.       width : int
  115.         total number of columns for output (pass None to constructor for
  116.         this value to be taken from the $COLUMNS environment variable)
  117.       level : int
  118.         current indentation level
  119.       current_indent : int
  120.         current indentation level (in columns)
  121.       help_width : int
  122.         number of columns available for option help text (calculated)
  123.       default_tag : str
  124.         text to replace with each option\'s default value, "%default"
  125.         by default.  Set to false value to disable default value expansion.
  126.       option_strings : { Option : str }
  127.         maps Option instances to the snippet of help text explaining
  128.         the syntax of that option, e.g. "-h, --help" or
  129.         "-fFILE, --file=FILE"
  130.       _short_opt_fmt : str
  131.         format string controlling how short options with values are
  132.         printed in help text.  Must be either "%s%s" ("-fFILE") or
  133.         "%s %s" ("-f FILE"), because those are the two syntaxes that
  134.         Optik supports.
  135.       _long_opt_fmt : str
  136.         similar but for long options; must be either "%s %s" ("--file FILE")
  137.         or "%s=%s" ("--file=FILE").
  138.     '''
  139.     NO_DEFAULT_VALUE = 'none'
  140.     
  141.     def __init__(self, indent_increment, max_help_position, width, short_first):
  142.         self.parser = None
  143.         self.indent_increment = indent_increment
  144.         self.help_position = self.max_help_position = max_help_position
  145.         if width is None:
  146.             
  147.             try:
  148.                 width = int(os.environ['COLUMNS'])
  149.             except (KeyError, ValueError):
  150.                 width = 80
  151.  
  152.             width -= 2
  153.         
  154.         self.width = width
  155.         self.current_indent = 0
  156.         self.level = 0
  157.         self.help_width = None
  158.         self.short_first = short_first
  159.         self.default_tag = '%default'
  160.         self.option_strings = { }
  161.         self._short_opt_fmt = '%s %s'
  162.         self._long_opt_fmt = '%s=%s'
  163.  
  164.     
  165.     def set_parser(self, parser):
  166.         self.parser = parser
  167.  
  168.     
  169.     def set_short_opt_delimiter(self, delim):
  170.         if delim not in ('', ' '):
  171.             raise ValueError('invalid metavar delimiter for short options: %r' % delim)
  172.         
  173.         self._short_opt_fmt = '%s' + delim + '%s'
  174.  
  175.     
  176.     def set_long_opt_delimiter(self, delim):
  177.         if delim not in ('=', ' '):
  178.             raise ValueError('invalid metavar delimiter for long options: %r' % delim)
  179.         
  180.         self._long_opt_fmt = '%s' + delim + '%s'
  181.  
  182.     
  183.     def indent(self):
  184.         self.current_indent += self.indent_increment
  185.         self.level += 1
  186.  
  187.     
  188.     def dedent(self):
  189.         self.current_indent -= self.indent_increment
  190.         self.level -= 1
  191.  
  192.     
  193.     def format_usage(self, usage):
  194.         raise NotImplementedError, 'subclasses must implement'
  195.  
  196.     
  197.     def format_heading(self, heading):
  198.         raise NotImplementedError, 'subclasses must implement'
  199.  
  200.     
  201.     def format_description(self, description):
  202.         if not description:
  203.             return ''
  204.         
  205.         desc_width = self.width - self.current_indent
  206.         indent = ' ' * self.current_indent
  207.         return textwrap.fill(description, desc_width, initial_indent = indent, subsequent_indent = indent) + '\n'
  208.  
  209.     
  210.     def expand_default(self, option):
  211.         if self.parser is None or not (self.default_tag):
  212.             return option.help
  213.         
  214.         default_value = self.parser.defaults.get(option.dest)
  215.         if default_value is NO_DEFAULT or default_value is None:
  216.             default_value = self.NO_DEFAULT_VALUE
  217.         
  218.         return option.help.replace(self.default_tag, str(default_value))
  219.  
  220.     
  221.     def format_option(self, option):
  222.         result = []
  223.         opts = self.option_strings[option]
  224.         opt_width = self.help_position - self.current_indent - 2
  225.         if len(opts) > opt_width:
  226.             opts = '%*s%s\n' % (self.current_indent, '', opts)
  227.             indent_first = self.help_position
  228.         else:
  229.             opts = '%*s%-*s  ' % (self.current_indent, '', opt_width, opts)
  230.             indent_first = 0
  231.         result.append(opts)
  232.         if option.help:
  233.             help_text = self.expand_default(option)
  234.             help_lines = textwrap.wrap(help_text, self.help_width)
  235.             result.append('%*s%s\n' % (indent_first, '', help_lines[0]))
  236.             []([ '%*s%s\n' % (self.help_position, '', line) for line in help_lines[1:] ])
  237.         elif opts[-1] != '\n':
  238.             result.append('\n')
  239.         
  240.         return ''.join(result)
  241.  
  242.     
  243.     def store_option_strings(self, parser):
  244.         self.indent()
  245.         max_len = 0
  246.         for opt in parser.option_list:
  247.             strings = self.format_option_strings(opt)
  248.             self.option_strings[opt] = strings
  249.             max_len = max(max_len, len(strings) + self.current_indent)
  250.         
  251.         self.indent()
  252.         for group in parser.option_groups:
  253.             for opt in group.option_list:
  254.                 strings = self.format_option_strings(opt)
  255.                 self.option_strings[opt] = strings
  256.                 max_len = max(max_len, len(strings) + self.current_indent)
  257.             
  258.         
  259.         self.dedent()
  260.         self.dedent()
  261.         self.help_position = min(max_len + 2, self.max_help_position)
  262.         self.help_width = self.width - self.help_position
  263.  
  264.     
  265.     def format_option_strings(self, option):
  266.         '''Return a comma-separated list of option strings & metavariables.'''
  267.         return ', '.join(opts)
  268.  
  269.  
  270.  
  271. class IndentedHelpFormatter(HelpFormatter):
  272.     '''Format help with indented section bodies.
  273.     '''
  274.     
  275.     def __init__(self, indent_increment = 2, max_help_position = 24, width = None, short_first = 1):
  276.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  277.  
  278.     
  279.     def format_usage(self, usage):
  280.         return _('usage: %s\n') % usage
  281.  
  282.     
  283.     def format_heading(self, heading):
  284.         return '%*s%s:\n' % (self.current_indent, '', heading)
  285.  
  286.  
  287.  
  288. class TitledHelpFormatter(HelpFormatter):
  289.     '''Format help with underlined section headers.
  290.     '''
  291.     
  292.     def __init__(self, indent_increment = 0, max_help_position = 24, width = None, short_first = 0):
  293.         HelpFormatter.__init__(self, indent_increment, max_help_position, width, short_first)
  294.  
  295.     
  296.     def format_usage(self, usage):
  297.         return '%s  %s\n' % (self.format_heading(_('Usage')), usage)
  298.  
  299.     
  300.     def format_heading(self, heading):
  301.         return '%s\n%s\n' % (heading, '=-'[self.level] * len(heading))
  302.  
  303.  
  304. _builtin_cvt = {
  305.     'int': (int, _('integer')),
  306.     'long': (long, _('long integer')),
  307.     'float': (float, _('floating-point')),
  308.     'complex': (complex, _('complex')) }
  309.  
  310. def check_builtin(option, opt, value):
  311.     (cvt, what) = _builtin_cvt[option.type]
  312.     
  313.     try:
  314.         return cvt(value)
  315.     except ValueError:
  316.         raise OptionValueError(_('option %s: invalid %s value: %r') % (opt, what, value))
  317.  
  318.  
  319.  
  320. def check_choice(option, opt, value):
  321.     if value in option.choices:
  322.         return value
  323.     else:
  324.         choices = ', '.join(map(repr, option.choices))
  325.         raise OptionValueError(_('option %s: invalid choice: %r (choose from %s)') % (opt, value, choices))
  326.  
  327. NO_DEFAULT = ('NO', 'DEFAULT')
  328.  
  329. class Option:
  330.     '''
  331.     Instance attributes:
  332.       _short_opts : [string]
  333.       _long_opts : [string]
  334.  
  335.       action : string
  336.       type : string
  337.       dest : string
  338.       default : any
  339.       nargs : int
  340.       const : any
  341.       choices : [string]
  342.       callback : function
  343.       callback_args : (any*)
  344.       callback_kwargs : { string : any }
  345.       help : string
  346.       metavar : string
  347.     '''
  348.     ATTRS = [
  349.         'action',
  350.         'type',
  351.         'dest',
  352.         'default',
  353.         'nargs',
  354.         'const',
  355.         'choices',
  356.         'callback',
  357.         'callback_args',
  358.         'callback_kwargs',
  359.         'help',
  360.         'metavar']
  361.     ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'count', 'callback', 'help', 'version')
  362.     STORE_ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'count')
  363.     TYPED_ACTIONS = ('store', 'append', 'callback')
  364.     ALWAYS_TYPED_ACTIONS = ('store', 'append')
  365.     TYPES = ('string', 'int', 'long', 'float', 'complex', 'choice')
  366.     TYPE_CHECKER = {
  367.         'int': check_builtin,
  368.         'long': check_builtin,
  369.         'float': check_builtin,
  370.         'complex': check_builtin,
  371.         'choice': check_choice }
  372.     CHECK_METHODS = None
  373.     
  374.     def __init__(self, *opts, **attrs):
  375.         self._short_opts = []
  376.         self._long_opts = []
  377.         opts = self._check_opt_strings(opts)
  378.         self._set_opt_strings(opts)
  379.         self._set_attrs(attrs)
  380.         for checker in self.CHECK_METHODS:
  381.             checker(self)
  382.         
  383.  
  384.     
  385.     def _check_opt_strings(self, opts):
  386.         opts = filter(None, opts)
  387.         if not opts:
  388.             raise TypeError('at least one option string must be supplied')
  389.         
  390.         return opts
  391.  
  392.     
  393.     def _set_opt_strings(self, opts):
  394.         for opt in opts:
  395.             if len(opt) < 2:
  396.                 raise OptionError('invalid option string %r: must be at least two characters long' % opt, self)
  397.                 continue
  398.             if len(opt) == 2:
  399.                 if not opt[0] == '-' and opt[1] != '-':
  400.                     raise OptionError('invalid short option string %r: must be of the form -x, (x any non-dash char)' % opt, self)
  401.                 
  402.                 self._short_opts.append(opt)
  403.                 continue
  404.             if not opt[0:2] == '--' and opt[2] != '-':
  405.                 raise OptionError('invalid long option string %r: must start with --, followed by non-dash' % opt, self)
  406.             
  407.             self._long_opts.append(opt)
  408.         
  409.  
  410.     
  411.     def _set_attrs(self, attrs):
  412.         for attr in self.ATTRS:
  413.             if attrs.has_key(attr):
  414.                 setattr(self, attr, attrs[attr])
  415.                 del attrs[attr]
  416.                 continue
  417.             if attr == 'default':
  418.                 setattr(self, attr, NO_DEFAULT)
  419.                 continue
  420.             setattr(self, attr, None)
  421.         
  422.         if attrs:
  423.             attrs = attrs.keys()
  424.             attrs.sort()
  425.             raise OptionError('invalid keyword arguments: %s' % ', '.join(attrs), self)
  426.         
  427.  
  428.     
  429.     def _check_action(self):
  430.         if self.action is None:
  431.             self.action = 'store'
  432.         elif self.action not in self.ACTIONS:
  433.             raise OptionError('invalid action: %r' % self.action, self)
  434.         
  435.  
  436.     
  437.     def _check_type(self):
  438.         if self.type is None:
  439.             if self.action in self.ALWAYS_TYPED_ACTIONS:
  440.                 if self.choices is not None:
  441.                     self.type = 'choice'
  442.                 else:
  443.                     self.type = 'string'
  444.             
  445.         elif type(self.type) is type:
  446.             self.type = self.type.__name__
  447.         
  448.         if self.type == 'str':
  449.             self.type = 'string'
  450.         
  451.         if self.type not in self.TYPES:
  452.             raise OptionError('invalid option type: %r' % self.type, self)
  453.         
  454.         if self.action not in self.TYPED_ACTIONS:
  455.             raise OptionError('must not supply a type for action %r' % self.action, self)
  456.         
  457.  
  458.     
  459.     def _check_choice(self):
  460.         if self.type == 'choice':
  461.             if self.choices is None:
  462.                 raise OptionError("must supply a list of choices for type 'choice'", self)
  463.             elif type(self.choices) not in (types.TupleType, types.ListType):
  464.                 raise OptionError("choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self)
  465.             
  466.         elif self.choices is not None:
  467.             raise OptionError('must not supply choices for type %r' % self.type, self)
  468.         
  469.  
  470.     
  471.     def _check_dest(self):
  472.         if not self.action in self.STORE_ACTIONS:
  473.             pass
  474.         takes_value = self.type is not None
  475.         if self.dest is None and takes_value:
  476.             if self._long_opts:
  477.                 self.dest = self._long_opts[0][2:].replace('-', '_')
  478.             else:
  479.                 self.dest = self._short_opts[0][1]
  480.         
  481.  
  482.     
  483.     def _check_const(self):
  484.         if self.action != 'store_const' and self.const is not None:
  485.             raise OptionError("'const' must not be supplied for action %r" % self.action, self)
  486.         
  487.  
  488.     
  489.     def _check_nargs(self):
  490.         if self.action in self.TYPED_ACTIONS:
  491.             if self.nargs is None:
  492.                 self.nargs = 1
  493.             
  494.         elif self.nargs is not None:
  495.             raise OptionError("'nargs' must not be supplied for action %r" % self.action, self)
  496.         
  497.  
  498.     
  499.     def _check_callback(self):
  500.         if self.action == 'callback':
  501.             if not callable(self.callback):
  502.                 raise OptionError('callback not callable: %r' % self.callback, self)
  503.             
  504.             if self.callback_args is not None and type(self.callback_args) is not types.TupleType:
  505.                 raise OptionError('callback_args, if supplied, must be a tuple: not %r' % self.callback_args, self)
  506.             
  507.             if self.callback_kwargs is not None and type(self.callback_kwargs) is not types.DictType:
  508.                 raise OptionError('callback_kwargs, if supplied, must be a dict: not %r' % self.callback_kwargs, self)
  509.             
  510.         elif self.callback is not None:
  511.             raise OptionError('callback supplied (%r) for non-callback option' % self.callback, self)
  512.         
  513.         if self.callback_args is not None:
  514.             raise OptionError('callback_args supplied for non-callback option', self)
  515.         
  516.         if self.callback_kwargs is not None:
  517.             raise OptionError('callback_kwargs supplied for non-callback option', self)
  518.         
  519.  
  520.     CHECK_METHODS = [
  521.         _check_action,
  522.         _check_type,
  523.         _check_choice,
  524.         _check_dest,
  525.         _check_const,
  526.         _check_nargs,
  527.         _check_callback]
  528.     
  529.     def __str__(self):
  530.         return '/'.join(self._short_opts + self._long_opts)
  531.  
  532.     __repr__ = _repr
  533.     
  534.     def takes_value(self):
  535.         return self.type is not None
  536.  
  537.     
  538.     def get_opt_string(self):
  539.         if self._long_opts:
  540.             return self._long_opts[0]
  541.         else:
  542.             return self._short_opts[0]
  543.  
  544.     
  545.     def check_value(self, opt, value):
  546.         checker = self.TYPE_CHECKER.get(self.type)
  547.         if checker is None:
  548.             return value
  549.         else:
  550.             return checker(self, opt, value)
  551.  
  552.     
  553.     def convert_value(self, opt, value):
  554.         pass
  555.  
  556.     
  557.     def process(self, opt, value, values, parser):
  558.         value = self.convert_value(opt, value)
  559.         return self.take_action(self.action, self.dest, opt, value, values, parser)
  560.  
  561.     
  562.     def take_action(self, action, dest, opt, value, values, parser):
  563.         if action == 'store':
  564.             setattr(values, dest, value)
  565.         elif action == 'store_const':
  566.             setattr(values, dest, self.const)
  567.         elif action == 'store_true':
  568.             setattr(values, dest, True)
  569.         elif action == 'store_false':
  570.             setattr(values, dest, False)
  571.         elif action == 'append':
  572.             values.ensure_value(dest, []).append(value)
  573.         elif action == 'count':
  574.             setattr(values, dest, values.ensure_value(dest, 0) + 1)
  575.         elif action == 'callback':
  576.             if not self.callback_args:
  577.                 pass
  578.             args = ()
  579.             if not self.callback_kwargs:
  580.                 pass
  581.             kwargs = { }
  582.             self.callback(self, opt, value, parser, *args, **kwargs)
  583.         elif action == 'help':
  584.             parser.print_help()
  585.             parser.exit()
  586.         elif action == 'version':
  587.             parser.print_version()
  588.             parser.exit()
  589.         else:
  590.             raise RuntimeError, 'unknown action %r' % self.action
  591.         return 1
  592.  
  593.  
  594. SUPPRESS_HELP = 'SUPPRESS' + 'HELP'
  595. SUPPRESS_USAGE = 'SUPPRESS' + 'USAGE'
  596.  
  597. try:
  598.     (True, False)
  599. except NameError:
  600.     (True, False) = (1, 0)
  601.  
  602.  
  603. try:
  604.     basestring
  605. except NameError:
  606.     basestring = (str, unicode)
  607.  
  608.  
  609. class Values:
  610.     
  611.     def __init__(self, defaults = None):
  612.         if defaults:
  613.             for attr, val in defaults.items():
  614.                 setattr(self, attr, val)
  615.             
  616.         
  617.  
  618.     
  619.     def __str__(self):
  620.         return str(self.__dict__)
  621.  
  622.     __repr__ = _repr
  623.     
  624.     def __eq__(self, other):
  625.         if isinstance(other, Values):
  626.             return self.__dict__ == other.__dict__
  627.         elif isinstance(other, dict):
  628.             return self.__dict__ == other
  629.         else:
  630.             return False
  631.  
  632.     
  633.     def __ne__(self, other):
  634.         return not (self == other)
  635.  
  636.     
  637.     def _update_careful(self, dict):
  638.         '''
  639.         Update the option values from an arbitrary dictionary, but only
  640.         use keys from dict that already have a corresponding attribute
  641.         in self.  Any keys in dict without a corresponding attribute
  642.         are silently ignored.
  643.         '''
  644.         for attr in dir(self):
  645.             if dict.has_key(attr):
  646.                 dval = dict[attr]
  647.                 if dval is not None:
  648.                     setattr(self, attr, dval)
  649.                 
  650.             dval is not None
  651.         
  652.  
  653.     
  654.     def _update_loose(self, dict):
  655.         '''
  656.         Update the option values from an arbitrary dictionary,
  657.         using all keys from the dictionary regardless of whether
  658.         they have a corresponding attribute in self or not.
  659.         '''
  660.         self.__dict__.update(dict)
  661.  
  662.     
  663.     def _update(self, dict, mode):
  664.         if mode == 'careful':
  665.             self._update_careful(dict)
  666.         elif mode == 'loose':
  667.             self._update_loose(dict)
  668.         else:
  669.             raise ValueError, 'invalid update mode: %r' % mode
  670.  
  671.     
  672.     def read_module(self, modname, mode = 'careful'):
  673.         __import__(modname)
  674.         mod = sys.modules[modname]
  675.         self._update(vars(mod), mode)
  676.  
  677.     
  678.     def read_file(self, filename, mode = 'careful'):
  679.         vars = { }
  680.         execfile(filename, vars)
  681.         self._update(vars, mode)
  682.  
  683.     
  684.     def ensure_value(self, attr, value):
  685.         if not hasattr(self, attr) or getattr(self, attr) is None:
  686.             setattr(self, attr, value)
  687.         
  688.         return getattr(self, attr)
  689.  
  690.  
  691.  
  692. class OptionContainer:
  693.     '''
  694.     Abstract base class.
  695.  
  696.     Class attributes:
  697.       standard_option_list : [Option]
  698.         list of standard options that will be accepted by all instances
  699.         of this parser class (intended to be overridden by subclasses).
  700.  
  701.     Instance attributes:
  702.       option_list : [Option]
  703.         the list of Option objects contained by this OptionContainer
  704.       _short_opt : { string : Option }
  705.         dictionary mapping short option strings, eg. "-f" or "-X",
  706.         to the Option instances that implement them.  If an Option
  707.         has multiple short option strings, it will appears in this
  708.         dictionary multiple times. [1]
  709.       _long_opt : { string : Option }
  710.         dictionary mapping long option strings, eg. "--file" or
  711.         "--exclude", to the Option instances that implement them.
  712.         Again, a given Option can occur multiple times in this
  713.         dictionary. [1]
  714.       defaults : { string : any }
  715.         dictionary mapping option destination names to default
  716.         values for each destination [1]
  717.  
  718.     [1] These mappings are common to (shared by) all components of the
  719.         controlling OptionParser, where they are initially created.
  720.  
  721.     '''
  722.     
  723.     def __init__(self, option_class, conflict_handler, description):
  724.         self._create_option_list()
  725.         self.option_class = option_class
  726.         self.set_conflict_handler(conflict_handler)
  727.         self.set_description(description)
  728.  
  729.     
  730.     def _create_option_mappings(self):
  731.         self._short_opt = { }
  732.         self._long_opt = { }
  733.         self.defaults = { }
  734.  
  735.     
  736.     def _share_option_mappings(self, parser):
  737.         self._short_opt = parser._short_opt
  738.         self._long_opt = parser._long_opt
  739.         self.defaults = parser.defaults
  740.  
  741.     
  742.     def set_conflict_handler(self, handler):
  743.         if handler not in ('error', 'resolve'):
  744.             raise ValueError, 'invalid conflict_resolution value %r' % handler
  745.         
  746.         self.conflict_handler = handler
  747.  
  748.     
  749.     def set_description(self, description):
  750.         self.description = description
  751.  
  752.     
  753.     def get_description(self):
  754.         return self.description
  755.  
  756.     
  757.     def _check_conflict(self, option):
  758.         conflict_opts = []
  759.         for opt in option._short_opts:
  760.             if self._short_opt.has_key(opt):
  761.                 conflict_opts.append((opt, self._short_opt[opt]))
  762.                 continue
  763.         
  764.         for opt in option._long_opts:
  765.             if self._long_opt.has_key(opt):
  766.                 conflict_opts.append((opt, self._long_opt[opt]))
  767.                 continue
  768.         
  769.         if conflict_opts:
  770.             handler = self.conflict_handler
  771.             if handler == 'error':
  772.                 raise ', '.join([] % []([ co[0] for co in conflict_opts ]), option)
  773.             elif handler == 'resolve':
  774.                 for opt, c_option in conflict_opts:
  775.                     if opt.startswith('--'):
  776.                         c_option._long_opts.remove(opt)
  777.                         del self._long_opt[opt]
  778.                     else:
  779.                         c_option._short_opts.remove(opt)
  780.                         del self._short_opt[opt]
  781.                     if not c_option._short_opts or c_option._long_opts:
  782.                         c_option.container.option_list.remove(c_option)
  783.                         continue
  784.                 
  785.             
  786.         
  787.  
  788.     
  789.     def add_option(self, *args, **kwargs):
  790.         '''add_option(Option)
  791.            add_option(opt_str, ..., kwarg=val, ...)
  792.         '''
  793.         if type(args[0]) is types.StringType:
  794.             option = self.option_class(*args, **kwargs)
  795.         elif len(args) == 1 and not kwargs:
  796.             option = args[0]
  797.             if not isinstance(option, Option):
  798.                 raise TypeError, 'not an Option instance: %r' % option
  799.             
  800.         else:
  801.             raise TypeError, 'invalid arguments'
  802.         self._check_conflict(option)
  803.         self.option_list.append(option)
  804.         option.container = self
  805.         for opt in option._short_opts:
  806.             self._short_opt[opt] = option
  807.         
  808.         for opt in option._long_opts:
  809.             self._long_opt[opt] = option
  810.         
  811.         if option.dest is not None:
  812.             if option.default is not NO_DEFAULT:
  813.                 self.defaults[option.dest] = option.default
  814.             elif not self.defaults.has_key(option.dest):
  815.                 self.defaults[option.dest] = None
  816.             
  817.         
  818.         return option
  819.  
  820.     
  821.     def add_options(self, option_list):
  822.         for option in option_list:
  823.             self.add_option(option)
  824.         
  825.  
  826.     
  827.     def get_option(self, opt_str):
  828.         if not self._short_opt.get(opt_str):
  829.             pass
  830.         return self._long_opt.get(opt_str)
  831.  
  832.     
  833.     def has_option(self, opt_str):
  834.         if not self._short_opt.has_key(opt_str):
  835.             pass
  836.         return self._long_opt.has_key(opt_str)
  837.  
  838.     
  839.     def remove_option(self, opt_str):
  840.         option = self._short_opt.get(opt_str)
  841.         if option is None:
  842.             option = self._long_opt.get(opt_str)
  843.         
  844.         if option is None:
  845.             raise ValueError('no such option %r' % opt_str)
  846.         
  847.         for opt in option._short_opts:
  848.             del self._short_opt[opt]
  849.         
  850.         for opt in option._long_opts:
  851.             del self._long_opt[opt]
  852.         
  853.         option.container.option_list.remove(option)
  854.  
  855.     
  856.     def format_option_help(self, formatter):
  857.         if not self.option_list:
  858.             return ''
  859.         
  860.         result = []
  861.         for option in self.option_list:
  862.             if option.help is not SUPPRESS_HELP:
  863.                 result.append(formatter.format_option(option))
  864.                 continue
  865.         
  866.         return ''.join(result)
  867.  
  868.     
  869.     def format_description(self, formatter):
  870.         return formatter.format_description(self.get_description())
  871.  
  872.     
  873.     def format_help(self, formatter):
  874.         result = []
  875.         if self.description:
  876.             result.append(self.format_description(formatter))
  877.         
  878.         if self.option_list:
  879.             result.append(self.format_option_help(formatter))
  880.         
  881.         return '\n'.join(result)
  882.  
  883.  
  884.  
  885. class OptionGroup(OptionContainer):
  886.     
  887.     def __init__(self, parser, title, description = None):
  888.         self.parser = parser
  889.         OptionContainer.__init__(self, parser.option_class, parser.conflict_handler, description)
  890.         self.title = title
  891.  
  892.     
  893.     def _create_option_list(self):
  894.         self.option_list = []
  895.         self._share_option_mappings(self.parser)
  896.  
  897.     
  898.     def set_title(self, title):
  899.         self.title = title
  900.  
  901.     
  902.     def format_help(self, formatter):
  903.         result = formatter.format_heading(self.title)
  904.         formatter.indent()
  905.         result += OptionContainer.format_help(self, formatter)
  906.         formatter.dedent()
  907.         return result
  908.  
  909.  
  910.  
  911. class OptionParser(OptionContainer):
  912.     '''
  913.     Class attributes:
  914.       standard_option_list : [Option]
  915.         list of standard options that will be accepted by all instances
  916.         of this parser class (intended to be overridden by subclasses).
  917.  
  918.     Instance attributes:
  919.       usage : string
  920.         a usage string for your program.  Before it is displayed
  921.         to the user, "%prog" will be expanded to the name of
  922.         your program (self.prog or os.path.basename(sys.argv[0])).
  923.       prog : string
  924.         the name of the current program (to override
  925.         os.path.basename(sys.argv[0])).
  926.  
  927.       option_groups : [OptionGroup]
  928.         list of option groups in this parser (option groups are
  929.         irrelevant for parsing the command-line, but very useful
  930.         for generating help)
  931.  
  932.       allow_interspersed_args : bool = true
  933.         if true, positional arguments may be interspersed with options.
  934.         Assuming -a and -b each take a single argument, the command-line
  935.           -ablah foo bar -bboo baz
  936.         will be interpreted the same as
  937.           -ablah -bboo -- foo bar baz
  938.         If this flag were false, that command line would be interpreted as
  939.           -ablah -- foo bar -bboo baz
  940.         -- ie. we stop processing options as soon as we see the first
  941.         non-option argument.  (This is the tradition followed by
  942.         Python\'s getopt module, Perl\'s Getopt::Std, and other argument-
  943.         parsing libraries, but it is generally annoying to users.)
  944.  
  945.       process_default_values : bool = true
  946.         if true, option default values are processed similarly to option
  947.         values from the command line: that is, they are passed to the
  948.         type-checking function for the option\'s type (as long as the
  949.         default value is a string).  (This really only matters if you
  950.         have defined custom types; see SF bug #955889.)  Set it to false
  951.         to restore the behaviour of Optik 1.4.1 and earlier.
  952.  
  953.       rargs : [string]
  954.         the argument list currently being parsed.  Only set when
  955.         parse_args() is active, and continually trimmed down as
  956.         we consume arguments.  Mainly there for the benefit of
  957.         callback options.
  958.       largs : [string]
  959.         the list of leftover arguments that we have skipped while
  960.         parsing options.  If allow_interspersed_args is false, this
  961.         list is always empty.
  962.       values : Values
  963.         the set of option values currently being accumulated.  Only
  964.         set when parse_args() is active.  Also mainly for callbacks.
  965.  
  966.     Because of the \'rargs\', \'largs\', and \'values\' attributes,
  967.     OptionParser is not thread-safe.  If, for some perverse reason, you
  968.     need to parse command-line arguments simultaneously in different
  969.     threads, use different OptionParser instances.
  970.  
  971.     '''
  972.     standard_option_list = []
  973.     
  974.     def __init__(self, usage = None, option_list = None, option_class = Option, version = None, conflict_handler = 'error', description = None, formatter = None, add_help_option = True, prog = None):
  975.         OptionContainer.__init__(self, option_class, conflict_handler, description)
  976.         self.set_usage(usage)
  977.         self.prog = prog
  978.         self.version = version
  979.         self.allow_interspersed_args = True
  980.         self.process_default_values = True
  981.         if formatter is None:
  982.             formatter = IndentedHelpFormatter()
  983.         
  984.         self.formatter = formatter
  985.         self.formatter.set_parser(self)
  986.         self._populate_option_list(option_list, add_help = add_help_option)
  987.         self._init_parsing_state()
  988.  
  989.     
  990.     def _create_option_list(self):
  991.         self.option_list = []
  992.         self.option_groups = []
  993.         self._create_option_mappings()
  994.  
  995.     
  996.     def _add_help_option(self):
  997.         self.add_option('-h', '--help', action = 'help', help = _('show this help message and exit'))
  998.  
  999.     
  1000.     def _add_version_option(self):
  1001.         self.add_option('--version', action = 'version', help = _("show program's version number and exit"))
  1002.  
  1003.     
  1004.     def _populate_option_list(self, option_list, add_help = True):
  1005.         if self.standard_option_list:
  1006.             self.add_options(self.standard_option_list)
  1007.         
  1008.         if option_list:
  1009.             self.add_options(option_list)
  1010.         
  1011.         if self.version:
  1012.             self._add_version_option()
  1013.         
  1014.         if add_help:
  1015.             self._add_help_option()
  1016.         
  1017.  
  1018.     
  1019.     def _init_parsing_state(self):
  1020.         self.rargs = None
  1021.         self.largs = None
  1022.         self.values = None
  1023.  
  1024.     
  1025.     def set_usage(self, usage):
  1026.         if usage is None:
  1027.             self.usage = _('%prog [options]')
  1028.         elif usage is SUPPRESS_USAGE:
  1029.             self.usage = None
  1030.         elif usage.startswith('usage:' + ' '):
  1031.             self.usage = usage[7:]
  1032.         else:
  1033.             self.usage = usage
  1034.  
  1035.     
  1036.     def enable_interspersed_args(self):
  1037.         self.allow_interspersed_args = True
  1038.  
  1039.     
  1040.     def disable_interspersed_args(self):
  1041.         self.allow_interspersed_args = False
  1042.  
  1043.     
  1044.     def set_process_default_values(self, process):
  1045.         self.process_default_values = process
  1046.  
  1047.     
  1048.     def set_default(self, dest, value):
  1049.         self.defaults[dest] = value
  1050.  
  1051.     
  1052.     def set_defaults(self, **kwargs):
  1053.         self.defaults.update(kwargs)
  1054.  
  1055.     
  1056.     def _get_all_options(self):
  1057.         options = self.option_list[:]
  1058.         for group in self.option_groups:
  1059.             options.extend(group.option_list)
  1060.         
  1061.         return options
  1062.  
  1063.     
  1064.     def get_default_values(self):
  1065.         if not self.process_default_values:
  1066.             return Values(self.defaults)
  1067.         
  1068.         defaults = self.defaults.copy()
  1069.         for option in self._get_all_options():
  1070.             default = defaults.get(option.dest)
  1071.             if isinstance(default, basestring):
  1072.                 opt_str = option.get_opt_string()
  1073.                 defaults[option.dest] = option.check_value(opt_str, default)
  1074.                 continue
  1075.         
  1076.         return Values(defaults)
  1077.  
  1078.     
  1079.     def add_option_group(self, *args, **kwargs):
  1080.         if type(args[0]) is types.StringType:
  1081.             group = OptionGroup(self, *args, **kwargs)
  1082.         elif len(args) == 1 and not kwargs:
  1083.             group = args[0]
  1084.             if not isinstance(group, OptionGroup):
  1085.                 raise TypeError, 'not an OptionGroup instance: %r' % group
  1086.             
  1087.             if group.parser is not self:
  1088.                 raise ValueError, 'invalid OptionGroup (wrong parser)'
  1089.             
  1090.         else:
  1091.             raise TypeError, 'invalid arguments'
  1092.         self.option_groups.append(group)
  1093.         return group
  1094.  
  1095.     
  1096.     def get_option_group(self, opt_str):
  1097.         if not self._short_opt.get(opt_str):
  1098.             pass
  1099.         option = self._long_opt.get(opt_str)
  1100.         if option and option.container is not self:
  1101.             return option.container
  1102.         
  1103.  
  1104.     
  1105.     def _get_args(self, args):
  1106.         if args is None:
  1107.             return sys.argv[1:]
  1108.         else:
  1109.             return args[:]
  1110.  
  1111.     
  1112.     def parse_args(self, args = None, values = None):
  1113.         """
  1114.         parse_args(args : [string] = sys.argv[1:],
  1115.                    values : Values = None)
  1116.         -> (values : Values, args : [string])
  1117.  
  1118.         Parse the command-line options found in 'args' (default:
  1119.         sys.argv[1:]).  Any errors result in a call to 'error()', which
  1120.         by default prints the usage message to stderr and calls
  1121.         sys.exit() with an error message.  On success returns a pair
  1122.         (values, args) where 'values' is an Values instance (with all
  1123.         your option values) and 'args' is the list of arguments left
  1124.         over after parsing options.
  1125.         """
  1126.         rargs = self._get_args(args)
  1127.         if values is None:
  1128.             values = self.get_default_values()
  1129.         
  1130.         self.rargs = rargs
  1131.         self.largs = largs = []
  1132.         self.values = values
  1133.         
  1134.         try:
  1135.             stop = self._process_args(largs, rargs, values)
  1136.         except (BadOptionError, OptionValueError):
  1137.             err = None
  1138.             self.error(err.msg)
  1139.  
  1140.         args = largs + rargs
  1141.         return self.check_values(values, args)
  1142.  
  1143.     
  1144.     def check_values(self, values, args):
  1145.         '''
  1146.         check_values(values : Values, args : [string])
  1147.         -> (values : Values, args : [string])
  1148.  
  1149.         Check that the supplied option values and leftover arguments are
  1150.         valid.  Returns the option values and leftover arguments
  1151.         (possibly adjusted, possibly completely new -- whatever you
  1152.         like).  Default implementation just returns the passed-in
  1153.         values; subclasses may override as desired.
  1154.         '''
  1155.         return (values, args)
  1156.  
  1157.     
  1158.     def _process_args(self, largs, rargs, values):
  1159.         """_process_args(largs : [string],
  1160.                          rargs : [string],
  1161.                          values : Values)
  1162.  
  1163.         Process command-line arguments and populate 'values', consuming
  1164.         options and arguments from 'rargs'.  If 'allow_interspersed_args' is
  1165.         false, stop at the first non-option argument.  If true, accumulate any
  1166.         interspersed non-option arguments in 'largs'.
  1167.         """
  1168.         while rargs:
  1169.             arg = rargs[0]
  1170.             if arg == '--':
  1171.                 del rargs[0]
  1172.                 return None
  1173.                 continue
  1174.             if arg[0:2] == '--':
  1175.                 self._process_long_opt(rargs, values)
  1176.                 continue
  1177.             if arg[:1] == '-' and len(arg) > 1:
  1178.                 self._process_short_opts(rargs, values)
  1179.                 continue
  1180.             if self.allow_interspersed_args:
  1181.                 largs.append(arg)
  1182.                 del rargs[0]
  1183.                 continue
  1184.             return None
  1185.  
  1186.     
  1187.     def _match_long_opt(self, opt):
  1188.         """_match_long_opt(opt : string) -> string
  1189.  
  1190.         Determine which long option string 'opt' matches, ie. which one
  1191.         it is an unambiguous abbrevation for.  Raises BadOptionError if
  1192.         'opt' doesn't unambiguously match any long option string.
  1193.         """
  1194.         return _match_abbrev(opt, self._long_opt)
  1195.  
  1196.     
  1197.     def _process_long_opt(self, rargs, values):
  1198.         arg = rargs.pop(0)
  1199.         if '=' in arg:
  1200.             (opt, next_arg) = arg.split('=', 1)
  1201.             rargs.insert(0, next_arg)
  1202.             had_explicit_value = True
  1203.         else:
  1204.             opt = arg
  1205.             had_explicit_value = False
  1206.         opt = self._match_long_opt(opt)
  1207.         option = self._long_opt[opt]
  1208.         if option.takes_value():
  1209.             nargs = option.nargs
  1210.             if len(rargs) < nargs:
  1211.                 if nargs == 1:
  1212.                     self.error(_('%s option requires an argument') % opt)
  1213.                 else:
  1214.                     self.error(_('%s option requires %d arguments') % (opt, nargs))
  1215.             elif nargs == 1:
  1216.                 value = rargs.pop(0)
  1217.             else:
  1218.                 value = tuple(rargs[0:nargs])
  1219.                 del rargs[0:nargs]
  1220.         elif had_explicit_value:
  1221.             self.error(_('%s option does not take a value') % opt)
  1222.         else:
  1223.             value = None
  1224.         option.process(opt, value, values, self)
  1225.  
  1226.     
  1227.     def _process_short_opts(self, rargs, values):
  1228.         arg = rargs.pop(0)
  1229.         stop = False
  1230.         i = 1
  1231.         for ch in arg[1:]:
  1232.             opt = '-' + ch
  1233.             option = self._short_opt.get(opt)
  1234.             i += 1
  1235.             if not option:
  1236.                 self.error(_('no such option: %s') % opt)
  1237.             
  1238.             if option.takes_value():
  1239.                 if i < len(arg):
  1240.                     rargs.insert(0, arg[i:])
  1241.                     stop = True
  1242.                 
  1243.                 nargs = option.nargs
  1244.                 if len(rargs) < nargs:
  1245.                     if nargs == 1:
  1246.                         self.error(_('%s option requires an argument') % opt)
  1247.                     else:
  1248.                         self.error(_('%s option requires %d arguments') % (opt, nargs))
  1249.                 elif nargs == 1:
  1250.                     value = rargs.pop(0)
  1251.                 else:
  1252.                     value = tuple(rargs[0:nargs])
  1253.                     del rargs[0:nargs]
  1254.             else:
  1255.                 value = None
  1256.             option.process(opt, value, values, self)
  1257.             if stop:
  1258.                 break
  1259.                 continue
  1260.         
  1261.  
  1262.     
  1263.     def get_prog_name(self):
  1264.         if self.prog is None:
  1265.             return os.path.basename(sys.argv[0])
  1266.         else:
  1267.             return self.prog
  1268.  
  1269.     
  1270.     def expand_prog_name(self, s):
  1271.         return s.replace('%prog', self.get_prog_name())
  1272.  
  1273.     
  1274.     def get_description(self):
  1275.         return self.expand_prog_name(self.description)
  1276.  
  1277.     
  1278.     def exit(self, status = 0, msg = None):
  1279.         if msg:
  1280.             sys.stderr.write(msg)
  1281.         
  1282.         sys.exit(status)
  1283.  
  1284.     
  1285.     def error(self, msg):
  1286.         """error(msg : string)
  1287.  
  1288.         Print a usage message incorporating 'msg' to stderr and exit.
  1289.         If you override this in a subclass, it should not return -- it
  1290.         should either exit or raise an exception.
  1291.         """
  1292.         self.print_usage(sys.stderr)
  1293.         self.exit(2, '%s: error: %s\n' % (self.get_prog_name(), msg))
  1294.  
  1295.     
  1296.     def get_usage(self):
  1297.         if self.usage:
  1298.             return self.formatter.format_usage(self.expand_prog_name(self.usage))
  1299.         else:
  1300.             return ''
  1301.  
  1302.     
  1303.     def print_usage(self, file = None):
  1304.         '''print_usage(file : file = stdout)
  1305.  
  1306.         Print the usage message for the current program (self.usage) to
  1307.         \'file\' (default stdout).  Any occurence of the string "%prog" in
  1308.         self.usage is replaced with the name of the current program
  1309.         (basename of sys.argv[0]).  Does nothing if self.usage is empty
  1310.         or not defined.
  1311.         '''
  1312.         if self.usage:
  1313.             print >>file, self.get_usage()
  1314.         
  1315.  
  1316.     
  1317.     def get_version(self):
  1318.         if self.version:
  1319.             return self.expand_prog_name(self.version)
  1320.         else:
  1321.             return ''
  1322.  
  1323.     
  1324.     def print_version(self, file = None):
  1325.         '''print_version(file : file = stdout)
  1326.  
  1327.         Print the version message for this program (self.version) to
  1328.         \'file\' (default stdout).  As with print_usage(), any occurence
  1329.         of "%prog" in self.version is replaced by the current program\'s
  1330.         name.  Does nothing if self.version is empty or undefined.
  1331.         '''
  1332.         if self.version:
  1333.             print >>file, self.get_version()
  1334.         
  1335.  
  1336.     
  1337.     def format_option_help(self, formatter = None):
  1338.         if formatter is None:
  1339.             formatter = self.formatter
  1340.         
  1341.         formatter.store_option_strings(self)
  1342.         result = []
  1343.         result.append(formatter.format_heading(_('options')))
  1344.         formatter.indent()
  1345.         if self.option_list:
  1346.             result.append(OptionContainer.format_option_help(self, formatter))
  1347.             result.append('\n')
  1348.         
  1349.         for group in self.option_groups:
  1350.             result.append(group.format_help(formatter))
  1351.             result.append('\n')
  1352.         
  1353.         formatter.dedent()
  1354.         return ''.join(result[:-1])
  1355.  
  1356.     
  1357.     def format_help(self, formatter = None):
  1358.         if formatter is None:
  1359.             formatter = self.formatter
  1360.         
  1361.         result = []
  1362.         if self.usage:
  1363.             result.append(self.get_usage() + '\n')
  1364.         
  1365.         if self.description:
  1366.             result.append(self.format_description(formatter) + '\n')
  1367.         
  1368.         result.append(self.format_option_help(formatter))
  1369.         return ''.join(result)
  1370.  
  1371.     
  1372.     def print_help(self, file = None):
  1373.         """print_help(file : file = stdout)
  1374.  
  1375.         Print an extended help message, listing all options and any
  1376.         help text provided with them, to 'file' (default stdout).
  1377.         """
  1378.         if file is None:
  1379.             file = sys.stdout
  1380.         
  1381.         file.write(self.format_help())
  1382.  
  1383.  
  1384.  
  1385. def _match_abbrev(s, wordmap):
  1386.     """_match_abbrev(s : string, wordmap : {string : Option}) -> string
  1387.  
  1388.     Return the string key in 'wordmap' for which 's' is an unambiguous
  1389.     abbreviation.  If 's' is found to be ambiguous or doesn't match any of
  1390.     'words', raise BadOptionError.
  1391.     """
  1392.     if wordmap.has_key(s):
  1393.         return s
  1394.     else:
  1395.         possibilities = _[1]
  1396.         if len(possibilities) == 1:
  1397.             return possibilities[0]
  1398.         elif not possibilities:
  1399.             raise BadOptionError(_('no such option: %s') % s)
  1400.         else:
  1401.             possibilities.sort()
  1402.             raise BadOptionError(_('ambiguous option: %s (%s?)') % (s, ', '.join(possibilities)))
  1403.  
  1404. make_option = Option
  1405.