home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / python2.4 / optparse.py < prev    next >
Encoding:
Python Source  |  2007-04-12  |  55.5 KB  |  1,574 lines

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