mirror of
https://github.com/python/cpython.git
synced 2025-09-15 05:06:12 +00:00
Update optparse to Optik 1.5.1.
This commit is contained in:
parent
cdd432808f
commit
ab05edc0d1
4 changed files with 636 additions and 182 deletions
204
Lib/optparse.py
204
Lib/optparse.py
|
@ -16,7 +16,7 @@ For support, use the optik-users@lists.sourceforge.net mailing list
|
|||
# Python developers: please do not make changes to this file, since
|
||||
# it is automatically generated from the Optik source code.
|
||||
|
||||
__version__ = "1.5a2"
|
||||
__version__ = "1.5.1"
|
||||
|
||||
__all__ = ['Option',
|
||||
'SUPPRESS_HELP',
|
||||
|
@ -35,8 +35,8 @@ __all__ = ['Option',
|
|||
'BadOptionError']
|
||||
|
||||
__copyright__ = """
|
||||
Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved.
|
||||
Copyright (c) 2002-2004 Python Software Foundation. All rights reserved.
|
||||
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 without
|
||||
modification, are permitted provided that the following conditions are
|
||||
|
@ -67,21 +67,26 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
"""
|
||||
|
||||
import sys, os
|
||||
import types
|
||||
import textwrap
|
||||
try:
|
||||
from gettext import gettext as _
|
||||
except ImportError:
|
||||
_ = lambda arg: arg
|
||||
|
||||
def _repr(self):
|
||||
return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
|
||||
|
||||
|
||||
# This file was generated from:
|
||||
# Id: option_parser.py 421 2004-10-26 00:45:16Z greg
|
||||
# Id: option.py 422 2004-10-26 00:53:47Z greg
|
||||
# Id: help.py 367 2004-07-24 23:21:21Z gward
|
||||
# Id: errors.py 367 2004-07-24 23:21:21Z gward
|
||||
# Id: option_parser.py 509 2006-04-20 00:58:24Z gward
|
||||
# Id: option.py 509 2006-04-20 00:58:24Z gward
|
||||
# Id: help.py 509 2006-04-20 00:58:24Z gward
|
||||
# Id: errors.py 509 2006-04-20 00:58:24Z gward
|
||||
|
||||
try:
|
||||
from gettext import gettext
|
||||
except ImportError:
|
||||
def gettext(message):
|
||||
return message
|
||||
_ = gettext
|
||||
|
||||
|
||||
class OptParseError (Exception):
|
||||
def __init__(self, msg):
|
||||
|
@ -120,8 +125,25 @@ class OptionValueError (OptParseError):
|
|||
|
||||
class BadOptionError (OptParseError):
|
||||
"""
|
||||
Raised if an invalid or ambiguous option is seen on the command-line.
|
||||
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:
|
||||
|
@ -223,15 +245,30 @@ class HelpFormatter:
|
|||
def format_heading(self, heading):
|
||||
raise NotImplementedError, "subclasses must implement"
|
||||
|
||||
def format_description(self, description):
|
||||
if not description:
|
||||
return ""
|
||||
desc_width = self.width - self.current_indent
|
||||
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(description,
|
||||
desc_width,
|
||||
return textwrap.fill(text,
|
||||
text_width,
|
||||
initial_indent=indent,
|
||||
subsequent_indent=indent) + "\n"
|
||||
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:
|
||||
|
@ -328,7 +365,7 @@ class IndentedHelpFormatter (HelpFormatter):
|
|||
self, indent_increment, max_help_position, width, short_first)
|
||||
|
||||
def format_usage(self, usage):
|
||||
return _("usage: %s\n") % usage
|
||||
return _("Usage: %s\n") % usage
|
||||
|
||||
def format_heading(self, heading):
|
||||
return "%*s%s:\n" % (self.current_indent, "", heading)
|
||||
|
@ -353,8 +390,27 @@ class TitledHelpFormatter (HelpFormatter):
|
|||
return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
|
||||
|
||||
|
||||
_builtin_cvt = { "int" : (int, _("integer")),
|
||||
"long" : (long, _("long integer")),
|
||||
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")) }
|
||||
|
||||
|
@ -422,6 +478,7 @@ class Option:
|
|||
"store_true",
|
||||
"store_false",
|
||||
"append",
|
||||
"append_const",
|
||||
"count",
|
||||
"callback",
|
||||
"help",
|
||||
|
@ -435,6 +492,7 @@ class Option:
|
|||
"store_true",
|
||||
"store_false",
|
||||
"append",
|
||||
"append_const",
|
||||
"count")
|
||||
|
||||
# The set of actions for which it makes sense to supply a value
|
||||
|
@ -448,6 +506,10 @@ class Option:
|
|||
ALWAYS_TYPED_ACTIONS = ("store",
|
||||
"append")
|
||||
|
||||
# The set of actions which take a 'const' attribute.
|
||||
CONST_ACTIONS = ("store_const",
|
||||
"append_const")
|
||||
|
||||
# The set of known types for option parsers. Again, listed here for
|
||||
# constructor argument validation.
|
||||
TYPES = ("string", "int", "long", "float", "complex", "choice")
|
||||
|
@ -572,9 +634,17 @@ class Option:
|
|||
# No type given? "string" is the most sensible default.
|
||||
self.type = "string"
|
||||
else:
|
||||
# Allow type objects as an alternative to their names.
|
||||
if type(self.type) is type:
|
||||
# Allow type objects or builtin type conversion functions
|
||||
# (int, str, etc.) as an alternative to their names. (The
|
||||
# complicated check of __builtin__ is only necessary for
|
||||
# Python 2.1 and earlier, and is short-circuited by the
|
||||
# first check on modern Pythons.)
|
||||
import __builtin__
|
||||
if ( type(self.type) is types.TypeType or
|
||||
(hasattr(self.type, "__name__") and
|
||||
getattr(__builtin__, self.type.__name__, None) is self.type) ):
|
||||
self.type = self.type.__name__
|
||||
|
||||
if self.type == "str":
|
||||
self.type = "string"
|
||||
|
||||
|
@ -589,7 +659,7 @@ class Option:
|
|||
if self.choices is None:
|
||||
raise OptionError(
|
||||
"must supply a list of choices for type 'choice'", self)
|
||||
elif type(self.choices) not in (tuple, list):
|
||||
elif type(self.choices) not in (types.TupleType, types.ListType):
|
||||
raise OptionError(
|
||||
"choices must be a list of strings ('%s' supplied)"
|
||||
% str(type(self.choices)).split("'")[1], self)
|
||||
|
@ -613,7 +683,7 @@ class Option:
|
|||
self.dest = self._short_opts[0][1]
|
||||
|
||||
def _check_const(self):
|
||||
if self.action != "store_const" and self.const is not None:
|
||||
if self.action not in self.CONST_ACTIONS and self.const is not None:
|
||||
raise OptionError(
|
||||
"'const' must not be supplied for action %r" % self.action,
|
||||
self)
|
||||
|
@ -633,12 +703,12 @@ class Option:
|
|||
raise OptionError(
|
||||
"callback not callable: %r" % self.callback, self)
|
||||
if (self.callback_args is not None and
|
||||
type(self.callback_args) is not tuple):
|
||||
type(self.callback_args) is not types.TupleType):
|
||||
raise OptionError(
|
||||
"callback_args, if supplied, must be a tuple: not %r"
|
||||
% self.callback_args, self)
|
||||
if (self.callback_kwargs is not None and
|
||||
type(self.callback_kwargs) is not dict):
|
||||
type(self.callback_kwargs) is not types.DictType):
|
||||
raise OptionError(
|
||||
"callback_kwargs, if supplied, must be a dict: not %r"
|
||||
% self.callback_kwargs, self)
|
||||
|
@ -720,6 +790,8 @@ class Option:
|
|||
setattr(values, dest, False)
|
||||
elif action == "append":
|
||||
values.ensure_value(dest, []).append(value)
|
||||
elif action == "append_const":
|
||||
values.ensure_value(dest, []).append(self.const)
|
||||
elif action == "count":
|
||||
setattr(values, dest, values.ensure_value(dest, 0) + 1)
|
||||
elif action == "callback":
|
||||
|
@ -748,11 +820,9 @@ try:
|
|||
True, False
|
||||
except NameError:
|
||||
(True, False) = (1, 0)
|
||||
try:
|
||||
basestring
|
||||
except NameError:
|
||||
basestring = (str, unicode)
|
||||
|
||||
def isbasestring(x):
|
||||
return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType)
|
||||
|
||||
class Values:
|
||||
|
||||
|
@ -766,16 +836,13 @@ class Values:
|
|||
|
||||
__repr__ = _repr
|
||||
|
||||
def __eq__(self, other):
|
||||
def __cmp__(self, other):
|
||||
if isinstance(other, Values):
|
||||
return self.__dict__ == other.__dict__
|
||||
elif isinstance(other, dict):
|
||||
return self.__dict__ == other
|
||||
return cmp(self.__dict__, other.__dict__)
|
||||
elif isinstance(other, types.DictType):
|
||||
return cmp(self.__dict__, other)
|
||||
else:
|
||||
return False
|
||||
|
||||
def __ne__(self, other):
|
||||
return not (self == other)
|
||||
return -1
|
||||
|
||||
def _update_careful(self, dict):
|
||||
"""
|
||||
|
@ -893,6 +960,13 @@ class OptionContainer:
|
|||
return self.description
|
||||
|
||||
|
||||
def destroy(self):
|
||||
"""see OptionParser.destroy()."""
|
||||
del self._short_opt
|
||||
del self._long_opt
|
||||
del self.defaults
|
||||
|
||||
|
||||
# -- Option-adding methods -----------------------------------------
|
||||
|
||||
def _check_conflict(self, option):
|
||||
|
@ -926,7 +1000,7 @@ class OptionContainer:
|
|||
"""add_option(Option)
|
||||
add_option(opt_str, ..., kwarg=val, ...)
|
||||
"""
|
||||
if type(args[0]) is str:
|
||||
if type(args[0]) is types.StringType:
|
||||
option = self.option_class(*args, **kwargs)
|
||||
elif len(args) == 1 and not kwargs:
|
||||
option = args[0]
|
||||
|
@ -1018,6 +1092,11 @@ class OptionGroup (OptionContainer):
|
|||
def set_title(self, title):
|
||||
self.title = title
|
||||
|
||||
def destroy(self):
|
||||
"""see OptionParser.destroy()."""
|
||||
OptionContainer.destroy(self)
|
||||
del self.option_list
|
||||
|
||||
# -- Help-formatting methods ---------------------------------------
|
||||
|
||||
def format_help(self, formatter):
|
||||
|
@ -1044,6 +1123,8 @@ class OptionParser (OptionContainer):
|
|||
prog : string
|
||||
the name of the current program (to override
|
||||
os.path.basename(sys.argv[0])).
|
||||
epilog : string
|
||||
paragraph of help text to print after option help
|
||||
|
||||
option_groups : [OptionGroup]
|
||||
list of option groups in this parser (option groups are
|
||||
|
@ -1102,7 +1183,8 @@ class OptionParser (OptionContainer):
|
|||
description=None,
|
||||
formatter=None,
|
||||
add_help_option=True,
|
||||
prog=None):
|
||||
prog=None,
|
||||
epilog=None):
|
||||
OptionContainer.__init__(
|
||||
self, option_class, conflict_handler, description)
|
||||
self.set_usage(usage)
|
||||
|
@ -1114,6 +1196,7 @@ class OptionParser (OptionContainer):
|
|||
formatter = IndentedHelpFormatter()
|
||||
self.formatter = formatter
|
||||
self.formatter.set_parser(self)
|
||||
self.epilog = epilog
|
||||
|
||||
# Populate the option list; initial sources are the
|
||||
# standard_option_list class attribute, the 'option_list'
|
||||
|
@ -1124,6 +1207,22 @@ class OptionParser (OptionContainer):
|
|||
|
||||
self._init_parsing_state()
|
||||
|
||||
|
||||
def destroy(self):
|
||||
"""
|
||||
Declare that you are done with this OptionParser. This cleans up
|
||||
reference cycles so the OptionParser (and all objects referenced by
|
||||
it) can be garbage-collected promptly. After calling destroy(), the
|
||||
OptionParser is unusable.
|
||||
"""
|
||||
OptionContainer.destroy(self)
|
||||
for group in self.option_groups:
|
||||
group.destroy()
|
||||
del self.option_list
|
||||
del self.option_groups
|
||||
del self.formatter
|
||||
|
||||
|
||||
# -- Private methods -----------------------------------------------
|
||||
# (used by our or OptionContainer's constructor)
|
||||
|
||||
|
@ -1167,7 +1266,7 @@ class OptionParser (OptionContainer):
|
|||
elif usage is SUPPRESS_USAGE:
|
||||
self.usage = None
|
||||
# For backwards compatibility with Optik 1.3 and earlier.
|
||||
elif usage.startswith("usage:" + " "):
|
||||
elif usage.lower().startswith("usage: "):
|
||||
self.usage = usage[7:]
|
||||
else:
|
||||
self.usage = usage
|
||||
|
@ -1201,7 +1300,7 @@ class OptionParser (OptionContainer):
|
|||
defaults = self.defaults.copy()
|
||||
for option in self._get_all_options():
|
||||
default = defaults.get(option.dest)
|
||||
if isinstance(default, basestring):
|
||||
if isbasestring(default):
|
||||
opt_str = option.get_opt_string()
|
||||
defaults[option.dest] = option.check_value(opt_str, default)
|
||||
|
||||
|
@ -1212,7 +1311,7 @@ class OptionParser (OptionContainer):
|
|||
|
||||
def add_option_group(self, *args, **kwargs):
|
||||
# XXX lots of overlap with OptionContainer.add_option()
|
||||
if type(args[0]) is str:
|
||||
if type(args[0]) is types.StringType:
|
||||
group = OptionGroup(self, *args, **kwargs)
|
||||
elif len(args) == 1 and not kwargs:
|
||||
group = args[0]
|
||||
|
@ -1276,7 +1375,7 @@ class OptionParser (OptionContainer):
|
|||
try:
|
||||
stop = self._process_args(largs, rargs, values)
|
||||
except (BadOptionError, OptionValueError), err:
|
||||
self.error(err.msg)
|
||||
self.error(str(err))
|
||||
|
||||
args = largs + rargs
|
||||
return self.check_values(values, args)
|
||||
|
@ -1401,7 +1500,7 @@ class OptionParser (OptionContainer):
|
|||
i += 1 # we have consumed a character
|
||||
|
||||
if not option:
|
||||
self.error(_("no such option: %s") % opt)
|
||||
raise BadOptionError(opt)
|
||||
if option.takes_value():
|
||||
# Any characters left in arg? Pretend they're the
|
||||
# next arg, and stop consuming characters of arg.
|
||||
|
@ -1501,7 +1600,7 @@ class OptionParser (OptionContainer):
|
|||
formatter = self.formatter
|
||||
formatter.store_option_strings(self)
|
||||
result = []
|
||||
result.append(formatter.format_heading(_("options")))
|
||||
result.append(formatter.format_heading(_("Options")))
|
||||
formatter.indent()
|
||||
if self.option_list:
|
||||
result.append(OptionContainer.format_option_help(self, formatter))
|
||||
|
@ -1513,6 +1612,9 @@ class OptionParser (OptionContainer):
|
|||
# Drop the last "\n", or the header if no options or option groups:
|
||||
return "".join(result[:-1])
|
||||
|
||||
def format_epilog(self, formatter):
|
||||
return formatter.format_epilog(self.epilog)
|
||||
|
||||
def format_help(self, formatter=None):
|
||||
if formatter is None:
|
||||
formatter = self.formatter
|
||||
|
@ -1522,6 +1624,7 @@ class OptionParser (OptionContainer):
|
|||
if self.description:
|
||||
result.append(self.format_description(formatter) + "\n")
|
||||
result.append(self.format_option_help(formatter))
|
||||
result.append(self.format_epilog(formatter))
|
||||
return "".join(result)
|
||||
|
||||
def print_help(self, file=None):
|
||||
|
@ -1555,11 +1658,10 @@ def _match_abbrev(s, wordmap):
|
|||
if len(possibilities) == 1:
|
||||
return possibilities[0]
|
||||
elif not possibilities:
|
||||
raise BadOptionError(_("no such option: %s") % s)
|
||||
raise BadOptionError(s)
|
||||
else:
|
||||
# More than one possible completion: ambiguous prefix.
|
||||
raise BadOptionError(_("ambiguous option: %s (%s?)")
|
||||
% (s, ", ".join(possibilities)))
|
||||
raise AmbiguousOptionError(s, possibilities)
|
||||
|
||||
|
||||
# Some day, there might be many Option classes. As of Optik 1.3, the
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue