4a3d3a89504fc28ca956b654962dbfee4b4a8848
"""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's
SourceForge 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.
Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved.
Copyright (c) 2002-2004 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
* 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 "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
CONTRIBUTORS 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, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from gettext
import gettext
as _
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
class OptParseError (Exception):
class OptionError (OptParseError
):
Raised if an Option instance is created with invalid or
def __init__(self
, msg
, option
):
self
.option_id
= str(option
)
return "option %s: %s" % (self
.option_id
, 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
class BadOptionError (OptParseError
):
Raised if an invalid or ambiguous option is seen on the command-line.
Abstract base class for formatting option help. OptionParser
instances should use one of the HelpFormatter subclasses for
formatting help; by default IndentedHelpFormatter is used.
the controlling OptionParser instance
the number of columns to indent per nesting level
the maximum starting column for option help text
the calculated starting column for option help text;
initially the same as the maximum
total number of columns for output (pass None to constructor for
this value to be taken from the $COLUMNS environment variable)
current indentation level
current indentation level (in columns)
number of columns available for option help text (calculated)
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
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
similar but for long options; must be either "%s %s" ("--file FILE")
or "%s=%s" ("--file=FILE").
NO_DEFAULT_VALUE
= "none"
self
.indent_increment
= indent_increment
self
.help_position
= self
.max_help_position
= max_help_position
width
= int(os
.environ
['COLUMNS'])
except (KeyError, ValueError):
self
.help_width
= None # computed later
self
.short_first
= short_first
self
.default_tag
= "%default"
self
._short
_opt
_fmt
= "%s %s"
self
._long
_opt
_fmt
= "%s=%s"
def set_parser(self
, parser
):
def set_short_opt_delimiter(self
, delim
):
if delim
not in ("", " "):
"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 ("=", " "):
"invalid metavar delimiter for long options: %r" % delim
)
self
._long
_opt
_fmt
= "%s" + delim
+ "%s"
self
.current_indent
+= self
.indent_increment
self
.current_indent
-= self
.indent_increment
assert self
.current_indent
>= 0, "Indent decreased below 0."
def format_usage(self
, usage
):
raise NotImplementedError, "subclasses must implement"
def format_heading(self
, heading
):
raise NotImplementedError, "subclasses must implement"
def format_description(self
, description
):
desc_width
= self
.width
- self
.current_indent
indent
= " "*self
.current_indent
return textwrap
.fill(description
,
subsequent_indent
=indent
) + "\n"
def expand_default(self
, option
):
if self
.parser
is None or not self
.default_tag
:
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:
# 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
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
)
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:]])
def store_option_strings(self
, parser
):
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
)
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
.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."""
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
]
short_opts
= option
._short
_opts
long_opts
= option
._long
_opts
opts
= short_opts
+ long_opts
opts
= long_opts
+ short_opts
class IndentedHelpFormatter (HelpFormatter
):
"""Format help with indented section bodies.
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.
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
))
_builtin_cvt
= { "int" : (int, _("integer")),
"long" : (long, _("long integer")),
"float" : (float, _("floating-point")),
"complex" : (complex, _("complex")) }
def check_builtin(option
, opt
, value
):
(cvt
, what
) = _builtin_cvt
[option
.type]
_("option %s: invalid %s value: %r") % (opt
, what
, value
))
def check_choice(option
, opt
, value
):
if value
in option
.choices
:
choices
= ", ".join(map(repr, option
.choices
))
_("option %s: invalid choice: %r (choose from %s)")
# Not supplying a default is different from a default of None,
# so we need an explicit "not supplied" value.
NO_DEFAULT
= ("NO", "DEFAULT")
callback_kwargs : { string : any }
# The list of instance attributes that may be set through
# keyword args to the constructor.
# The set of actions allowed by option parsers. Explicitly listed
# here so the constructor can validate its arguments.
# 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",
# 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",
# The set of actions which *require* a value type, ie. that
# always consume an argument from the command line.
ALWAYS_TYPED_ACTIONS
= ("store",
# The set of known types for option parsers. Again, listed here for
# constructor argument validation.
TYPES
= ("string", "int", "long", "float", "complex", "choice")
# Dictionary of argument checking functions, which convert and
# validate option arguments according to the option type.
# Signature of checking functions is:
# check(option : Option, opt : string, value : string) -> any
# option is the Option instance calling the checker
# opt is the actual option seen on the command-line
# value is the option argument seen on the command-line
# The return value should be in the appropriate Python type
# for option.type -- eg. an integer if option.type == "int".
# If no checker is defined for a type, arguments will be
# unchecked and remain strings.
TYPE_CHECKER
= { "int" : check_builtin
,
"complex": check_builtin
,
# CHECK_METHODS is a list of unbound method objects; they are called
# by the constructor, in order, after all attributes are
# initialized. The list is created and filled in later, after all
# the methods are actually defined. (I just put it here because I
# like to define and document all class attributes in the same
# place.) Subclasses that add another _check_*() method should
# define their own CHECK_METHODS list that adds their check method
# to those from this class.
# -- Constructor/initialization methods ----------------------------
def __init__(self
, *opts
, **attrs
):
# Set _short_opts, _long_opts attrs from 'opts' tuple.
# Have to be set now, in case no option strings are supplied.
opts
= self
._check
_opt
_strings
(opts
)
self
._set
_opt
_strings
(opts
)
# Set all other attrs (action, type, etc.) from 'attrs' dict
# Check all the attributes we just set. There are lots of
# complicated interdependencies, but luckily they can be farmed
# out to the _check_*() methods listed in CHECK_METHODS -- which
# could be handy for subclasses! The one thing these all share
# is that they raise OptionError if they discover a problem.
for checker
in self
.CHECK_METHODS
:
def _check_opt_strings(self
, opts
):
# Filter out None because early versions of Optik had exactly
# one short option and one long option, either of which
opts
= filter(None, opts
)
raise TypeError("at least one option string must be supplied")
def _set_opt_strings(self
, opts
):
"invalid option string %r: "
"must be at least two characters long" % opt
, self
)
if not (opt
[0] == "-" and opt
[1] != "-"):
"invalid short option string %r: "
"must be of the form -x, (x any non-dash char)" % opt
,
self
._short
_opts
.append(opt
)
if not (opt
[0:2] == "--" and opt
[2] != "-"):
"invalid long option string %r: "
"must start with --, followed by non-dash" % opt
,
self
._long
_opts
.append(opt
)
def _set_attrs(self
, attrs
):
setattr(self
, attr
, attrs
[attr
])
setattr(self
, attr
, NO_DEFAULT
)
setattr(self
, attr
, None)
"invalid keyword arguments: %s" % ", ".join(attrs
.keys()),
# -- Constructor validation methods --------------------------------
elif self
.action
not in self
.ACTIONS
:
raise OptionError("invalid action: %r" % self
.action
, self
)
if self
.action
in self
.ALWAYS_TYPED_ACTIONS
:
if self
.choices
is not None:
# The "choices" attribute implies "choice" type.
# No type given? "string" is the most sensible default.
# Allow type objects as an alternative to their names.
if type(self
.type) is type:
self
.type = self
.type.__name
__
if self
.type not in self
.TYPES
:
raise OptionError("invalid option type: %r" % self
.type, self
)
if self
.action
not in self
.TYPED_ACTIONS
:
"must not supply a type for action %r" % self
.action
, self
)
if self
.type == "choice":
"must supply a list of choices for type 'choice'", self
)
elif type(self
.choices
) not in (types
.TupleType
, types
.ListType
):
"choices must be a list of strings ('%s' supplied)"
% str(type(self
.choices
)).split("'")[1], self
)
elif self
.choices
is not None:
"must not supply choices for type %r" % self
.type, self
)
# No destination given, and we need one for this action. The
# self.type check is for callbacks that take a value.
takes_value
= (self
.action
in self
.STORE_ACTIONS
or
if self
.dest
is None and takes_value
:
# Glean a destination from the first long option string,
# or from the first short option string if no long options.
# eg. "--foo-bar" -> "foo_bar"
self
.dest
= self
._long
_opts
[0][2:].replace('-', '_')
self
.dest
= self
._short
_opts
[0][1]
if self
.action
!= "store_const" and self
.const
is not None:
"'const' must not be supplied for action %r" % self
.action
,
if self
.action
in self
.TYPED_ACTIONS
:
elif self
.nargs
is not None:
"'nargs' must not be supplied for action %r" % self
.action
,
def _check_callback(self
):
if self
.action
== "callback":
if not callable(self
.callback
):
"callback not callable: %r" % self
.callback
, self
)
if (self
.callback_args
is not None and
type(self
.callback_args
) is not types
.TupleType
):
"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 types
.DictType
):
"callback_kwargs, if supplied, must be a dict: not %r"
% self
.callback_kwargs
, self
)
if self
.callback
is not None:
"callback supplied (%r) for non-callback option"
if self
.callback_args
is not None:
"callback_args supplied for non-callback option", self
)
if self
.callback_kwargs
is not None:
"callback_kwargs supplied for non-callback option", self
)
CHECK_METHODS
= [_check_action
,
# -- Miscellaneous methods -----------------------------------------
return "/".join(self
._short
_opts
+ self
._long
_opts
)
return self
.type is not None
def get_opt_string(self
):
return self
._long
_opts
[0]
return self
._short
_opts
[0]
# -- Processing methods --------------------------------------------
def check_value(self
, opt
, value
):
checker
= self
.TYPE_CHECKER
.get(self
.type)
return checker(self
, opt
, value
)
def convert_value(self
, opt
, value
):
return self
.check_value(opt
, value
)
return tuple([self
.check_value(opt
, v
) for v
in value
])
def process(self
, opt
, value
, values
, parser
):
# First, convert the value(s) to the right type. Howl if any
value
= self
.convert_value(opt
, value
)
# And then take whatever action is expected of us.
# This is a separate method to make life easier for
# subclasses to add new actions.
self
.action
, self
.dest
, opt
, value
, values
, parser
)
def take_action(self
, action
, dest
, opt
, value
, values
, parser
):
setattr(values
, dest
, value
)
elif action
== "store_const":
setattr(values
, dest
, self
.const
)
elif action
== "store_true":
setattr(values
, dest
, True)
elif action
== "store_false":
setattr(values
, dest
, False)
values
.ensure_value(dest
, []).append(value
)
setattr(values
, dest
, values
.ensure_value(dest
, 0) + 1)
elif action
== "callback":
args
= self
.callback_args
or ()
kwargs
= self
.callback_kwargs
or {}
self
.callback(self
, opt
, value
, parser
, *args
, **kwargs
)
elif action
== "version":
raise RuntimeError, "unknown action %r" % self
.action
SUPPRESS_HELP
= "SUPPRESS"+"HELP"
SUPPRESS_USAGE
= "SUPPRESS"+"USAGE"
# For compatibility with Python 2.2
basestring
= (str, unicode)
def __init__(self
, defaults
=None):
for (attr
, val
) in defaults
.items():
return str(self
.__dict
__)
if isinstance(other
, Values
):
return self
.__dict
__ == other
.__dict
__
elif isinstance(other
, dict):
return self
.__dict
__ == other
return not (self
== other
)
def _update_careful(self
, dict):
Update the option values from an arbitrary dictionary, but only
use keys from dict that already have a corresponding attribute
in self. Any keys in dict without a corresponding attribute
setattr(self
, attr
, dval
)
def _update_loose(self
, dict):
Update the option values from an arbitrary dictionary,
using all keys from the dictionary regardless of whether
they have a corresponding attribute in self or not.
self
.__dict
__.update(dict)
def _update(self
, dict, mode
):
self
._update
_careful
(dict)
raise ValueError, "invalid update mode: %r" % mode
def read_module(self
, modname
, mode
="careful"):
mod
= sys
.modules
[modname
]
self
._update
(vars(mod
), mode
)
def read_file(self
, filename
, mode
="careful"):
def ensure_value(self
, attr
, value
):
if not hasattr(self
, attr
) or getattr(self
, attr
) is None:
setattr(self
, attr
, value
)
return getattr(self
, attr
)
standard_option_list : [Option]
list of standard options that will be accepted by all instances
of this parser class (intended to be overridden by subclasses).
the list of Option objects contained by this OptionContainer
_short_opt : { string : Option }
dictionary mapping short option strings, eg. "-f" or "-X",
to the Option instances that implement them. If an Option
has multiple short option strings, it will appears in this
dictionary multiple times. [1]
_long_opt : { string : Option }
dictionary mapping long option strings, eg. "--file" or
"--exclude", to the Option instances that implement them.
Again, a given Option can occur multiple times in this
defaults : { string : any }
dictionary mapping option destination names to default
values for each destination [1]
[1] These mappings are common to (shared by) all components of the
controlling OptionParser, where they are initially created.
def __init__(self
, option_class
, conflict_handler
, description
):
# Initialize the option list and related data structures.
# This method must be provided by subclasses, and it must
# initialize at least the following instance attributes:
# option_list, _short_opt, _long_opt, defaults.
self
._create
_option
_list
()
self
.option_class
= option_class
self
.set_conflict_handler(conflict_handler
)
self
.set_description(description
)
def _create_option_mappings(self
):
# For use by OptionParser constructor -- create the master
# option mappings used by this OptionParser and all
# OptionGroups that it owns.
self
._short
_opt
= {} # single letter -> Option instance
self
._long
_opt
= {} # long option -> Option instance
self
.defaults
= {} # maps option dest -> default value
def _share_option_mappings(self
, parser
):
# For use by OptionGroup constructor -- use shared option
# mappings from the OptionParser that owns this OptionGroup.
self
._short
_opt
= parser
._short
_opt
self
._long
_opt
= parser
._long
_opt
self
.defaults
= parser
.defaults
def set_conflict_handler(self
, handler
):
if handler
not in ("error", "resolve"):
raise ValueError, "invalid conflict_resolution value %r" % handler
self
.conflict_handler
= handler
def set_description(self
, description
):
self
.description
= description
def get_description(self
):
# -- Option-adding methods -----------------------------------------
def _check_conflict(self
, option
):
for opt
in option
._short
_opts
:
if self
._short
_opt
.has_key(opt
):
conflict_opts
.append((opt
, self
._short
_opt
[opt
]))
for opt
in option
._long
_opts
:
if self
._long
_opt
.has_key(opt
):
conflict_opts
.append((opt
, self
._long
_opt
[opt
]))
handler
= self
.conflict_handler
raise OptionConflictError(
"conflicting option string(s): %s"
% ", ".join([co
[0] for co
in conflict_opts
]),
elif handler
== "resolve":
for (opt
, c_option
) in conflict_opts
:
c_option
._long
_opts
.remove(opt
)
c_option
._short
_opts
.remove(opt
)
if not (c_option
._short
_opts
or c_option
._long
_opts
):
c_option
.container
.option_list
.remove(c_option
)
def add_option(self
, *args
, **kwargs
):
add_option(opt_str, ..., kwarg=val, ...)
if type(args
[0]) is types
.StringType
:
option
= self
.option_class(*args
, **kwargs
)
elif len(args
) == 1 and not kwargs
:
if not isinstance(option
, Option
):
raise TypeError, "not an Option instance: %r" % option
raise TypeError, "invalid arguments"
self
._check
_conflict
(option
)
self
.option_list
.append(option
)
for opt
in option
._short
_opts
:
self
._short
_opt
[opt
] = option
for opt
in option
._long
_opts
:
self
._long
_opt
[opt
] = option
if option
.dest
is not None: # option has a dest, we need a default
if option
.default
is not NO_DEFAULT
:
self
.defaults
[option
.dest
] = option
.default
elif not self
.defaults
.has_key(option
.dest
):
self
.defaults
[option
.dest
] = None
def add_options(self
, option_list
):
for option
in option_list
:
# -- Option query/removal methods ----------------------------------
def get_option(self
, opt_str
):
return (self
._short
_opt
.get(opt_str
) or
self
._long
_opt
.get(opt_str
))
def has_option(self
, opt_str
):
return (self
._short
_opt
.has_key(opt_str
) or
self
._long
_opt
.has_key(opt_str
))
def remove_option(self
, opt_str
):
option
= self
._short
_opt
.get(opt_str
)
option
= self
._long
_opt
.get(opt_str
)
raise ValueError("no such option %r" % opt_str
)
for opt
in option
._short
_opts
:
for opt
in option
._long
_opts
:
option
.container
.option_list
.remove(option
)
# -- Help-formatting methods ---------------------------------------
def format_option_help(self
, formatter
):
for option
in self
.option_list
:
if not option
.help is SUPPRESS_HELP
:
result
.append(formatter
.format_option(option
))
def format_description(self
, formatter
):
return formatter
.format_description(self
.get_description())
def format_help(self
, formatter
):
result
.append(self
.format_description(formatter
))
result
.append(self
.format_option_help(formatter
))
class OptionGroup (OptionContainer
):
def __init__(self
, parser
, title
, description
=None):
OptionContainer
.__init
__(
self
, parser
.option_class
, parser
.conflict_handler
, description
)
def _create_option_list(self
):
self
._share
_option
_mappings
(self
.parser
)
def set_title(self
, title
):
# -- Help-formatting methods ---------------------------------------
def format_help(self
, formatter
):
result
= formatter
.format_heading(self
.title
)
result
+= OptionContainer
.format_help(self
, formatter
)
class OptionParser (OptionContainer
):
standard_option_list : [Option]
list of standard options that will be accepted by all instances
of this parser class (intended to be overridden by subclasses).
a usage string for your program. Before it is displayed
to the user, "%prog" will be expanded to the name of
your program (self.prog or os.path.basename(sys.argv[0])).
the name of the current program (to override
os.path.basename(sys.argv[0])).
option_groups : [OptionGroup]
list of option groups in this parser (option groups are
irrelevant for parsing the command-line, but very useful
allow_interspersed_args : bool = true
if true, positional arguments may be interspersed with options.
Assuming -a and -b each take a single argument, the command-line
will be interpreted the same as
-ablah -bboo -- foo bar baz
If this flag were false, that command line would be interpreted as
-ablah -- foo bar -bboo baz
-- ie. we stop processing options as soon as we see the first
non-option argument. (This is the tradition followed by
Python's getopt module, Perl's Getopt::Std, and other argument-
parsing libraries, but it is generally annoying to users.)
process_default_values : bool = true
if true, option default values are processed similarly to option
values from the command line: that is, they are passed to the
type-checking function for the option's type (as long as the
default value is a string). (This really only matters if you
have defined custom types; see SF bug #955889.) Set it to false
to restore the behaviour of Optik 1.4.1 and earlier.
the argument list currently being parsed. Only set when
parse_args() is active, and continually trimmed down as
we consume arguments. Mainly there for the benefit of
the list of leftover arguments that we have skipped while
parsing options. If allow_interspersed_args is false, this
the set of option values currently being accumulated. Only
set when parse_args() is active. Also mainly for callbacks.
Because of the 'rargs', 'largs', and 'values' attributes,
OptionParser is not thread-safe. If, for some perverse reason, you
need to parse command-line arguments simultaneously in different
threads, use different OptionParser instances.
standard_option_list
= []
conflict_handler
="error",
OptionContainer
.__init
__(
self
, option_class
, conflict_handler
, description
)
self
.allow_interspersed_args
= True
self
.process_default_values
= True
formatter
= IndentedHelpFormatter()
self
.formatter
= formatter
self
.formatter
.set_parser(self
)
# Populate the option list; initial sources are the
# standard_option_list class attribute, the 'option_list'
# argument, and (if applicable) the _add_version_option() and
# _add_help_option() methods.
self
._populate
_option
_list
(option_list
,
add_help
=add_help_option
)
self
._init
_parsing
_state
()
# -- Private methods -----------------------------------------------
# (used by our or OptionContainer's constructor)
def _create_option_list(self
):
self
._create
_option
_mappings
()
def _add_help_option(self
):
self
.add_option("-h", "--help",
help=_("show this help message and exit"))
def _add_version_option(self
):
self
.add_option("--version",
help=_("show program's version number and exit"))
def _populate_option_list(self
, option_list
, add_help
=True):
if self
.standard_option_list
:
self
.add_options(self
.standard_option_list
)
self
.add_options(option_list
)
self
._add
_version
_option
()
def _init_parsing_state(self
):
# These are set in parse_args() for the convenience of callbacks.
# -- Simple modifier methods ---------------------------------------
def set_usage(self
, usage
):
self
.usage
= _("%prog [options]")
elif usage
is SUPPRESS_USAGE
:
# For backwards compatibility with Optik 1.3 and earlier.
elif usage
.startswith("usage:" + " "):
def enable_interspersed_args(self
):
self
.allow_interspersed_args
= True
def disable_interspersed_args(self
):
self
.allow_interspersed_args
= False
def set_process_default_values(self
, process
):
self
.process_default_values
= process
def set_default(self
, dest
, value
):
self
.defaults
[dest
] = value
def set_defaults(self
, **kwargs
):
self
.defaults
.update(kwargs
)
def _get_all_options(self
):
options
= self
.option_list
[:]
for group
in self
.option_groups
:
options
.extend(group
.option_list
)
def get_default_values(self
):
if not self
.process_default_values
:
# Old, pre-Optik 1.5 behaviour.
return Values(self
.defaults
)
defaults
= self
.defaults
.copy()
for option
in self
._get
_all
_options
():
default
= defaults
.get(option
.dest
)
if isinstance(default
, basestring
):
opt_str
= option
.get_opt_string()
defaults
[option
.dest
] = option
.check_value(opt_str
, default
)
# -- OptionGroup methods -------------------------------------------
def add_option_group(self
, *args
, **kwargs
):
# XXX lots of overlap with OptionContainer.add_option()
if type(args
[0]) is types
.StringType
:
group
= OptionGroup(self
, *args
, **kwargs
)
elif len(args
) == 1 and not kwargs
:
if not isinstance(group
, OptionGroup
):
raise TypeError, "not an OptionGroup instance: %r" % group
if group
.parser
is not self
:
raise ValueError, "invalid OptionGroup (wrong parser)"
raise TypeError, "invalid arguments"
self
.option_groups
.append(group
)
def get_option_group(self
, opt_str
):
option
= (self
._short
_opt
.get(opt_str
) or
self
._long
_opt
.get(opt_str
))
if option
and option
.container
is not self
:
# -- Option-parsing methods ----------------------------------------
def _get_args(self
, args
):
return args
[:] # don't modify caller's list
def parse_args(self
, args
=None, values
=None):
parse_args(args : [string] = sys.argv[1:],
-> (values : Values, args : [string])
Parse the command-line options found in 'args' (default:
sys.argv[1:]). Any errors result in a call to 'error()', which
by default prints the usage message to stderr and calls
sys.exit() with an error message. On success returns a pair
(values, args) where 'values' is an Values instance (with all
your option values) and 'args' is the list of arguments left
over after parsing options.
rargs
= self
._get
_args
(args
)
values
= self
.get_default_values()
# Store the halves of the argument list as attributes for the
# convenience of callbacks:
# the rest of the command-line (the "r" stands for
# "remaining" or "right-hand")
# the leftover arguments -- ie. what's left after removing
# options and their arguments (the "l" stands for "leftover"
stop
= self
._process
_args
(largs
, rargs
, values
)
except (BadOptionError
, OptionValueError
), err
:
return self
.check_values(values
, args
)
def check_values(self
, values
, args
):
check_values(values : Values, args : [string])
-> (values : Values, args : [string])
Check that the supplied option values and leftover arguments are
valid. Returns the option values and leftover arguments
(possibly adjusted, possibly completely new -- whatever you
like). Default implementation just returns the passed-in
values; subclasses may override as desired.
def _process_args(self
, largs
, rargs
, values
):
"""_process_args(largs : [string],
Process command-line arguments and populate 'values', consuming
options and arguments from 'rargs'. If 'allow_interspersed_args' is
false, stop at the first non-option argument. If true, accumulate any
interspersed non-option arguments in 'largs'.
# We handle bare "--" explicitly, and bare "-" is handled by the
# standard arg handler since the short arg case ensures that the
# len of the opt string is greater than 1.
# process a single long option (possibly with value(s))
self
._process
_long
_opt
(rargs
, values
)
elif arg
[:1] == "-" and len(arg
) > 1:
# process a cluster of short options (possibly with
# value(s) for the last one only)
self
._process
_short
_opts
(rargs
, values
)
elif self
.allow_interspersed_args
:
return # stop now, leave this arg in rargs
# Say this is the original argument list:
# [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
# (we are about to process arg(i)).
# Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
# [arg0, ..., arg(i-1)] (any options and their arguments will have
# been removed from largs).
# The while loop will usually consume 1 or more arguments per pass.
# If it consumes 1 (eg. arg is an option that takes no arguments),
# then after _process_arg() is done the situation is:
# largs = subset of [arg0, ..., arg(i)]
# rargs = [arg(i+1), ..., arg(N-1)]
# If allow_interspersed_args is false, largs will always be
# *empty* -- still a subset of [arg0, ..., arg(i-1)], but
# not a very interesting subset!
def _match_long_opt(self
, opt
):
"""_match_long_opt(opt : string) -> string
Determine which long option string 'opt' matches, ie. which one
it is an unambiguous abbrevation for. Raises BadOptionError if
'opt' doesn't unambiguously match any long option string.
return _match_abbrev(opt
, self
._long
_opt
)
def _process_long_opt(self
, rargs
, values
):
# Value explicitly attached to arg? Pretend it's the next
(opt
, next_arg
) = arg
.split("=", 1)
rargs
.insert(0, next_arg
)
had_explicit_value
= True
had_explicit_value
= False
opt
= self
._match
_long
_opt
(opt
)
option
= self
._long
_opt
[opt
]
self
.error(_("%s option requires an argument") % opt
)
self
.error(_("%s option requires %d arguments")
value
= tuple(rargs
[0:nargs
])
self
.error(_("%s option does not take a value") % opt
)
option
.process(opt
, value
, values
, self
)
def _process_short_opts(self
, rargs
, values
):
option
= self
._short
_opt
.get(opt
)
i
+= 1 # we have consumed a character
self
.error(_("no such option: %s") % opt
)
# Any characters left in arg? Pretend they're the
# next arg, and stop consuming characters of arg.
self
.error(_("%s option requires an argument") % opt
)
self
.error(_("%s option requires %d arguments")
value
= tuple(rargs
[0:nargs
])
else: # option doesn't take a value
option
.process(opt
, value
, values
, self
)
# -- Feedback methods ----------------------------------------------
return os
.path
.basename(sys
.argv
[0])
def expand_prog_name(self
, s
):
return s
.replace("%prog", self
.get_prog_name())
def get_description(self
):
return self
.expand_prog_name(self
.description
)
def exit(self
, status
=0, msg
=None):
Print a usage message incorporating 'msg' to stderr and exit.
If you override this in a subclass, it should not return -- it
should either exit or raise an exception.
self
.print_usage(sys
.stderr
)
self
.exit(2, "%s: error: %s\n" % (self
.get_prog_name(), msg
))
return self
.formatter
.format_usage(
self
.expand_prog_name(self
.usage
))
def print_usage(self
, file=None):
"""print_usage(file : file = stdout)
Print the usage message for the current program (self.usage) to
'file' (default stdout). Any occurence of the string "%prog" in
self.usage is replaced with the name of the current program
(basename of sys.argv[0]). Does nothing if self.usage is empty
print >>file, self
.get_usage()
return self
.expand_prog_name(self
.version
)
def print_version(self
, file=None):
"""print_version(file : file = stdout)
Print the version message for this program (self.version) to
'file' (default stdout). As with print_usage(), any occurence
of "%prog" in self.version is replaced by the current program's
name. Does nothing if self.version is empty or undefined.
print >>file, self
.get_version()
def format_option_help(self
, formatter
=None):
formatter
= self
.formatter
formatter
.store_option_strings(self
)
result
.append(formatter
.format_heading(_("options")))
result
.append(OptionContainer
.format_option_help(self
, formatter
))
for group
in self
.option_groups
:
result
.append(group
.format_help(formatter
))
# Drop the last "\n", or the header if no options or option groups:
return "".join(result
[:-1])
def format_help(self
, formatter
=None):
formatter
= self
.formatter
result
.append(self
.get_usage() + "\n")
result
.append(self
.format_description(formatter
) + "\n")
result
.append(self
.format_option_help(formatter
))
def print_help(self
, file=None):
"""print_help(file : file = stdout)
Print an extended help message, listing all options and any
help text provided with them, to 'file' (default stdout).
file.write(self
.format_help())
def _match_abbrev(s
, wordmap
):
"""_match_abbrev(s : string, wordmap : {string : Option}) -> string
Return the string key in 'wordmap' for which 's' is an unambiguous
abbreviation. If 's' is found to be ambiguous or doesn't match any of
'words', raise BadOptionError.
# Is there an exact match?
# Isolate all words with s as a prefix.
possibilities
= [word
for word
in wordmap
.keys()
# No exact match, so there had better be just one possibility.
if len(possibilities
) == 1:
raise BadOptionError(_("no such option: %s") % s
)
# More than one possible completion: ambiguous prefix.
raise BadOptionError(_("ambiguous option: %s (%s?)")
% (s
, ", ".join(possibilities
)))
# Some day, there might be many Option classes. As of Optik 1.3, the
# preferred way to instantiate Options is indirectly, via make_option(),
# which will become a factory function when there are many Option