1682 lines · 58.8 KB · Python
RawDownload
"""optparse - a powerful, extensible, and easy-to-use option parser. By Greg Ward <gward@python.net> Originally distributed as Optik; see http://optik.sourceforge.net/ . If you have problems with this module, please do not file bugs,patches, or feature requests with Python; instead, use Optik'sSourceForge project page:  http://sourceforge.net/projects/optik For support, use the optik-users@lists.sourceforge.net mailing list(http://lists.sourceforge.net/lists/listinfo/optik-users).""" # Python developers: please do not make changes to this file, since# it is automatically generated from the Optik source code. __version__ = "1.5.3" __all__ = ['Option',           'SUPPRESS_HELP',           'SUPPRESS_USAGE',           'Values',           'OptionContainer',           'OptionGroup',           'OptionParser',           'HelpFormatter',           'IndentedHelpFormatter',           'TitledHelpFormatter',           'OptParseError',           'OptionError',           'OptionConflictError',           'OptionValueError',           'BadOptionError'] __copyright__ = """Copyright (c) 2001-2006 Gregory P. Ward.  All rights reserved.Copyright (c) 2002-2006 Python Software Foundation.  All rights reserved. Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditions aremet:   * Redistributions of source code must retain the above copyright    notice, this list of conditions and the following disclaimer.   * Redistributions in binary form must reproduce the above copyright    notice, this list of conditions and the following disclaimer in the    documentation and/or other materials provided with the distribution.   * Neither the name of the author nor the names of its    contributors may be used to endorse or promote products derived from    this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "ASIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITEDTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR APARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR ORCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ORPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.""" import sys, osimport typesimport textwrap def _repr(self):    return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)  # This file was generated from:#   Id: option_parser.py 527 2006-07-23 15:21:30Z greg#   Id: option.py 522 2006-06-11 16:22:03Z gward#   Id: help.py 527 2006-07-23 15:21:30Z greg#   Id: errors.py 509 2006-04-20 00:58:24Z gward try:    from gettext import gettextexcept ImportError:    def gettext(message):        return message_ = gettext  class OptParseError (Exception):    def __init__(self, msg):        self.msg = msg     def __str__(self):        return self.msg  class OptionError (OptParseError):    """    Raised if an Option instance is created with invalid or    inconsistent arguments.    """     def __init__(self, msg, option):        self.msg = msg        self.option_id = str(option)     def __str__(self):        if self.option_id:            return "option %s: %s" % (self.option_id, self.msg)        else:            return self.msg class OptionConflictError (OptionError):    """    Raised if conflicting options are added to an OptionParser.    """ class OptionValueError (OptParseError):    """    Raised if an invalid option value is encountered on the command    line.    """ class BadOptionError (OptParseError):    """    Raised if an invalid option is seen on the command line.    """    def __init__(self, opt_str):        self.opt_str = opt_str     def __str__(self):        return _("no such option: %s") % self.opt_str class AmbiguousOptionError (BadOptionError):    """    Raised if an ambiguous option is seen on the command line.    """    def __init__(self, opt_str, possibilities):        BadOptionError.__init__(self, opt_str)        self.possibilities = possibilities     def __str__(self):        return (_("ambiguous option: %s (%s?)")                % (self.opt_str, ", ".join(self.possibilities)))  class HelpFormatter:     """    Abstract base class for formatting option help.  OptionParser    instances should use one of the HelpFormatter subclasses for    formatting help; by default IndentedHelpFormatter is used.     Instance attributes:      parser : OptionParser        the controlling OptionParser instance      indent_increment : int        the number of columns to indent per nesting level      max_help_position : int        the maximum starting column for option help text      help_position : int        the calculated starting column for option help text;        initially the same as the maximum      width : int        total number of columns for output (pass None to constructor for        this value to be taken from the $COLUMNS environment variable)      level : int        current indentation level      current_indent : int        current indentation level (in columns)      help_width : int        number of columns available for option help text (calculated)      default_tag : str        text to replace with each option's default value, "%default"        by default.  Set to false value to disable default value expansion.      option_strings : { Option : str }        maps Option instances to the snippet of help text explaining        the syntax of that option, e.g. "-h, --help" or        "-fFILE, --file=FILE"      _short_opt_fmt : str        format string controlling how short options with values are        printed in help text.  Must be either "%s%s" ("-fFILE") or        "%s %s" ("-f FILE"), because those are the two syntaxes that        Optik supports.      _long_opt_fmt : str        similar but for long options; must be either "%s %s" ("--file FILE")        or "%s=%s" ("--file=FILE").    """     NO_DEFAULT_VALUE = "none"     def __init__(self,                 indent_increment,                 max_help_position,                 width,                 short_first):        self.parser = None        self.indent_increment = indent_increment        self.help_position = self.max_help_position = max_help_position        if width is None:            try:                width = int(os.environ['COLUMNS'])            except (KeyError, ValueError):                width = 80            width -= 2        self.width = width        self.current_indent = 0        self.level = 0        self.help_width = None          # computed later        self.short_first = short_first        self.default_tag = "%default"        self.option_strings = {}        self._short_opt_fmt = "%s %s"        self._long_opt_fmt = "%s=%s"     def set_parser(self, parser):        self.parser = parser     def set_short_opt_delimiter(self, delim):        if delim not in ("", " "):            raise ValueError(                "invalid metavar delimiter for short options: %r" % delim)        self._short_opt_fmt = "%s" + delim + "%s"     def set_long_opt_delimiter(self, delim):        if delim not in ("=", " "):            raise ValueError(                "invalid metavar delimiter for long options: %r" % delim)        self._long_opt_fmt = "%s" + delim + "%s"     def indent(self):        self.current_indent += self.indent_increment        self.level += 1     def dedent(self):        self.current_indent -= self.indent_increment        assert self.current_indent >= 0, "Indent decreased below 0."        self.level -= 1     def format_usage(self, usage):        raise NotImplementedError, "subclasses must implement"     def format_heading(self, heading):        raise NotImplementedError, "subclasses must implement"     def _format_text(self, text):        """        Format a paragraph of free-form text for inclusion in the        help output at the current indentation level.        """        text_width = self.width - self.current_indent        indent = " "*self.current_indent        return textwrap.fill(text,                             text_width,                             initial_indent=indent,                             subsequent_indent=indent)     def format_description(self, description):        if description:            return self._format_text(description) + "\n"        else:            return ""     def format_epilog(self, epilog):        if epilog:            return "\n" + self._format_text(epilog) + "\n"        else:            return ""      def expand_default(self, option):        if self.parser is None or not self.default_tag:            return option.help         default_value = self.parser.defaults.get(option.dest)        if default_value is NO_DEFAULT or default_value is None:            default_value = self.NO_DEFAULT_VALUE         return option.help.replace(self.default_tag, str(default_value))     def format_option(self, option):        # The help for each option consists of two parts:        #   * the opt strings and metavars        #     eg. ("-x", or "-fFILENAME, --file=FILENAME")        #   * the user-supplied help string        #     eg. ("turn on expert mode", "read data from FILENAME")        #        # If possible, we write both of these on the same line:        #   -x      turn on expert mode        #        # But if the opt string list is too long, we put the help        # string on a second line, indented to the same column it would        # start in if it fit on the first line.        #   -fFILENAME, --file=FILENAME        #           read data from FILENAME        result = []        opts = self.option_strings[option]        opt_width = self.help_position - self.current_indent - 2        if len(opts) > opt_width:            opts = "%*s%s\n" % (self.current_indent, "", opts)            indent_first = self.help_position        else:                       # start help on same line as opts            opts = "%*s%-*s  " % (self.current_indent, "", opt_width, opts)            indent_first = 0        result.append(opts)        if option.help:            help_text = self.expand_default(option)            help_lines = textwrap.wrap(help_text, self.help_width)            result.append("%*s%s\n" % (indent_first, "", help_lines[0]))            result.extend(["%*s%s\n" % (self.help_position, "", line)                           for line in help_lines[1:]])        elif opts[-1] != "\n":            result.append("\n")        return "".join(result)     def store_option_strings(self, parser):        self.indent()        max_len = 0        for opt in parser.option_list:            strings = self.format_option_strings(opt)            self.option_strings[opt] = strings            max_len = max(max_len, len(strings) + self.current_indent)        self.indent()        for group in parser.option_groups:            for opt in group.option_list:                strings = self.format_option_strings(opt)                self.option_strings[opt] = strings                max_len = max(max_len, len(strings) + self.current_indent)        self.dedent()        self.dedent()        self.help_position = min(max_len + 2, self.max_help_position)        self.help_width = self.width - self.help_position     def format_option_strings(self, option):        """Return a comma-separated list of option strings & metavariables."""        if option.takes_value():            metavar = option.metavar or option.dest.upper()            short_opts = [self._short_opt_fmt % (sopt, metavar)                          for sopt in option._short_opts]            long_opts = [self._long_opt_fmt % (lopt, metavar)                         for lopt in option._long_opts]        else:            short_opts = option._short_opts            long_opts = option._long_opts         if self.short_first:            opts = short_opts + long_opts        else:            opts = long_opts + short_opts         return ", ".join(opts) class IndentedHelpFormatter (HelpFormatter):    """Format help with indented section bodies.    """     def __init__(self,                 indent_increment=2,                 max_help_position=24,                 width=None,                 short_first=1):        HelpFormatter.__init__(            self, indent_increment, max_help_position, width, short_first)     def format_usage(self, usage):        return _("Usage: %s\n") % usage     def format_heading(self, heading):        return "%*s%s:\n" % (self.current_indent, "", heading)  class TitledHelpFormatter (HelpFormatter):    """Format help with underlined section headers.    """     def __init__(self,                 indent_increment=0,                 max_help_position=24,                 width=None,                 short_first=0):        HelpFormatter.__init__ (            self, indent_increment, max_help_position, width, short_first)     def format_usage(self, usage):        return "%s  %s\n" % (self.format_heading(_("Usage")), usage)     def format_heading(self, heading):        return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))  def _parse_num(val, type):    if val[:2].lower() == "0x":         # hexadecimal        radix = 16    elif val[:2].lower() == "0b":       # binary        radix = 2        val = val[2:] or "0"            # have to remove "0b" prefix    elif val[:1] == "0":                # octal        radix = 8    else:                               # decimal        radix = 10     return type(val, radix) def _parse_int(val):    return _parse_num(val, int) def _parse_long(val):    return _parse_num(val, long) _builtin_cvt = { "int" : (_parse_int, _("integer")),                 "long" : (_parse_long, _("long integer")),                 "float" : (float, _("floating-point")),                 "complex" : (complex, _("complex")) } def check_builtin(option, opt, value):    (cvt, what) = _builtin_cvt[option.type]    try:        return cvt(value)    except ValueError:        raise OptionValueError(            _("option %s: invalid %s value: %r") % (opt, what, value)) def check_choice(option, opt, value):    if value in option.choices:        return value    else:        choices = ", ".join(map(repr, option.choices))        raise OptionValueError(            _("option %s: invalid choice: %r (choose from %s)")            % (opt, value, choices)) # Not supplying a default is different from a default of None,# so we need an explicit "not supplied" value.NO_DEFAULT = ("NO", "DEFAULT")  class Option:    """    Instance attributes:      _short_opts : [string]      _long_opts : [string]       action : string      type : string      dest : string      default : any      nargs : int      const : any      choices : [string]      callback : function      callback_args : (any*)      callback_kwargs : { string : any }      help : string      metavar : string    """     # The list of instance attributes that may be set through    # keyword args to the constructor.    ATTRS = ['action',             'type',             'dest',             'default',             'nargs',             'const',             'choices',             'callback',             'callback_args',             'callback_kwargs',             'help',             'metavar']     # The set of actions allowed by option parsers.  Explicitly listed    # here so the constructor can validate its arguments.    ACTIONS = ("store",               "store_const",               "store_true",               "store_false",               "append",               "append_const",               "count",               "callback",               "help",               "version")     # The set of actions that involve storing a value somewhere;    # also listed just for constructor argument validation.  (If    # the action is one of these, there must be a destination.)    STORE_ACTIONS = ("store",                     "store_const",                     "store_true",                     "store_false",                     "append",                     "append_const",                     "count")     # The set of actions for which it makes sense to supply a value    # type, ie. which may consume an argument from the command line.    TYPED_ACTIONS = ("store",

Lines 1–500 of 1682.