PyXR

c:\python24\lib \ optparse.py



0001 """optparse - a powerful, extensible, and easy-to-use option parser.
0002 
0003 By Greg Ward <gward@python.net>
0004 
0005 Originally distributed as Optik; see http://optik.sourceforge.net/ .
0006 
0007 If you have problems with this module, please do not file bugs,
0008 patches, or feature requests with Python; instead, use Optik's
0009 SourceForge project page:
0010   http://sourceforge.net/projects/optik
0011 
0012 For support, use the optik-users@lists.sourceforge.net mailing list
0013 (http://lists.sourceforge.net/lists/listinfo/optik-users).
0014 """
0015 
0016 # Python developers: please do not make changes to this file, since
0017 # it is automatically generated from the Optik source code.
0018 
0019 __version__ = "1.5a2"
0020 
0021 __all__ = ['Option',
0022            'SUPPRESS_HELP',
0023            'SUPPRESS_USAGE',
0024            'Values',
0025            'OptionContainer',
0026            'OptionGroup',
0027            'OptionParser',
0028            'HelpFormatter',
0029            'IndentedHelpFormatter',
0030            'TitledHelpFormatter',
0031            'OptParseError',
0032            'OptionError',
0033            'OptionConflictError',
0034            'OptionValueError',
0035            'BadOptionError']
0036 
0037 __copyright__ = """
0038 Copyright (c) 2001-2004 Gregory P. Ward.  All rights reserved.
0039 Copyright (c) 2002-2004 Python Software Foundation.  All rights reserved.
0040 
0041 Redistribution and use in source and binary forms, with or without
0042 modification, are permitted provided that the following conditions are
0043 met:
0044 
0045   * Redistributions of source code must retain the above copyright
0046     notice, this list of conditions and the following disclaimer.
0047 
0048   * Redistributions in binary form must reproduce the above copyright
0049     notice, this list of conditions and the following disclaimer in the
0050     documentation and/or other materials provided with the distribution.
0051 
0052   * Neither the name of the author nor the names of its
0053     contributors may be used to endorse or promote products derived from
0054     this software without specific prior written permission.
0055 
0056 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
0057 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
0058 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
0059 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
0060 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
0061 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
0062 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
0063 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
0064 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
0065 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
0066 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0067 """
0068 
0069 import sys, os
0070 import types
0071 import textwrap
0072 from gettext import gettext as _
0073 
0074 def _repr(self):
0075     return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
0076 
0077 
0078 # This file was generated from:
0079 #   Id: option_parser.py 421 2004-10-26 00:45:16Z greg
0080 #   Id: option.py 422 2004-10-26 00:53:47Z greg
0081 #   Id: help.py 367 2004-07-24 23:21:21Z gward
0082 #   Id: errors.py 367 2004-07-24 23:21:21Z gward
0083 
0084 class OptParseError (Exception):
0085     def __init__(self, msg):
0086         self.msg = msg
0087 
0088     def __str__(self):
0089         return self.msg
0090 
0091 
0092 class OptionError (OptParseError):
0093     """
0094     Raised if an Option instance is created with invalid or
0095     inconsistent arguments.
0096     """
0097 
0098     def __init__(self, msg, option):
0099         self.msg = msg
0100         self.option_id = str(option)
0101 
0102     def __str__(self):
0103         if self.option_id:
0104             return "option %s: %s" % (self.option_id, self.msg)
0105         else:
0106             return self.msg
0107 
0108 class OptionConflictError (OptionError):
0109     """
0110     Raised if conflicting options are added to an OptionParser.
0111     """
0112 
0113 class OptionValueError (OptParseError):
0114     """
0115     Raised if an invalid option value is encountered on the command
0116     line.
0117     """
0118 
0119 class BadOptionError (OptParseError):
0120     """
0121     Raised if an invalid or ambiguous option is seen on the command-line.
0122     """
0123 
0124 
0125 class HelpFormatter:
0126 
0127     """
0128     Abstract base class for formatting option help.  OptionParser
0129     instances should use one of the HelpFormatter subclasses for
0130     formatting help; by default IndentedHelpFormatter is used.
0131 
0132     Instance attributes:
0133       parser : OptionParser
0134         the controlling OptionParser instance
0135       indent_increment : int
0136         the number of columns to indent per nesting level
0137       max_help_position : int
0138         the maximum starting column for option help text
0139       help_position : int
0140         the calculated starting column for option help text;
0141         initially the same as the maximum
0142       width : int
0143         total number of columns for output (pass None to constructor for
0144         this value to be taken from the $COLUMNS environment variable)
0145       level : int
0146         current indentation level
0147       current_indent : int
0148         current indentation level (in columns)
0149       help_width : int
0150         number of columns available for option help text (calculated)
0151       default_tag : str
0152         text to replace with each option's default value, "%default"
0153         by default.  Set to false value to disable default value expansion.
0154       option_strings : { Option : str }
0155         maps Option instances to the snippet of help text explaining
0156         the syntax of that option, e.g. "-h, --help" or
0157         "-fFILE, --file=FILE"
0158       _short_opt_fmt : str
0159         format string controlling how short options with values are
0160         printed in help text.  Must be either "%s%s" ("-fFILE") or
0161         "%s %s" ("-f FILE"), because those are the two syntaxes that
0162         Optik supports.
0163       _long_opt_fmt : str
0164         similar but for long options; must be either "%s %s" ("--file FILE")
0165         or "%s=%s" ("--file=FILE").
0166     """
0167 
0168     NO_DEFAULT_VALUE = "none"
0169 
0170     def __init__(self,
0171                  indent_increment,
0172                  max_help_position,
0173                  width,
0174                  short_first):
0175         self.parser = None
0176         self.indent_increment = indent_increment
0177         self.help_position = self.max_help_position = max_help_position
0178         if width is None:
0179             try:
0180                 width = int(os.environ['COLUMNS'])
0181             except (KeyError, ValueError):
0182                 width = 80
0183             width -= 2
0184         self.width = width
0185         self.current_indent = 0
0186         self.level = 0
0187         self.help_width = None          # computed later
0188         self.short_first = short_first
0189         self.default_tag = "%default"
0190         self.option_strings = {}
0191         self._short_opt_fmt = "%s %s"
0192         self._long_opt_fmt = "%s=%s"
0193 
0194     def set_parser(self, parser):
0195         self.parser = parser
0196 
0197     def set_short_opt_delimiter(self, delim):
0198         if delim not in ("", " "):
0199             raise ValueError(
0200                 "invalid metavar delimiter for short options: %r" % delim)
0201         self._short_opt_fmt = "%s" + delim + "%s"
0202 
0203     def set_long_opt_delimiter(self, delim):
0204         if delim not in ("=", " "):
0205             raise ValueError(
0206                 "invalid metavar delimiter for long options: %r" % delim)
0207         self._long_opt_fmt = "%s" + delim + "%s"
0208 
0209     def indent(self):
0210         self.current_indent += self.indent_increment
0211         self.level += 1
0212 
0213     def dedent(self):
0214         self.current_indent -= self.indent_increment
0215         assert self.current_indent >= 0, "Indent decreased below 0."
0216         self.level -= 1
0217 
0218     def format_usage(self, usage):
0219         raise NotImplementedError, "subclasses must implement"
0220 
0221     def format_heading(self, heading):
0222         raise NotImplementedError, "subclasses must implement"
0223 
0224     def format_description(self, description):
0225         if not description:
0226             return ""
0227         desc_width = self.width - self.current_indent
0228         indent = " "*self.current_indent
0229         return textwrap.fill(description,
0230                              desc_width,
0231                              initial_indent=indent,
0232                              subsequent_indent=indent) + "\n"
0233 
0234     def expand_default(self, option):
0235         if self.parser is None or not self.default_tag:
0236             return option.help
0237 
0238         default_value = self.parser.defaults.get(option.dest)
0239         if default_value is NO_DEFAULT or default_value is None:
0240             default_value = self.NO_DEFAULT_VALUE
0241 
0242         return option.help.replace(self.default_tag, str(default_value))
0243 
0244     def format_option(self, option):
0245         # The help for each option consists of two parts:
0246         #   * the opt strings and metavars
0247         #     eg. ("-x", or "-fFILENAME, --file=FILENAME")
0248         #   * the user-supplied help string
0249         #     eg. ("turn on expert mode", "read data from FILENAME")
0250         #
0251         # If possible, we write both of these on the same line:
0252         #   -x      turn on expert mode
0253         #
0254         # But if the opt string list is too long, we put the help
0255         # string on a second line, indented to the same column it would
0256         # start in if it fit on the first line.
0257         #   -fFILENAME, --file=FILENAME
0258         #           read data from FILENAME
0259         result = []
0260         opts = self.option_strings[option]
0261         opt_width = self.help_position - self.current_indent - 2
0262         if len(opts) > opt_width:
0263             opts = "%*s%s\n" % (self.current_indent, "", opts)
0264             indent_first = self.help_position
0265         else:                       # start help on same line as opts
0266             opts = "%*s%-*s  " % (self.current_indent, "", opt_width, opts)
0267             indent_first = 0
0268         result.append(opts)
0269         if option.help:
0270             help_text = self.expand_default(option)
0271             help_lines = textwrap.wrap(help_text, self.help_width)
0272             result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
0273             result.extend(["%*s%s\n" % (self.help_position, "", line)
0274                            for line in help_lines[1:]])
0275         elif opts[-1] != "\n":
0276             result.append("\n")
0277         return "".join(result)
0278 
0279     def store_option_strings(self, parser):
0280         self.indent()
0281         max_len = 0
0282         for opt in parser.option_list:
0283             strings = self.format_option_strings(opt)
0284             self.option_strings[opt] = strings
0285             max_len = max(max_len, len(strings) + self.current_indent)
0286         self.indent()
0287         for group in parser.option_groups:
0288             for opt in group.option_list:
0289                 strings = self.format_option_strings(opt)
0290                 self.option_strings[opt] = strings
0291                 max_len = max(max_len, len(strings) + self.current_indent)
0292         self.dedent()
0293         self.dedent()
0294         self.help_position = min(max_len + 2, self.max_help_position)
0295         self.help_width = self.width - self.help_position
0296 
0297     def format_option_strings(self, option):
0298         """Return a comma-separated list of option strings & metavariables."""
0299         if option.takes_value():
0300             metavar = option.metavar or option.dest.upper()
0301             short_opts = [self._short_opt_fmt % (sopt, metavar)
0302                           for sopt in option._short_opts]
0303             long_opts = [self._long_opt_fmt % (lopt, metavar)
0304                          for lopt in option._long_opts]
0305         else:
0306             short_opts = option._short_opts
0307             long_opts = option._long_opts
0308 
0309         if self.short_first:
0310             opts = short_opts + long_opts
0311         else:
0312             opts = long_opts + short_opts
0313 
0314         return ", ".join(opts)
0315 
0316 class IndentedHelpFormatter (HelpFormatter):
0317     """Format help with indented section bodies.
0318     """
0319 
0320     def __init__(self,
0321                  indent_increment=2,
0322                  max_help_position=24,
0323                  width=None,
0324                  short_first=1):
0325         HelpFormatter.__init__(
0326             self, indent_increment, max_help_position, width, short_first)
0327 
0328     def format_usage(self, usage):
0329         return _("usage: %s\n") % usage
0330 
0331     def format_heading(self, heading):
0332         return "%*s%s:\n" % (self.current_indent, "", heading)
0333 
0334 
0335 class TitledHelpFormatter (HelpFormatter):
0336     """Format help with underlined section headers.
0337     """
0338 
0339     def __init__(self,
0340                  indent_increment=0,
0341                  max_help_position=24,
0342                  width=None,
0343                  short_first=0):
0344         HelpFormatter.__init__ (
0345             self, indent_increment, max_help_position, width, short_first)
0346 
0347     def format_usage(self, usage):
0348         return "%s  %s\n" % (self.format_heading(_("Usage")), usage)
0349 
0350     def format_heading(self, heading):
0351         return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
0352 
0353 
0354 _builtin_cvt = { "int" : (int, _("integer")),
0355                  "long" : (long, _("long integer")),
0356                  "float" : (float, _("floating-point")),
0357                  "complex" : (complex, _("complex")) }
0358 
0359 def check_builtin(option, opt, value):
0360     (cvt, what) = _builtin_cvt[option.type]
0361     try:
0362         return cvt(value)
0363     except ValueError:
0364         raise OptionValueError(
0365             _("option %s: invalid %s value: %r") % (opt, what, value))
0366 
0367 def check_choice(option, opt, value):
0368     if value in option.choices:
0369         return value
0370     else:
0371         choices = ", ".join(map(repr, option.choices))
0372         raise OptionValueError(
0373             _("option %s: invalid choice: %r (choose from %s)")
0374             % (opt, value, choices))
0375 
0376 # Not supplying a default is different from a default of None,
0377 # so we need an explicit "not supplied" value.
0378 NO_DEFAULT = ("NO", "DEFAULT")
0379 
0380 
0381 class Option:
0382     """
0383     Instance attributes:
0384       _short_opts : [string]
0385       _long_opts : [string]
0386 
0387       action : string
0388       type : string
0389       dest : string
0390       default : any
0391       nargs : int
0392       const : any
0393       choices : [string]
0394       callback : function
0395       callback_args : (any*)
0396       callback_kwargs : { string : any }
0397       help : string
0398       metavar : string
0399     """
0400 
0401     # The list of instance attributes that may be set through
0402     # keyword args to the constructor.
0403     ATTRS = ['action',
0404              'type',
0405              'dest',
0406              'default',
0407              'nargs',
0408              'const',
0409              'choices',
0410              'callback',
0411              'callback_args',
0412              'callback_kwargs',
0413              'help',
0414              'metavar']
0415 
0416     # The set of actions allowed by option parsers.  Explicitly listed
0417     # here so the constructor can validate its arguments.
0418     ACTIONS = ("store",
0419                "store_const",
0420                "store_true",
0421                "store_false",
0422                "append",
0423                "count",
0424                "callback",
0425                "help",
0426                "version")
0427 
0428     # The set of actions that involve storing a value somewhere;
0429     # also listed just for constructor argument validation.  (If
0430     # the action is one of these, there must be a destination.)
0431     STORE_ACTIONS = ("store",
0432                      "store_const",
0433                      "store_true",
0434                      "store_false",
0435                      "append",
0436                      "count")
0437 
0438     # The set of actions for which it makes sense to supply a value
0439     # type, ie. which may consume an argument from the command line.
0440     TYPED_ACTIONS = ("store",
0441                      "append",
0442                      "callback")
0443 
0444     # The set of actions which *require* a value type, ie. that
0445     # always consume an argument from the command line.
0446     ALWAYS_TYPED_ACTIONS = ("store",
0447                             "append")
0448 
0449     # The set of known types for option parsers.  Again, listed here for
0450     # constructor argument validation.
0451     TYPES = ("string", "int", "long", "float", "complex", "choice")
0452 
0453     # Dictionary of argument checking functions, which convert and
0454     # validate option arguments according to the option type.
0455     #
0456     # Signature of checking functions is:
0457     #   check(option : Option, opt : string, value : string) -> any
0458     # where
0459     #   option is the Option instance calling the checker
0460     #   opt is the actual option seen on the command-line
0461     #     (eg. "-a", "--file")
0462     #   value is the option argument seen on the command-line
0463     #
0464     # The return value should be in the appropriate Python type
0465     # for option.type -- eg. an integer if option.type == "int".
0466     #
0467     # If no checker is defined for a type, arguments will be
0468     # unchecked and remain strings.
0469     TYPE_CHECKER = { "int"    : check_builtin,
0470                      "long"   : check_builtin,
0471                      "float"  : check_builtin,
0472                      "complex": check_builtin,
0473                      "choice" : check_choice,
0474                    }
0475 
0476 
0477     # CHECK_METHODS is a list of unbound method objects; they are called
0478     # by the constructor, in order, after all attributes are
0479     # initialized.  The list is created and filled in later, after all
0480     # the methods are actually defined.  (I just put it here because I
0481     # like to define and document all class attributes in the same
0482     # place.)  Subclasses that add another _check_*() method should
0483     # define their own CHECK_METHODS list that adds their check method
0484     # to those from this class.
0485     CHECK_METHODS = None
0486 
0487 
0488     # -- Constructor/initialization methods ----------------------------
0489 
0490     def __init__(self, *opts, **attrs):
0491         # Set _short_opts, _long_opts attrs from 'opts' tuple.
0492         # Have to be set now, in case no option strings are supplied.
0493         self._short_opts = []
0494         self._long_opts = []
0495         opts = self._check_opt_strings(opts)
0496         self._set_opt_strings(opts)
0497 
0498         # Set all other attrs (action, type, etc.) from 'attrs' dict
0499         self._set_attrs(attrs)
0500 
0501         # Check all the attributes we just set.  There are lots of
0502         # complicated interdependencies, but luckily they can be farmed
0503         # out to the _check_*() methods listed in CHECK_METHODS -- which
0504         # could be handy for subclasses!  The one thing these all share
0505         # is that they raise OptionError if they discover a problem.
0506         for checker in self.CHECK_METHODS:
0507             checker(self)
0508 
0509     def _check_opt_strings(self, opts):
0510         # Filter out None because early versions of Optik had exactly
0511         # one short option and one long option, either of which
0512         # could be None.
0513         opts = filter(None, opts)
0514         if not opts:
0515             raise TypeError("at least one option string must be supplied")
0516         return opts
0517 
0518     def _set_opt_strings(self, opts):
0519         for opt in opts:
0520             if len(opt) < 2:
0521                 raise OptionError(
0522                     "invalid option string %r: "
0523                     "must be at least two characters long" % opt, self)
0524             elif len(opt) == 2:
0525                 if not (opt[0] == "-" and opt[1] != "-"):
0526                     raise OptionError(
0527                         "invalid short option string %r: "
0528                         "must be of the form -x, (x any non-dash char)" % opt,
0529                         self)
0530                 self._short_opts.append(opt)
0531             else:
0532                 if not (opt[0:2] == "--" and opt[2] != "-"):
0533                     raise OptionError(
0534                         "invalid long option string %r: "
0535                         "must start with --, followed by non-dash" % opt,
0536                         self)
0537                 self._long_opts.append(opt)
0538 
0539     def _set_attrs(self, attrs):
0540         for attr in self.ATTRS:
0541             if attrs.has_key(attr):
0542                 setattr(self, attr, attrs[attr])
0543                 del attrs[attr]
0544             else:
0545                 if attr == 'default':
0546                     setattr(self, attr, NO_DEFAULT)
0547                 else:
0548                     setattr(self, attr, None)
0549         if attrs:
0550             raise OptionError(
0551                 "invalid keyword arguments: %s" % ", ".join(attrs.keys()),
0552                 self)
0553 
0554 
0555     # -- Constructor validation methods --------------------------------
0556 
0557     def _check_action(self):
0558         if self.action is None:
0559             self.action = "store"
0560         elif self.action not in self.ACTIONS:
0561             raise OptionError("invalid action: %r" % self.action, self)
0562 
0563     def _check_type(self):
0564         if self.type is None:
0565             if self.action in self.ALWAYS_TYPED_ACTIONS:
0566                 if self.choices is not None:
0567                     # The "choices" attribute implies "choice" type.
0568                     self.type = "choice"
0569                 else:
0570                     # No type given?  "string" is the most sensible default.
0571                     self.type = "string"
0572         else:
0573             # Allow type objects as an alternative to their names.
0574             if type(self.type) is type:
0575                 self.type = self.type.__name__
0576             if self.type == "str":
0577                 self.type = "string"
0578 
0579             if self.type not in self.TYPES:
0580                 raise OptionError("invalid option type: %r" % self.type, self)
0581             if self.action not in self.TYPED_ACTIONS:
0582                 raise OptionError(
0583                     "must not supply a type for action %r" % self.action, self)
0584 
0585     def _check_choice(self):
0586         if self.type == "choice":
0587             if self.choices is None:
0588                 raise OptionError(
0589                     "must supply a list of choices for type 'choice'", self)
0590             elif type(self.choices) not in (types.TupleType, types.ListType):
0591                 raise OptionError(
0592                     "choices must be a list of strings ('%s' supplied)"
0593                     % str(type(self.choices)).split("'")[1], self)
0594         elif self.choices is not None:
0595             raise OptionError(
0596                 "must not supply choices for type %r" % self.type, self)
0597 
0598     def _check_dest(self):
0599         # No destination given, and we need one for this action.  The
0600         # self.type check is for callbacks that take a value.
0601         takes_value = (self.action in self.STORE_ACTIONS or
0602                        self.type is not None)
0603         if self.dest is None and takes_value:
0604 
0605             # Glean a destination from the first long option string,
0606             # or from the first short option string if no long options.
0607             if self._long_opts:
0608                 # eg. "--foo-bar" -> "foo_bar"
0609                 self.dest = self._long_opts[0][2:].replace('-', '_')
0610             else:
0611                 self.dest = self._short_opts[0][1]
0612 
0613     def _check_const(self):
0614         if self.action != "store_const" and self.const is not None:
0615             raise OptionError(
0616                 "'const' must not be supplied for action %r" % self.action,
0617                 self)
0618 
0619     def _check_nargs(self):
0620         if self.action in self.TYPED_ACTIONS:
0621             if self.nargs is None:
0622                 self.nargs = 1
0623         elif self.nargs is not None:
0624             raise OptionError(
0625                 "'nargs' must not be supplied for action %r" % self.action,
0626                 self)
0627 
0628     def _check_callback(self):
0629         if self.action == "callback":
0630             if not callable(self.callback):
0631                 raise OptionError(
0632                     "callback not callable: %r" % self.callback, self)
0633             if (self.callback_args is not None and
0634                 type(self.callback_args) is not types.TupleType):
0635                 raise OptionError(
0636                     "callback_args, if supplied, must be a tuple: not %r"
0637                     % self.callback_args, self)
0638             if (self.callback_kwargs is not None and
0639                 type(self.callback_kwargs) is not types.DictType):
0640                 raise OptionError(
0641                     "callback_kwargs, if supplied, must be a dict: not %r"
0642                     % self.callback_kwargs, self)
0643         else:
0644             if self.callback is not None:
0645                 raise OptionError(
0646                     "callback supplied (%r) for non-callback option"
0647                     % self.callback, self)
0648             if self.callback_args is not None:
0649                 raise OptionError(
0650                     "callback_args supplied for non-callback option", self)
0651             if self.callback_kwargs is not None:
0652                 raise OptionError(
0653                     "callback_kwargs supplied for non-callback option", self)
0654 
0655 
0656     CHECK_METHODS = [_check_action,
0657                      _check_type,
0658                      _check_choice,
0659                      _check_dest,
0660                      _check_const,
0661                      _check_nargs,
0662                      _check_callback]
0663 
0664 
0665     # -- Miscellaneous methods -----------------------------------------
0666 
0667     def __str__(self):
0668         return "/".join(self._short_opts + self._long_opts)
0669 
0670     __repr__ = _repr
0671 
0672     def takes_value(self):
0673         return self.type is not None
0674 
0675     def get_opt_string(self):
0676         if self._long_opts:
0677             return self._long_opts[0]
0678         else:
0679             return self._short_opts[0]
0680 
0681 
0682     # -- Processing methods --------------------------------------------
0683 
0684     def check_value(self, opt, value):
0685         checker = self.TYPE_CHECKER.get(self.type)
0686         if checker is None:
0687             return value
0688         else:
0689             return checker(self, opt, value)
0690 
0691     def convert_value(self, opt, value):
0692         if value is not None:
0693             if self.nargs == 1:
0694                 return self.check_value(opt, value)
0695             else:
0696                 return tuple([self.check_value(opt, v) for v in value])
0697 
0698     def process(self, opt, value, values, parser):
0699 
0700         # First, convert the value(s) to the right type.  Howl if any
0701         # value(s) are bogus.
0702         value = self.convert_value(opt, value)
0703 
0704         # And then take whatever action is expected of us.
0705         # This is a separate method to make life easier for
0706         # subclasses to add new actions.
0707         return self.take_action(
0708             self.action, self.dest, opt, value, values, parser)
0709 
0710     def take_action(self, action, dest, opt, value, values, parser):
0711         if action == "store":
0712             setattr(values, dest, value)
0713         elif action == "store_const":
0714             setattr(values, dest, self.const)
0715         elif action == "store_true":
0716             setattr(values, dest, True)
0717         elif action == "store_false":
0718             setattr(values, dest, False)
0719         elif action == "append":
0720             values.ensure_value(dest, []).append(value)
0721         elif action == "count":
0722             setattr(values, dest, values.ensure_value(dest, 0) + 1)
0723         elif action == "callback":
0724             args = self.callback_args or ()
0725             kwargs = self.callback_kwargs or {}
0726             self.callback(self, opt, value, parser, *args, **kwargs)
0727         elif action == "help":
0728             parser.print_help()
0729             parser.exit()
0730         elif action == "version":
0731             parser.print_version()
0732             parser.exit()
0733         else:
0734             raise RuntimeError, "unknown action %r" % self.action
0735 
0736         return 1
0737 
0738 # class Option
0739 
0740 
0741 SUPPRESS_HELP = "SUPPRESS"+"HELP"
0742 SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
0743 
0744 # For compatibility with Python 2.2
0745 try:
0746     True, False
0747 except NameError:
0748     (True, False) = (1, 0)
0749 try:
0750     basestring
0751 except NameError:
0752     basestring = (str, unicode)
0753 
0754 
0755 class Values:
0756 
0757     def __init__(self, defaults=None):
0758         if defaults:
0759             for (attr, val) in defaults.items():
0760                 setattr(self, attr, val)
0761 
0762     def __str__(self):
0763         return str(self.__dict__)
0764 
0765     __repr__ = _repr
0766 
0767     def __eq__(self, other):
0768         if isinstance(other, Values):
0769             return self.__dict__ == other.__dict__
0770         elif isinstance(other, dict):
0771             return self.__dict__ == other
0772         else:
0773             return False
0774 
0775     def __ne__(self, other):
0776         return not (self == other)
0777 
0778     def _update_careful(self, dict):
0779         """
0780         Update the option values from an arbitrary dictionary, but only
0781         use keys from dict that already have a corresponding attribute
0782         in self.  Any keys in dict without a corresponding attribute
0783         are silently ignored.
0784         """
0785         for attr in dir(self):
0786             if dict.has_key(attr):
0787                 dval = dict[attr]
0788                 if dval is not None:
0789                     setattr(self, attr, dval)
0790 
0791     def _update_loose(self, dict):
0792         """
0793         Update the option values from an arbitrary dictionary,
0794         using all keys from the dictionary regardless of whether
0795         they have a corresponding attribute in self or not.
0796         """
0797         self.__dict__.update(dict)
0798 
0799     def _update(self, dict, mode):
0800         if mode == "careful":
0801             self._update_careful(dict)
0802         elif mode == "loose":
0803             self._update_loose(dict)
0804         else:
0805             raise ValueError, "invalid update mode: %r" % mode
0806 
0807     def read_module(self, modname, mode="careful"):
0808         __import__(modname)
0809         mod = sys.modules[modname]
0810         self._update(vars(mod), mode)
0811 
0812     def read_file(self, filename, mode="careful"):
0813         vars = {}
0814         execfile(filename, vars)
0815         self._update(vars, mode)
0816 
0817     def ensure_value(self, attr, value):
0818         if not hasattr(self, attr) or getattr(self, attr) is None:
0819             setattr(self, attr, value)
0820         return getattr(self, attr)
0821 
0822 
0823 class OptionContainer:
0824 
0825     """
0826     Abstract base class.
0827 
0828     Class attributes:
0829       standard_option_list : [Option]
0830         list of standard options that will be accepted by all instances
0831         of this parser class (intended to be overridden by subclasses).
0832 
0833     Instance attributes:
0834       option_list : [Option]
0835         the list of Option objects contained by this OptionContainer
0836       _short_opt : { string : Option }
0837         dictionary mapping short option strings, eg. "-f" or "-X",
0838         to the Option instances that implement them.  If an Option
0839         has multiple short option strings, it will appears in this
0840         dictionary multiple times. [1]
0841       _long_opt : { string : Option }
0842         dictionary mapping long option strings, eg. "--file" or
0843         "--exclude", to the Option instances that implement them.
0844         Again, a given Option can occur multiple times in this
0845         dictionary. [1]
0846       defaults : { string : any }
0847         dictionary mapping option destination names to default
0848         values for each destination [1]
0849 
0850     [1] These mappings are common to (shared by) all components of the
0851         controlling OptionParser, where they are initially created.
0852 
0853     """
0854 
0855     def __init__(self, option_class, conflict_handler, description):
0856         # Initialize the option list and related data structures.
0857         # This method must be provided by subclasses, and it must
0858         # initialize at least the following instance attributes:
0859         # option_list, _short_opt, _long_opt, defaults.
0860         self._create_option_list()
0861 
0862         self.option_class = option_class
0863         self.set_conflict_handler(conflict_handler)
0864         self.set_description(description)
0865 
0866     def _create_option_mappings(self):
0867         # For use by OptionParser constructor -- create the master
0868         # option mappings used by this OptionParser and all
0869         # OptionGroups that it owns.
0870         self._short_opt = {}            # single letter -> Option instance
0871         self._long_opt = {}             # long option -> Option instance
0872         self.defaults = {}              # maps option dest -> default value
0873 
0874 
0875     def _share_option_mappings(self, parser):
0876         # For use by OptionGroup constructor -- use shared option
0877         # mappings from the OptionParser that owns this OptionGroup.
0878         self._short_opt = parser._short_opt
0879         self._long_opt = parser._long_opt
0880         self.defaults = parser.defaults
0881 
0882     def set_conflict_handler(self, handler):
0883         if handler not in ("error", "resolve"):
0884             raise ValueError, "invalid conflict_resolution value %r" % handler
0885         self.conflict_handler = handler
0886 
0887     def set_description(self, description):
0888         self.description = description
0889 
0890     def get_description(self):
0891         return self.description
0892 
0893 
0894     # -- Option-adding methods -----------------------------------------
0895 
0896     def _check_conflict(self, option):
0897         conflict_opts = []
0898         for opt in option._short_opts:
0899             if self._short_opt.has_key(opt):
0900                 conflict_opts.append((opt, self._short_opt[opt]))
0901         for opt in option._long_opts:
0902             if self._long_opt.has_key(opt):
0903                 conflict_opts.append((opt, self._long_opt[opt]))
0904 
0905         if conflict_opts:
0906             handler = self.conflict_handler
0907             if handler == "error":
0908                 raise OptionConflictError(
0909                     "conflicting option string(s): %s"
0910                     % ", ".join([co[0] for co in conflict_opts]),
0911                     option)
0912             elif handler == "resolve":
0913                 for (opt, c_option) in conflict_opts:
0914                     if opt.startswith("--"):
0915                         c_option._long_opts.remove(opt)
0916                         del self._long_opt[opt]
0917                     else:
0918                         c_option._short_opts.remove(opt)
0919                         del self._short_opt[opt]
0920                     if not (c_option._short_opts or c_option._long_opts):
0921                         c_option.container.option_list.remove(c_option)
0922 
0923     def add_option(self, *args, **kwargs):
0924         """add_option(Option)
0925            add_option(opt_str, ..., kwarg=val, ...)
0926         """
0927         if type(args[0]) is types.StringType:
0928             option = self.option_class(*args, **kwargs)
0929         elif len(args) == 1 and not kwargs:
0930             option = args[0]
0931             if not isinstance(option, Option):
0932                 raise TypeError, "not an Option instance: %r" % option
0933         else:
0934             raise TypeError, "invalid arguments"
0935 
0936         self._check_conflict(option)
0937 
0938         self.option_list.append(option)
0939         option.container = self
0940         for opt in option._short_opts:
0941             self._short_opt[opt] = option
0942         for opt in option._long_opts:
0943             self._long_opt[opt] = option
0944 
0945         if option.dest is not None:     # option has a dest, we need a default
0946             if option.default is not NO_DEFAULT:
0947                 self.defaults[option.dest] = option.default
0948             elif not self.defaults.has_key(option.dest):
0949                 self.defaults[option.dest] = None
0950 
0951         return option
0952 
0953     def add_options(self, option_list):
0954         for option in option_list:
0955             self.add_option(option)
0956 
0957     # -- Option query/removal methods ----------------------------------
0958 
0959     def get_option(self, opt_str):
0960         return (self._short_opt.get(opt_str) or
0961                 self._long_opt.get(opt_str))
0962 
0963     def has_option(self, opt_str):
0964         return (self._short_opt.has_key(opt_str) or
0965                 self._long_opt.has_key(opt_str))
0966 
0967     def remove_option(self, opt_str):
0968         option = self._short_opt.get(opt_str)
0969         if option is None:
0970             option = self._long_opt.get(opt_str)
0971         if option is None:
0972             raise ValueError("no such option %r" % opt_str)
0973 
0974         for opt in option._short_opts:
0975             del self._short_opt[opt]
0976         for opt in option._long_opts:
0977             del self._long_opt[opt]
0978         option.container.option_list.remove(option)
0979 
0980 
0981     # -- Help-formatting methods ---------------------------------------
0982 
0983     def format_option_help(self, formatter):
0984         if not self.option_list:
0985             return ""
0986         result = []
0987         for option in self.option_list:
0988             if not option.help is SUPPRESS_HELP:
0989                 result.append(formatter.format_option(option))
0990         return "".join(result)
0991 
0992     def format_description(self, formatter):
0993         return formatter.format_description(self.get_description())
0994 
0995     def format_help(self, formatter):
0996         result = []
0997         if self.description:
0998             result.append(self.format_description(formatter))
0999         if self.option_list:
1000             result.append(self.format_option_help(formatter))
1001         return "\n".join(result)
1002 
1003 
1004 class OptionGroup (OptionContainer):
1005 
1006     def __init__(self, parser, title, description=None):
1007         self.parser = parser
1008         OptionContainer.__init__(
1009             self, parser.option_class, parser.conflict_handler, description)
1010         self.title = title
1011 
1012     def _create_option_list(self):
1013         self.option_list = []
1014         self._share_option_mappings(self.parser)
1015 
1016     def set_title(self, title):
1017         self.title = title
1018 
1019     # -- Help-formatting methods ---------------------------------------
1020 
1021     def format_help(self, formatter):
1022         result = formatter.format_heading(self.title)
1023         formatter.indent()
1024         result += OptionContainer.format_help(self, formatter)
1025         formatter.dedent()
1026         return result
1027 
1028 
1029 class OptionParser (OptionContainer):
1030 
1031     """
1032     Class attributes:
1033       standard_option_list : [Option]
1034         list of standard options that will be accepted by all instances
1035         of this parser class (intended to be overridden by subclasses).
1036 
1037     Instance attributes:
1038       usage : string
1039         a usage string for your program.  Before it is displayed
1040         to the user, "%prog" will be expanded to the name of
1041         your program (self.prog or os.path.basename(sys.argv[0])).
1042       prog : string
1043         the name of the current program (to override
1044         os.path.basename(sys.argv[0])).
1045 
1046       option_groups : [OptionGroup]
1047         list of option groups in this parser (option groups are
1048         irrelevant for parsing the command-line, but very useful
1049         for generating help)
1050 
1051       allow_interspersed_args : bool = true
1052         if true, positional arguments may be interspersed with options.
1053         Assuming -a and -b each take a single argument, the command-line
1054           -ablah foo bar -bboo baz
1055         will be interpreted the same as
1056           -ablah -bboo -- foo bar baz
1057         If this flag were false, that command line would be interpreted as
1058           -ablah -- foo bar -bboo baz
1059         -- ie. we stop processing options as soon as we see the first
1060         non-option argument.  (This is the tradition followed by
1061         Python's getopt module, Perl's Getopt::Std, and other argument-
1062         parsing libraries, but it is generally annoying to users.)
1063 
1064       process_default_values : bool = true
1065         if true, option default values are processed similarly to option
1066         values from the command line: that is, they are passed to the
1067         type-checking function for the option's type (as long as the
1068         default value is a string).  (This really only matters if you
1069         have defined custom types; see SF bug #955889.)  Set it to false
1070         to restore the behaviour of Optik 1.4.1 and earlier.
1071 
1072       rargs : [string]
1073         the argument list currently being parsed.  Only set when
1074         parse_args() is active, and continually trimmed down as
1075         we consume arguments.  Mainly there for the benefit of
1076         callback options.
1077       largs : [string]
1078         the list of leftover arguments that we have skipped while
1079         parsing options.  If allow_interspersed_args is false, this
1080         list is always empty.
1081       values : Values
1082         the set of option values currently being accumulated.  Only
1083         set when parse_args() is active.  Also mainly for callbacks.
1084 
1085     Because of the 'rargs', 'largs', and 'values' attributes,
1086     OptionParser is not thread-safe.  If, for some perverse reason, you
1087     need to parse command-line arguments simultaneously in different
1088     threads, use different OptionParser instances.
1089 
1090     """
1091 
1092     standard_option_list = []
1093 
1094     def __init__(self,
1095                  usage=None,
1096                  option_list=None,
1097                  option_class=Option,
1098                  version=None,
1099                  conflict_handler="error",
1100                  description=None,
1101                  formatter=None,
1102                  add_help_option=True,
1103                  prog=None):
1104         OptionContainer.__init__(
1105             self, option_class, conflict_handler, description)
1106         self.set_usage(usage)
1107         self.prog = prog
1108         self.version = version
1109         self.allow_interspersed_args = True
1110         self.process_default_values = True
1111         if formatter is None:
1112             formatter = IndentedHelpFormatter()
1113         self.formatter = formatter
1114         self.formatter.set_parser(self)
1115 
1116         # Populate the option list; initial sources are the
1117         # standard_option_list class attribute, the 'option_list'
1118         # argument, and (if applicable) the _add_version_option() and
1119         # _add_help_option() methods.
1120         self._populate_option_list(option_list,
1121                                    add_help=add_help_option)
1122 
1123         self._init_parsing_state()
1124 
1125     # -- Private methods -----------------------------------------------
1126     # (used by our or OptionContainer's constructor)
1127 
1128     def _create_option_list(self):
1129         self.option_list = []
1130         self.option_groups = []
1131         self._create_option_mappings()
1132 
1133     def _add_help_option(self):
1134         self.add_option("-h", "--help",
1135                         action="help",
1136                         help=_("show this help message and exit"))
1137 
1138     def _add_version_option(self):
1139         self.add_option("--version",
1140                         action="version",
1141                         help=_("show program's version number and exit"))
1142 
1143     def _populate_option_list(self, option_list, add_help=True):
1144         if self.standard_option_list:
1145             self.add_options(self.standard_option_list)
1146         if option_list:
1147             self.add_options(option_list)
1148         if self.version:
1149             self._add_version_option()
1150         if add_help:
1151             self._add_help_option()
1152 
1153     def _init_parsing_state(self):
1154         # These are set in parse_args() for the convenience of callbacks.
1155         self.rargs = None
1156         self.largs = None
1157         self.values = None
1158 
1159 
1160     # -- Simple modifier methods ---------------------------------------
1161 
1162     def set_usage(self, usage):
1163         if usage is None:
1164             self.usage = _("%prog [options]")
1165         elif usage is SUPPRESS_USAGE:
1166             self.usage = None
1167         # For backwards compatibility with Optik 1.3 and earlier.
1168         elif usage.startswith("usage:" + " "):
1169             self.usage = usage[7:]
1170         else:
1171             self.usage = usage
1172 
1173     def enable_interspersed_args(self):
1174         self.allow_interspersed_args = True
1175 
1176     def disable_interspersed_args(self):
1177         self.allow_interspersed_args = False
1178 
1179     def set_process_default_values(self, process):
1180         self.process_default_values = process
1181 
1182     def set_default(self, dest, value):
1183         self.defaults[dest] = value
1184 
1185     def set_defaults(self, **kwargs):
1186         self.defaults.update(kwargs)
1187 
1188     def _get_all_options(self):
1189         options = self.option_list[:]
1190         for group in self.option_groups:
1191             options.extend(group.option_list)
1192         return options
1193 
1194     def get_default_values(self):
1195         if not self.process_default_values:
1196             # Old, pre-Optik 1.5 behaviour.
1197             return Values(self.defaults)
1198 
1199         defaults = self.defaults.copy()
1200         for option in self._get_all_options():
1201             default = defaults.get(option.dest)
1202             if isinstance(default, basestring):
1203                 opt_str = option.get_opt_string()
1204                 defaults[option.dest] = option.check_value(opt_str, default)
1205 
1206         return Values(defaults)
1207 
1208 
1209     # -- OptionGroup methods -------------------------------------------
1210 
1211     def add_option_group(self, *args, **kwargs):
1212         # XXX lots of overlap with OptionContainer.add_option()
1213         if type(args[0]) is types.StringType:
1214             group = OptionGroup(self, *args, **kwargs)
1215         elif len(args) == 1 and not kwargs:
1216             group = args[0]
1217             if not isinstance(group, OptionGroup):
1218                 raise TypeError, "not an OptionGroup instance: %r" % group
1219             if group.parser is not self:
1220                 raise ValueError, "invalid OptionGroup (wrong parser)"
1221         else:
1222             raise TypeError, "invalid arguments"
1223 
1224         self.option_groups.append(group)
1225         return group
1226 
1227     def get_option_group(self, opt_str):
1228         option = (self._short_opt.get(opt_str) or
1229                   self._long_opt.get(opt_str))
1230         if option and option.container is not self:
1231             return option.container
1232         return None
1233 
1234 
1235     # -- Option-parsing methods ----------------------------------------
1236 
1237     def _get_args(self, args):
1238         if args is None:
1239             return sys.argv[1:]
1240         else:
1241             return args[:]              # don't modify caller's list
1242 
1243     def parse_args(self, args=None, values=None):
1244         """
1245         parse_args(args : [string] = sys.argv[1:],
1246                    values : Values = None)
1247         -> (values : Values, args : [string])
1248 
1249         Parse the command-line options found in 'args' (default:
1250         sys.argv[1:]).  Any errors result in a call to 'error()', which
1251         by default prints the usage message to stderr and calls
1252         sys.exit() with an error message.  On success returns a pair
1253         (values, args) where 'values' is an Values instance (with all
1254         your option values) and 'args' is the list of arguments left
1255         over after parsing options.
1256         """
1257         rargs = self._get_args(args)
1258         if values is None:
1259             values = self.get_default_values()
1260 
1261         # Store the halves of the argument list as attributes for the
1262         # convenience of callbacks:
1263         #   rargs
1264         #     the rest of the command-line (the "r" stands for
1265         #     "remaining" or "right-hand")
1266         #   largs
1267         #     the leftover arguments -- ie. what's left after removing
1268         #     options and their arguments (the "l" stands for "leftover"
1269         #     or "left-hand")
1270         self.rargs = rargs
1271         self.largs = largs = []
1272         self.values = values
1273 
1274         try:
1275             stop = self._process_args(largs, rargs, values)
1276         except (BadOptionError, OptionValueError), err:
1277             self.error(err.msg)
1278 
1279         args = largs + rargs
1280         return self.check_values(values, args)
1281 
1282     def check_values(self, values, args):
1283         """
1284         check_values(values : Values, args : [string])
1285         -> (values : Values, args : [string])
1286 
1287         Check that the supplied option values and leftover arguments are
1288         valid.  Returns the option values and leftover arguments
1289         (possibly adjusted, possibly completely new -- whatever you
1290         like).  Default implementation just returns the passed-in
1291         values; subclasses may override as desired.
1292         """
1293         return (values, args)
1294 
1295     def _process_args(self, largs, rargs, values):
1296         """_process_args(largs : [string],
1297                          rargs : [string],
1298                          values : Values)
1299 
1300         Process command-line arguments and populate 'values', consuming
1301         options and arguments from 'rargs'.  If 'allow_interspersed_args' is
1302         false, stop at the first non-option argument.  If true, accumulate any
1303         interspersed non-option arguments in 'largs'.
1304         """
1305         while rargs:
1306             arg = rargs[0]
1307             # We handle bare "--" explicitly, and bare "-" is handled by the
1308             # standard arg handler since the short arg case ensures that the
1309             # len of the opt string is greater than 1.
1310             if arg == "--":
1311                 del rargs[0]
1312                 return
1313             elif arg[0:2] == "--":
1314                 # process a single long option (possibly with value(s))
1315                 self._process_long_opt(rargs, values)
1316             elif arg[:1] == "-" and len(arg) > 1:
1317                 # process a cluster of short options (possibly with
1318                 # value(s) for the last one only)
1319                 self._process_short_opts(rargs, values)
1320             elif self.allow_interspersed_args:
1321                 largs.append(arg)
1322                 del rargs[0]
1323             else:
1324                 return                  # stop now, leave this arg in rargs
1325 
1326         # Say this is the original argument list:
1327         # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1328         #                            ^
1329         # (we are about to process arg(i)).
1330         #
1331         # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1332         # [arg0, ..., arg(i-1)] (any options and their arguments will have
1333         # been removed from largs).
1334         #
1335         # The while loop will usually consume 1 or more arguments per pass.
1336         # If it consumes 1 (eg. arg is an option that takes no arguments),
1337         # then after _process_arg() is done the situation is:
1338         #
1339         #   largs = subset of [arg0, ..., arg(i)]
1340         #   rargs = [arg(i+1), ..., arg(N-1)]
1341         #
1342         # If allow_interspersed_args is false, largs will always be
1343         # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1344         # not a very interesting subset!
1345 
1346     def _match_long_opt(self, opt):
1347         """_match_long_opt(opt : string) -> string
1348 
1349         Determine which long option string 'opt' matches, ie. which one
1350         it is an unambiguous abbrevation for.  Raises BadOptionError if
1351         'opt' doesn't unambiguously match any long option string.
1352         """
1353         return _match_abbrev(opt, self._long_opt)
1354 
1355     def _process_long_opt(self, rargs, values):
1356         arg = rargs.pop(0)
1357 
1358         # Value explicitly attached to arg?  Pretend it's the next
1359         # argument.
1360         if "=" in arg:
1361             (opt, next_arg) = arg.split("=", 1)
1362             rargs.insert(0, next_arg)
1363             had_explicit_value = True
1364         else:
1365             opt = arg
1366             had_explicit_value = False
1367 
1368         opt = self._match_long_opt(opt)
1369         option = self._long_opt[opt]
1370         if option.takes_value():
1371             nargs = option.nargs
1372             if len(rargs) < nargs:
1373                 if nargs == 1:
1374                     self.error(_("%s option requires an argument") % opt)
1375                 else:
1376                     self.error(_("%s option requires %d arguments")
1377                                % (opt, nargs))
1378             elif nargs == 1:
1379                 value = rargs.pop(0)
1380             else:
1381                 value = tuple(rargs[0:nargs])
1382                 del rargs[0:nargs]
1383 
1384         elif had_explicit_value:
1385             self.error(_("%s option does not take a value") % opt)
1386 
1387         else:
1388             value = None
1389 
1390         option.process(opt, value, values, self)
1391 
1392     def _process_short_opts(self, rargs, values):
1393         arg = rargs.pop(0)
1394         stop = False
1395         i = 1
1396         for ch in arg[1:]:
1397             opt = "-" + ch
1398             option = self._short_opt.get(opt)
1399             i += 1                      # we have consumed a character
1400 
1401             if not option:
1402                 self.error(_("no such option: %s") % opt)
1403             if option.takes_value():
1404                 # Any characters left in arg?  Pretend they're the
1405                 # next arg, and stop consuming characters of arg.
1406                 if i < len(arg):
1407                     rargs.insert(0, arg[i:])
1408                     stop = True
1409 
1410                 nargs = option.nargs
1411                 if len(rargs) < nargs:
1412                     if nargs == 1:
1413                         self.error(_("%s option requires an argument") % opt)
1414                     else:
1415                         self.error(_("%s option requires %d arguments")
1416                                    % (opt, nargs))
1417                 elif nargs == 1:
1418                     value = rargs.pop(0)
1419                 else:
1420                     value = tuple(rargs[0:nargs])
1421                     del rargs[0:nargs]
1422 
1423             else:                       # option doesn't take a value
1424                 value = None
1425 
1426             option.process(opt, value, values, self)
1427 
1428             if stop:
1429                 break
1430 
1431 
1432     # -- Feedback methods ----------------------------------------------
1433 
1434     def get_prog_name(self):
1435         if self.prog is None:
1436             return os.path.basename(sys.argv[0])
1437         else:
1438             return self.prog
1439 
1440     def expand_prog_name(self, s):
1441         return s.replace("%prog", self.get_prog_name())
1442 
1443     def get_description(self):
1444         return self.expand_prog_name(self.description)
1445 
1446     def exit(self, status=0, msg=None):
1447         if msg:
1448             sys.stderr.write(msg)
1449         sys.exit(status)
1450 
1451     def error(self, msg):
1452         """error(msg : string)
1453 
1454         Print a usage message incorporating 'msg' to stderr and exit.
1455         If you override this in a subclass, it should not return -- it
1456         should either exit or raise an exception.
1457         """
1458         self.print_usage(sys.stderr)
1459         self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
1460 
1461     def get_usage(self):
1462         if self.usage:
1463             return self.formatter.format_usage(
1464                 self.expand_prog_name(self.usage))
1465         else:
1466             return ""
1467 
1468     def print_usage(self, file=None):
1469         """print_usage(file : file = stdout)
1470 
1471         Print the usage message for the current program (self.usage) to
1472         'file' (default stdout).  Any occurence of the string "%prog" in
1473         self.usage is replaced with the name of the current program
1474         (basename of sys.argv[0]).  Does nothing if self.usage is empty
1475         or not defined.
1476         """
1477         if self.usage:
1478             print >>file, self.get_usage()
1479 
1480     def get_version(self):
1481         if self.version:
1482             return self.expand_prog_name(self.version)
1483         else:
1484             return ""
1485 
1486     def print_version(self, file=None):
1487         """print_version(file : file = stdout)
1488 
1489         Print the version message for this program (self.version) to
1490         'file' (default stdout).  As with print_usage(), any occurence
1491         of "%prog" in self.version is replaced by the current program's
1492         name.  Does nothing if self.version is empty or undefined.
1493         """
1494         if self.version:
1495             print >>file, self.get_version()
1496 
1497     def format_option_help(self, formatter=None):
1498         if formatter is None:
1499             formatter = self.formatter
1500         formatter.store_option_strings(self)
1501         result = []
1502         result.append(formatter.format_heading(_("options")))
1503         formatter.indent()
1504         if self.option_list:
1505             result.append(OptionContainer.format_option_help(self, formatter))
1506             result.append("\n")
1507         for group in self.option_groups:
1508             result.append(group.format_help(formatter))
1509             result.append("\n")
1510         formatter.dedent()
1511         # Drop the last "\n", or the header if no options or option groups:
1512         return "".join(result[:-1])
1513 
1514     def format_help(self, formatter=None):
1515         if formatter is None:
1516             formatter = self.formatter
1517         result = []
1518         if self.usage:
1519             result.append(self.get_usage() + "\n")
1520         if self.description:
1521             result.append(self.format_description(formatter) + "\n")
1522         result.append(self.format_option_help(formatter))
1523         return "".join(result)
1524 
1525     def print_help(self, file=None):
1526         """print_help(file : file = stdout)
1527 
1528         Print an extended help message, listing all options and any
1529         help text provided with them, to 'file' (default stdout).
1530         """
1531         if file is None:
1532             file = sys.stdout
1533         file.write(self.format_help())
1534 
1535 # class OptionParser
1536 
1537 
1538 def _match_abbrev(s, wordmap):
1539     """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1540 
1541     Return the string key in 'wordmap' for which 's' is an unambiguous
1542     abbreviation.  If 's' is found to be ambiguous or doesn't match any of
1543     'words', raise BadOptionError.
1544     """
1545     # Is there an exact match?
1546     if wordmap.has_key(s):
1547         return s
1548     else:
1549         # Isolate all words with s as a prefix.
1550         possibilities = [word for word in wordmap.keys()
1551                          if word.startswith(s)]
1552         # No exact match, so there had better be just one possibility.
1553         if len(possibilities) == 1:
1554             return possibilities[0]
1555         elif not possibilities:
1556             raise BadOptionError(_("no such option: %s") % s)
1557         else:
1558             # More than one possible completion: ambiguous prefix.
1559             raise BadOptionError(_("ambiguous option: %s (%s?)")
1560                                  % (s, ", ".join(possibilities)))
1561 
1562 
1563 # Some day, there might be many Option classes.  As of Optik 1.3, the
1564 # preferred way to instantiate Options is indirectly, via make_option(),
1565 # which will become a factory function when there are many Option
1566 # classes.
1567 make_option = Option
1568 

Generated by PyXR 0.9.4
SourceForge.net Logo