1 """optparse - a powerful, extensible, and easy-to-use option parser.
3 By Greg Ward <gward@python.net>
5 Originally distributed as Optik; see http://optik.sourceforge.net/ .
7 If you have problems with this module, please do not file bugs,
8 patches, or feature requests with Python; instead, use Optik's
9 SourceForge project page:
10 http://sourceforge.net/projects/optik
12 For support, use the optik-users@lists.sourceforge.net mailing list
13 (http://lists.sourceforge.net/lists/listinfo/optik-users).
16 # Python developers: please do not make changes to this file, since
17 # it is automatically generated from the Optik source code.
29 'IndentedHelpFormatter',
30 'TitledHelpFormatter',
33 'OptionConflictError',
38 Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
39 Copyright (c) 2002-2006 Python Software Foundation. All rights reserved.
41 Redistribution and use in source and binary forms, with or without
42 modification, are permitted provided that the following conditions are
45 * Redistributions of source code must retain the above copyright
46 notice, this list of conditions and the following disclaimer.
48 * Redistributions in binary form must reproduce the above copyright
49 notice, this list of conditions and the following disclaimer in the
50 documentation and/or other materials provided with the distribution.
52 * Neither the name of the author nor the names of its
53 contributors may be used to endorse or promote products derived from
54 this software without specific prior written permission.
56 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
57 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
59 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
60 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
61 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
62 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
63 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
64 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
65 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
66 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
74 return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
78 sys.getdefaultencoding
79 except AttributeError:
80 def fake_getdefaultencoding():
82 sys.getdefaultencoding = fake_getdefaultencoding
86 except AttributeError:
87 def encode_wrapper(s, encoding, replacement):
90 def encode_wrapper(s, encoding, replacement):
91 return s.encode(encoding, replacement)
94 # This file was generated from:
95 # Id: option_parser.py 527 2006-07-23 15:21:30Z greg
96 # Id: option.py 522 2006-06-11 16:22:03Z gward
97 # Id: help.py 527 2006-07-23 15:21:30Z greg
98 # Id: errors.py 509 2006-04-20 00:58:24Z gward
101 from gettext import gettext
103 def gettext(message):
108 class OptParseError (Exception):
109 def __init__(self, msg):
116 class OptionError (OptParseError):
118 Raised if an Option instance is created with invalid or
119 inconsistent arguments.
122 def __init__(self, msg, option):
124 self.option_id = str(option)
128 return "option %s: %s" % (self.option_id, self.msg)
132 class OptionConflictError (OptionError):
134 Raised if conflicting options are added to an OptionParser.
137 class OptionValueError (OptParseError):
139 Raised if an invalid option value is encountered on the command
143 class BadOptionError (OptParseError):
145 Raised if an invalid option is seen on the command line.
147 def __init__(self, opt_str):
148 self.opt_str = opt_str
151 return _("no such option: %s") % self.opt_str
153 class AmbiguousOptionError (BadOptionError):
155 Raised if an ambiguous option is seen on the command line.
157 def __init__(self, opt_str, possibilities):
158 BadOptionError.__init__(self, opt_str)
159 self.possibilities = possibilities
162 return (_("ambiguous option: %s (%s?)")
163 % (self.opt_str, ", ".join(self.possibilities)))
169 Abstract base class for formatting option help. OptionParser
170 instances should use one of the HelpFormatter subclasses for
171 formatting help; by default IndentedHelpFormatter is used.
174 parser : OptionParser
175 the controlling OptionParser instance
176 indent_increment : int
177 the number of columns to indent per nesting level
178 max_help_position : int
179 the maximum starting column for option help text
181 the calculated starting column for option help text;
182 initially the same as the maximum
184 total number of columns for output (pass None to constructor for
185 this value to be taken from the $COLUMNS environment variable)
187 current indentation level
189 current indentation level (in columns)
191 number of columns available for option help text (calculated)
193 text to replace with each option's default value, "%default"
194 by default. Set to false value to disable default value expansion.
195 option_strings : { Option : str }
196 maps Option instances to the snippet of help text explaining
197 the syntax of that option, e.g. "-h, --help" or
198 "-fFILE, --file=FILE"
200 format string controlling how short options with values are
201 printed in help text. Must be either "%s%s" ("-fFILE") or
202 "%s %s" ("-f FILE"), because those are the two syntaxes that
205 similar but for long options; must be either "%s %s" ("--file FILE")
206 or "%s=%s" ("--file=FILE").
209 NO_DEFAULT_VALUE = "none"
217 self.indent_increment = indent_increment
218 self.help_position = self.max_help_position = max_help_position
221 width = int(os.environ['COLUMNS'])
222 except (KeyError, ValueError):
226 self.current_indent = 0
228 self.help_width = None # computed later
229 self.short_first = short_first
230 self.default_tag = "%default"
231 self.option_strings = {}
232 self._short_opt_fmt = "%s %s"
233 self._long_opt_fmt = "%s=%s"
235 def set_parser(self, parser):
238 def set_short_opt_delimiter(self, delim):
239 if delim not in ("", " "):
241 "invalid metavar delimiter for short options: %r" % delim)
242 self._short_opt_fmt = "%s" + delim + "%s"
244 def set_long_opt_delimiter(self, delim):
245 if delim not in ("=", " "):
247 "invalid metavar delimiter for long options: %r" % delim)
248 self._long_opt_fmt = "%s" + delim + "%s"
251 self.current_indent = self.current_indent + self.indent_increment
252 self.level = self.level + 1
255 self.current_indent = self.current_indent - self.indent_increment
256 assert self.current_indent >= 0, "Indent decreased below 0."
257 self.level = self.level - 1
259 def format_usage(self, usage):
260 raise NotImplementedError("subclasses must implement")
262 def format_heading(self, heading):
263 raise NotImplementedError("subclasses must implement")
265 def _format_text(self, text):
267 Format a paragraph of free-form text for inclusion in the
268 help output at the current indentation level.
270 text_width = self.width - self.current_indent
271 indent = " "*self.current_indent
272 return textwrap.fill(text,
274 initial_indent=indent,
275 subsequent_indent=indent)
277 def format_description(self, description):
279 return self._format_text(description) + "\n"
283 def format_epilog(self, epilog):
285 return "\n" + self._format_text(epilog) + "\n"
290 def expand_default(self, option):
291 if self.parser is None or not self.default_tag:
294 default_value = self.parser.defaults.get(option.dest)
295 if default_value is NO_DEFAULT or default_value is None:
296 default_value = self.NO_DEFAULT_VALUE
298 return option.help.replace(self.default_tag, str(default_value))
300 def format_option(self, option):
301 # The help for each option consists of two parts:
302 # * the opt strings and metavars
303 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
304 # * the user-supplied help string
305 # eg. ("turn on expert mode", "read data from FILENAME")
307 # If possible, we write both of these on the same line:
308 # -x turn on expert mode
310 # But if the opt string list is too long, we put the help
311 # string on a second line, indented to the same column it would
312 # start in if it fit on the first line.
313 # -fFILENAME, --file=FILENAME
314 # read data from FILENAME
316 opts = self.option_strings[option]
317 opt_width = self.help_position - self.current_indent - 2
318 if len(opts) > opt_width:
319 opts = "%*s%s\n" % (self.current_indent, "", opts)
320 indent_first = self.help_position
321 else: # start help on same line as opts
322 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
326 help_text = self.expand_default(option)
327 help_lines = textwrap.wrap(help_text, self.help_width)
328 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
329 for line in help_lines[1:]:
330 result.append("%*s%s\n" % (self.help_position, "", line))
331 elif opts[-1] != "\n":
333 return "".join(result)
335 def store_option_strings(self, parser):
338 for opt in parser.option_list:
339 strings = self.format_option_strings(opt)
340 self.option_strings[opt] = strings
341 max_len = max(max_len, len(strings) + self.current_indent)
343 for group in parser.option_groups:
344 for opt in group.option_list:
345 strings = self.format_option_strings(opt)
346 self.option_strings[opt] = strings
347 max_len = max(max_len, len(strings) + self.current_indent)
350 self.help_position = min(max_len + 2, self.max_help_position)
351 self.help_width = self.width - self.help_position
353 def format_option_strings(self, option):
354 """Return a comma-separated list of option strings & metavariables."""
355 if option.takes_value():
356 metavar = option.metavar or option.dest.upper()
358 for sopt in option._short_opts:
359 short_opts.append(self._short_opt_fmt % (sopt, metavar))
361 for lopt in option._long_opts:
362 long_opts.append(self._long_opt_fmt % (lopt, metavar))
364 short_opts = option._short_opts
365 long_opts = option._long_opts
368 opts = short_opts + long_opts
370 opts = long_opts + short_opts
372 return ", ".join(opts)
374 class IndentedHelpFormatter (HelpFormatter):
375 """Format help with indented section bodies.
380 max_help_position=24,
383 HelpFormatter.__init__(
384 self, indent_increment, max_help_position, width, short_first)
386 def format_usage(self, usage):
387 return _("Usage: %s\n") % usage
389 def format_heading(self, heading):
390 return "%*s%s:\n" % (self.current_indent, "", heading)
393 class TitledHelpFormatter (HelpFormatter):
394 """Format help with underlined section headers.
399 max_help_position=24,
402 HelpFormatter.__init__ (
403 self, indent_increment, max_help_position, width, short_first)
405 def format_usage(self, usage):
406 return "%s %s\n" % (self.format_heading(_("Usage")), usage)
408 def format_heading(self, heading):
409 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
412 def _parse_num(val, type):
413 if val[:2].lower() == "0x": # hexadecimal
415 elif val[:2].lower() == "0b": # binary
417 val = val[2:] or "0" # have to remove "0b" prefix
418 elif val[:1] == "0": # octal
423 return type(val, radix)
426 return _parse_num(val, int)
428 def _parse_long(val):
429 return _parse_num(val, long)
434 # Python 1.5.2 doesn't allow a radix value to be passed to int().
440 # Python 1.5.2 doesn't allow a radix value to be passed to long().
443 _builtin_cvt = { "int" : (_parse_int, _("integer")),
444 "long" : (_parse_long, _("long integer")),
445 "float" : (float, _("floating-point")),
446 "complex" : (complex, _("complex")) }
448 def check_builtin(option, opt, value):
449 (cvt, what) = _builtin_cvt[option.type]
453 raise OptionValueError(
454 _("option %s: invalid %s value: %r") % (opt, what, value))
456 def check_choice(option, opt, value):
457 if value in option.choices:
460 choices = ", ".join(map(repr, option.choices))
461 raise OptionValueError(
462 _("option %s: invalid choice: %r (choose from %s)")
463 % (opt, value, choices))
465 # Not supplying a default is different from a default of None,
466 # so we need an explicit "not supplied" value.
467 NO_DEFAULT = ("NO", "DEFAULT")
473 _short_opts : [string]
474 _long_opts : [string]
484 callback_args : (any*)
485 callback_kwargs : { string : any }
490 # The list of instance attributes that may be set through
491 # keyword args to the constructor.
505 # The set of actions allowed by option parsers. Explicitly listed
506 # here so the constructor can validate its arguments.
518 # The set of actions that involve storing a value somewhere;
519 # also listed just for constructor argument validation. (If
520 # the action is one of these, there must be a destination.)
521 STORE_ACTIONS = ("store",
529 # The set of actions for which it makes sense to supply a value
530 # type, ie. which may consume an argument from the command line.
531 TYPED_ACTIONS = ("store",
535 # The set of actions which *require* a value type, ie. that
536 # always consume an argument from the command line.
537 ALWAYS_TYPED_ACTIONS = ("store",
540 # The set of actions which take a 'const' attribute.
541 CONST_ACTIONS = ("store_const",
544 # The set of known types for option parsers. Again, listed here for
545 # constructor argument validation.
546 TYPES = ("string", "int", "long", "float", "complex", "choice")
548 # Dictionary of argument checking functions, which convert and
549 # validate option arguments according to the option type.
551 # Signature of checking functions is:
552 # check(option : Option, opt : string, value : string) -> any
554 # option is the Option instance calling the checker
555 # opt is the actual option seen on the command-line
556 # (eg. "-a", "--file")
557 # value is the option argument seen on the command-line
559 # The return value should be in the appropriate Python type
560 # for option.type -- eg. an integer if option.type == "int".
562 # If no checker is defined for a type, arguments will be
563 # unchecked and remain strings.
564 TYPE_CHECKER = { "int" : check_builtin,
565 "long" : check_builtin,
566 "float" : check_builtin,
567 "complex": check_builtin,
568 "choice" : check_choice,
572 # CHECK_METHODS is a list of unbound method objects; they are called
573 # by the constructor, in order, after all attributes are
574 # initialized. The list is created and filled in later, after all
575 # the methods are actually defined. (I just put it here because I
576 # like to define and document all class attributes in the same
577 # place.) Subclasses that add another _check_*() method should
578 # define their own CHECK_METHODS list that adds their check method
579 # to those from this class.
583 # -- Constructor/initialization methods ----------------------------
585 def __init__(self, *opts, **attrs):
586 # Set _short_opts, _long_opts attrs from 'opts' tuple.
587 # Have to be set now, in case no option strings are supplied.
588 self._short_opts = []
590 opts = self._check_opt_strings(opts)
591 self._set_opt_strings(opts)
593 # Set all other attrs (action, type, etc.) from 'attrs' dict
594 self._set_attrs(attrs)
596 # Check all the attributes we just set. There are lots of
597 # complicated interdependencies, but luckily they can be farmed
598 # out to the _check_*() methods listed in CHECK_METHODS -- which
599 # could be handy for subclasses! The one thing these all share
600 # is that they raise OptionError if they discover a problem.
601 for checker in self.CHECK_METHODS:
604 def _check_opt_strings(self, opts):
605 # Filter out None because early versions of Optik had exactly
606 # one short option and one long option, either of which
608 opts = [_f for _f in opts if _f]
610 raise TypeError("at least one option string must be supplied")
613 def _set_opt_strings(self, opts):
617 "invalid option string %r: "
618 "must be at least two characters long" % opt, self)
620 if not (opt[0] == "-" and opt[1] != "-"):
622 "invalid short option string %r: "
623 "must be of the form -x, (x any non-dash char)" % opt,
625 self._short_opts.append(opt)
627 if not (opt[0:2] == "--" and opt[2] != "-"):
629 "invalid long option string %r: "
630 "must start with --, followed by non-dash" % opt,
632 self._long_opts.append(opt)
634 def _set_attrs(self, attrs):
635 for attr in self.ATTRS:
637 setattr(self, attr, attrs[attr])
640 if attr == 'default':
641 setattr(self, attr, NO_DEFAULT)
643 setattr(self, attr, None)
645 attrs = sorted(attrs.keys())
647 "invalid keyword arguments: %s" % ", ".join(attrs),
651 # -- Constructor validation methods --------------------------------
653 def _check_action(self):
654 if self.action is None:
655 self.action = "store"
656 elif self.action not in self.ACTIONS:
657 raise OptionError("invalid action: %r" % self.action, self)
659 def _check_type(self):
660 if self.type is None:
661 if self.action in self.ALWAYS_TYPED_ACTIONS:
662 if self.choices is not None:
663 # The "choices" attribute implies "choice" type.
666 # No type given? "string" is the most sensible default.
669 # Allow type objects or builtin type conversion functions
670 # (int, str, etc.) as an alternative to their names.
671 if isinstance(self.type, type):
672 self.type = self.type.__name__
674 if self.type == "str":
677 if self.type not in self.TYPES:
678 raise OptionError("invalid option type: %r" % self.type, self)
679 if self.action not in self.TYPED_ACTIONS:
681 "must not supply a type for action %r" % self.action, self)
683 def _check_choice(self):
684 if self.type == "choice":
685 if self.choices is None:
687 "must supply a list of choices for type 'choice'", self)
688 elif type(self.choices) not in (tuple, list):
690 "choices must be a list of strings ('%s' supplied)"
691 % str(type(self.choices)).split("'")[1], self)
692 elif self.choices is not None:
694 "must not supply choices for type %r" % self.type, self)
696 def _check_dest(self):
697 # No destination given, and we need one for this action. The
698 # self.type check is for callbacks that take a value.
699 takes_value = (self.action in self.STORE_ACTIONS or
700 self.type is not None)
701 if self.dest is None and takes_value:
703 # Glean a destination from the first long option string,
704 # or from the first short option string if no long options.
706 # eg. "--foo-bar" -> "foo_bar"
707 self.dest = self._long_opts[0][2:].replace('-', '_')
709 self.dest = self._short_opts[0][1]
711 def _check_const(self):
712 if self.action not in self.CONST_ACTIONS and self.const is not None:
714 "'const' must not be supplied for action %r" % self.action,
717 def _check_nargs(self):
718 if self.action in self.TYPED_ACTIONS:
719 if self.nargs is None:
721 elif self.nargs is not None:
723 "'nargs' must not be supplied for action %r" % self.action,
726 def _check_callback(self):
727 if self.action == "callback":
728 if not callable(self.callback):
730 "callback not callable: %r" % self.callback, self)
731 if (self.callback_args is not None and
732 not isinstance(self.callback_args, tuple)):
734 "callback_args, if supplied, must be a tuple: not %r"
735 % self.callback_args, self)
736 if (self.callback_kwargs is not None and
737 not isinstance(self.callback_kwargs, dict)):
739 "callback_kwargs, if supplied, must be a dict: not %r"
740 % self.callback_kwargs, self)
742 if self.callback is not None:
744 "callback supplied (%r) for non-callback option"
745 % self.callback, self)
746 if self.callback_args is not None:
748 "callback_args supplied for non-callback option", self)
749 if self.callback_kwargs is not None:
751 "callback_kwargs supplied for non-callback option", self)
754 CHECK_METHODS = [_check_action,
763 # -- Miscellaneous methods -----------------------------------------
766 return "/".join(self._short_opts + self._long_opts)
770 def takes_value(self):
771 return self.type is not None
773 def get_opt_string(self):
775 return self._long_opts[0]
777 return self._short_opts[0]
780 # -- Processing methods --------------------------------------------
782 def check_value(self, opt, value):
783 checker = self.TYPE_CHECKER.get(self.type)
787 return checker(self, opt, value)
789 def convert_value(self, opt, value):
790 if value is not None:
792 return self.check_value(opt, value)
794 return tuple([self.check_value(opt, v) for v in value])
796 def process(self, opt, value, values, parser):
798 # First, convert the value(s) to the right type. Howl if any
799 # value(s) are bogus.
800 value = self.convert_value(opt, value)
802 # And then take whatever action is expected of us.
803 # This is a separate method to make life easier for
804 # subclasses to add new actions.
805 return self.take_action(
806 self.action, self.dest, opt, value, values, parser)
808 def take_action(self, action, dest, opt, value, values, parser):
809 if action == "store":
810 setattr(values, dest, value)
811 elif action == "store_const":
812 setattr(values, dest, self.const)
813 elif action == "store_true":
814 setattr(values, dest, True)
815 elif action == "store_false":
816 setattr(values, dest, False)
817 elif action == "append":
818 values.ensure_value(dest, []).append(value)
819 elif action == "append_const":
820 values.ensure_value(dest, []).append(self.const)
821 elif action == "count":
822 setattr(values, dest, values.ensure_value(dest, 0) + 1)
823 elif action == "callback":
824 args = self.callback_args or ()
825 kwargs = self.callback_kwargs or {}
826 self.callback(self, opt, value, parser, *args, **kwargs)
827 elif action == "help":
830 elif action == "version":
831 parser.print_version()
834 raise RuntimeError("unknown action %r" % self.action)
841 SUPPRESS_HELP = "SUPPRESS"+"HELP"
842 SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
844 # For compatibility with Python 2.2
848 (True, False) = (1, 0)
853 return isinstance(x, str)
856 return isinstance(x, str) or isinstance(x, unicode)
860 def __init__(self, defaults=None):
862 for (attr, val) in defaults.items():
863 setattr(self, attr, val)
866 return str(self.__dict__)
870 def __cmp__(self, other):
871 if isinstance(other, Values):
872 return cmp(self.__dict__, other.__dict__)
873 elif isinstance(other, dict):
874 return cmp(self.__dict__, other)
878 def _update_careful(self, dict):
880 Update the option values from an arbitrary dictionary, but only
881 use keys from dict that already have a corresponding attribute
882 in self. Any keys in dict without a corresponding attribute
883 are silently ignored.
885 for attr in dir(self):
889 setattr(self, attr, dval)
891 def _update_loose(self, dict):
893 Update the option values from an arbitrary dictionary,
894 using all keys from the dictionary regardless of whether
895 they have a corresponding attribute in self or not.
897 self.__dict__.update(dict)
899 def _update(self, dict, mode):
900 if mode == "careful":
901 self._update_careful(dict)
902 elif mode == "loose":
903 self._update_loose(dict)
905 raise ValueError("invalid update mode: %r" % mode)
907 def read_module(self, modname, mode="careful"):
909 mod = sys.modules[modname]
910 self._update(vars(mod), mode)
912 def read_file(self, filename, mode="careful"):
914 exec open(filename, 'rU').read() in vars
915 self._update(vars, mode)
917 def ensure_value(self, attr, value):
918 if not hasattr(self, attr) or getattr(self, attr) is None:
919 setattr(self, attr, value)
920 return getattr(self, attr)
923 class OptionContainer:
929 standard_option_list : [Option]
930 list of standard options that will be accepted by all instances
931 of this parser class (intended to be overridden by subclasses).
934 option_list : [Option]
935 the list of Option objects contained by this OptionContainer
936 _short_opt : { string : Option }
937 dictionary mapping short option strings, eg. "-f" or "-X",
938 to the Option instances that implement them. If an Option
939 has multiple short option strings, it will appears in this
940 dictionary multiple times. [1]
941 _long_opt : { string : Option }
942 dictionary mapping long option strings, eg. "--file" or
943 "--exclude", to the Option instances that implement them.
944 Again, a given Option can occur multiple times in this
946 defaults : { string : any }
947 dictionary mapping option destination names to default
948 values for each destination [1]
950 [1] These mappings are common to (shared by) all components of the
951 controlling OptionParser, where they are initially created.
955 def __init__(self, option_class, conflict_handler, description):
956 # Initialize the option list and related data structures.
957 # This method must be provided by subclasses, and it must
958 # initialize at least the following instance attributes:
959 # option_list, _short_opt, _long_opt, defaults.
960 self._create_option_list()
962 self.option_class = option_class
963 self.set_conflict_handler(conflict_handler)
964 self.set_description(description)
966 def _create_option_mappings(self):
967 # For use by OptionParser constructor -- create the master
968 # option mappings used by this OptionParser and all
969 # OptionGroups that it owns.
970 self._short_opt = {} # single letter -> Option instance
971 self._long_opt = {} # long option -> Option instance
972 self.defaults = {} # maps option dest -> default value
975 def _share_option_mappings(self, parser):
976 # For use by OptionGroup constructor -- use shared option
977 # mappings from the OptionParser that owns this OptionGroup.
978 self._short_opt = parser._short_opt
979 self._long_opt = parser._long_opt
980 self.defaults = parser.defaults
982 def set_conflict_handler(self, handler):
983 if handler not in ("error", "resolve"):
984 raise ValueError("invalid conflict_resolution value %r" % handler)
985 self.conflict_handler = handler
987 def set_description(self, description):
988 self.description = description
990 def get_description(self):
991 return self.description
995 """see OptionParser.destroy()."""
1001 # -- Option-adding methods -----------------------------------------
1003 def _check_conflict(self, option):
1005 for opt in option._short_opts:
1006 if opt in self._short_opt:
1007 conflict_opts.append((opt, self._short_opt[opt]))
1008 for opt in option._long_opts:
1009 if opt in self._long_opt:
1010 conflict_opts.append((opt, self._long_opt[opt]))
1013 handler = self.conflict_handler
1014 if handler == "error":
1015 raise OptionConflictError(
1016 "conflicting option string(s): %s"
1017 % ", ".join([co[0] for co in conflict_opts]),
1019 elif handler == "resolve":
1020 for (opt, c_option) in conflict_opts:
1022 c_option._long_opts.remove(opt)
1023 del self._long_opt[opt]
1025 c_option._short_opts.remove(opt)
1026 del self._short_opt[opt]
1027 if not (c_option._short_opts or c_option._long_opts):
1028 c_option.container.option_list.remove(c_option)
1030 def add_option(self, *args, **kwargs):
1031 """add_option(Option)
1032 add_option(opt_str, ..., kwarg=val, ...)
1034 if isinstance(args[0], str):
1035 option = self.option_class(*args, **kwargs)
1036 elif len(args) == 1 and not kwargs:
1038 if not isinstance(option, Option):
1039 raise TypeError("not an Option instance: %r" % option)
1041 raise TypeError("invalid arguments")
1043 self._check_conflict(option)
1045 self.option_list.append(option)
1046 option.container = self
1047 for opt in option._short_opts:
1048 self._short_opt[opt] = option
1049 for opt in option._long_opts:
1050 self._long_opt[opt] = option
1052 if option.dest is not None: # option has a dest, we need a default
1053 if option.default is not NO_DEFAULT:
1054 self.defaults[option.dest] = option.default
1055 elif option.dest not in self.defaults:
1056 self.defaults[option.dest] = None
1060 def add_options(self, option_list):
1061 for option in option_list:
1062 self.add_option(option)
1064 # -- Option query/removal methods ----------------------------------
1066 def get_option(self, opt_str):
1067 return (self._short_opt.get(opt_str) or
1068 self._long_opt.get(opt_str))
1070 def has_option(self, opt_str):
1071 return (opt_str in self._short_opt or
1072 opt_str in self._long_opt)
1074 def remove_option(self, opt_str):
1075 option = self._short_opt.get(opt_str)
1077 option = self._long_opt.get(opt_str)
1079 raise ValueError("no such option %r" % opt_str)
1081 for opt in option._short_opts:
1082 del self._short_opt[opt]
1083 for opt in option._long_opts:
1084 del self._long_opt[opt]
1085 option.container.option_list.remove(option)
1088 # -- Help-formatting methods ---------------------------------------
1090 def format_option_help(self, formatter):
1091 if not self.option_list:
1094 for option in self.option_list:
1095 if not option.help is SUPPRESS_HELP:
1096 result.append(formatter.format_option(option))
1097 return "".join(result)
1099 def format_description(self, formatter):
1100 return formatter.format_description(self.get_description())
1102 def format_help(self, formatter):
1104 if self.description:
1105 result.append(self.format_description(formatter))
1106 if self.option_list:
1107 result.append(self.format_option_help(formatter))
1108 return "\n".join(result)
1111 class OptionGroup (OptionContainer):
1113 def __init__(self, parser, title, description=None):
1114 self.parser = parser
1115 OptionContainer.__init__(
1116 self, parser.option_class, parser.conflict_handler, description)
1119 def _create_option_list(self):
1120 self.option_list = []
1121 self._share_option_mappings(self.parser)
1123 def set_title(self, title):
1127 """see OptionParser.destroy()."""
1128 OptionContainer.destroy(self)
1129 del self.option_list
1131 # -- Help-formatting methods ---------------------------------------
1133 def format_help(self, formatter):
1134 result = formatter.format_heading(self.title)
1136 result = result + OptionContainer.format_help(self, formatter)
1141 class OptionParser (OptionContainer):
1145 standard_option_list : [Option]
1146 list of standard options that will be accepted by all instances
1147 of this parser class (intended to be overridden by subclasses).
1149 Instance attributes:
1151 a usage string for your program. Before it is displayed
1152 to the user, "%prog" will be expanded to the name of
1153 your program (self.prog or os.path.basename(sys.argv[0])).
1155 the name of the current program (to override
1156 os.path.basename(sys.argv[0])).
1158 paragraph of help text to print after option help
1160 option_groups : [OptionGroup]
1161 list of option groups in this parser (option groups are
1162 irrelevant for parsing the command-line, but very useful
1163 for generating help)
1165 allow_interspersed_args : bool = true
1166 if true, positional arguments may be interspersed with options.
1167 Assuming -a and -b each take a single argument, the command-line
1168 -ablah foo bar -bboo baz
1169 will be interpreted the same as
1170 -ablah -bboo -- foo bar baz
1171 If this flag were false, that command line would be interpreted as
1172 -ablah -- foo bar -bboo baz
1173 -- ie. we stop processing options as soon as we see the first
1174 non-option argument. (This is the tradition followed by
1175 Python's getopt module, Perl's Getopt::Std, and other argument-
1176 parsing libraries, but it is generally annoying to users.)
1178 process_default_values : bool = true
1179 if true, option default values are processed similarly to option
1180 values from the command line: that is, they are passed to the
1181 type-checking function for the option's type (as long as the
1182 default value is a string). (This really only matters if you
1183 have defined custom types; see SF bug #955889.) Set it to false
1184 to restore the behaviour of Optik 1.4.1 and earlier.
1187 the argument list currently being parsed. Only set when
1188 parse_args() is active, and continually trimmed down as
1189 we consume arguments. Mainly there for the benefit of
1192 the list of leftover arguments that we have skipped while
1193 parsing options. If allow_interspersed_args is false, this
1194 list is always empty.
1196 the set of option values currently being accumulated. Only
1197 set when parse_args() is active. Also mainly for callbacks.
1199 Because of the 'rargs', 'largs', and 'values' attributes,
1200 OptionParser is not thread-safe. If, for some perverse reason, you
1201 need to parse command-line arguments simultaneously in different
1202 threads, use different OptionParser instances.
1206 standard_option_list = []
1211 option_class=Option,
1213 conflict_handler="error",
1216 add_help_option=True,
1219 OptionContainer.__init__(
1220 self, option_class, conflict_handler, description)
1221 self.set_usage(usage)
1223 self.version = version
1224 self.allow_interspersed_args = True
1225 self.process_default_values = True
1226 if formatter is None:
1227 formatter = IndentedHelpFormatter()
1228 self.formatter = formatter
1229 self.formatter.set_parser(self)
1230 self.epilog = epilog
1232 # Populate the option list; initial sources are the
1233 # standard_option_list class attribute, the 'option_list'
1234 # argument, and (if applicable) the _add_version_option() and
1235 # _add_help_option() methods.
1236 self._populate_option_list(option_list,
1237 add_help=add_help_option)
1239 self._init_parsing_state()
1244 Declare that you are done with this OptionParser. This cleans up
1245 reference cycles so the OptionParser (and all objects referenced by
1246 it) can be garbage-collected promptly. After calling destroy(), the
1247 OptionParser is unusable.
1249 OptionContainer.destroy(self)
1250 for group in self.option_groups:
1252 del self.option_list
1253 del self.option_groups
1257 # -- Private methods -----------------------------------------------
1258 # (used by our or OptionContainer's constructor)
1260 def _create_option_list(self):
1261 self.option_list = []
1262 self.option_groups = []
1263 self._create_option_mappings()
1265 def _add_help_option(self):
1266 self.add_option("-h", "--help",
1268 help=_("show this help message and exit"))
1270 def _add_version_option(self):
1271 self.add_option("--version",
1273 help=_("show program's version number and exit"))
1275 def _populate_option_list(self, option_list, add_help=True):
1276 if self.standard_option_list:
1277 self.add_options(self.standard_option_list)
1279 self.add_options(option_list)
1281 self._add_version_option()
1283 self._add_help_option()
1285 def _init_parsing_state(self):
1286 # These are set in parse_args() for the convenience of callbacks.
1292 # -- Simple modifier methods ---------------------------------------
1294 def set_usage(self, usage):
1296 self.usage = _("%prog [options]")
1297 elif usage is SUPPRESS_USAGE:
1299 # For backwards compatibility with Optik 1.3 and earlier.
1300 elif usage.lower()[:7] == "usage: ":
1301 self.usage = usage[7:]
1305 def enable_interspersed_args(self):
1306 self.allow_interspersed_args = True
1308 def disable_interspersed_args(self):
1309 self.allow_interspersed_args = False
1311 def set_process_default_values(self, process):
1312 self.process_default_values = process
1314 def set_default(self, dest, value):
1315 self.defaults[dest] = value
1317 def set_defaults(self, **kwargs):
1318 self.defaults.update(kwargs)
1320 def _get_all_options(self):
1321 options = self.option_list[:]
1322 for group in self.option_groups:
1323 options.extend(group.option_list)
1326 def get_default_values(self):
1327 if not self.process_default_values:
1328 # Old, pre-Optik 1.5 behaviour.
1329 return Values(self.defaults)
1331 defaults = self.defaults.copy()
1332 for option in self._get_all_options():
1333 default = defaults.get(option.dest)
1334 if isbasestring(default):
1335 opt_str = option.get_opt_string()
1336 defaults[option.dest] = option.check_value(opt_str, default)
1338 return Values(defaults)
1341 # -- OptionGroup methods -------------------------------------------
1343 def add_option_group(self, *args, **kwargs):
1344 # XXX lots of overlap with OptionContainer.add_option()
1345 if isinstance(args[0], str):
1346 group = OptionGroup(self, *args, **kwargs)
1347 elif len(args) == 1 and not kwargs:
1349 if not isinstance(group, OptionGroup):
1350 raise TypeError("not an OptionGroup instance: %r" % group)
1351 if group.parser is not self:
1352 raise ValueError("invalid OptionGroup (wrong parser)")
1354 raise TypeError("invalid arguments")
1356 self.option_groups.append(group)
1359 def get_option_group(self, opt_str):
1360 option = (self._short_opt.get(opt_str) or
1361 self._long_opt.get(opt_str))
1362 if option and option.container is not self:
1363 return option.container
1367 # -- Option-parsing methods ----------------------------------------
1369 def _get_args(self, args):
1373 return args[:] # don't modify caller's list
1375 def parse_args(self, args=None, values=None):
1377 parse_args(args : [string] = sys.argv[1:],
1378 values : Values = None)
1379 -> (values : Values, args : [string])
1381 Parse the command-line options found in 'args' (default:
1382 sys.argv[1:]). Any errors result in a call to 'error()', which
1383 by default prints the usage message to stderr and calls
1384 sys.exit() with an error message. On success returns a pair
1385 (values, args) where 'values' is an Values instance (with all
1386 your option values) and 'args' is the list of arguments left
1387 over after parsing options.
1389 rargs = self._get_args(args)
1391 values = self.get_default_values()
1393 # Store the halves of the argument list as attributes for the
1394 # convenience of callbacks:
1396 # the rest of the command-line (the "r" stands for
1397 # "remaining" or "right-hand")
1399 # the leftover arguments -- ie. what's left after removing
1400 # options and their arguments (the "l" stands for "leftover"
1403 self.largs = largs = []
1404 self.values = values
1407 stop = self._process_args(largs, rargs, values)
1408 except (BadOptionError, OptionValueError), err:
1409 self.error(str(err))
1411 args = largs + rargs
1412 return self.check_values(values, args)
1414 def check_values(self, values, args):
1416 check_values(values : Values, args : [string])
1417 -> (values : Values, args : [string])
1419 Check that the supplied option values and leftover arguments are
1420 valid. Returns the option values and leftover arguments
1421 (possibly adjusted, possibly completely new -- whatever you
1422 like). Default implementation just returns the passed-in
1423 values; subclasses may override as desired.
1425 return (values, args)
1427 def _process_args(self, largs, rargs, values):
1428 """_process_args(largs : [string],
1432 Process command-line arguments and populate 'values', consuming
1433 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1434 false, stop at the first non-option argument. If true, accumulate any
1435 interspersed non-option arguments in 'largs'.
1439 # We handle bare "--" explicitly, and bare "-" is handled by the
1440 # standard arg handler since the short arg case ensures that the
1441 # len of the opt string is greater than 1.
1445 elif arg[0:2] == "--":
1446 # process a single long option (possibly with value(s))
1447 self._process_long_opt(rargs, values)
1448 elif arg[:1] == "-" and len(arg) > 1:
1449 # process a cluster of short options (possibly with
1450 # value(s) for the last one only)
1451 self._process_short_opts(rargs, values)
1452 elif self.allow_interspersed_args:
1456 return # stop now, leave this arg in rargs
1458 # Say this is the original argument list:
1459 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1461 # (we are about to process arg(i)).
1463 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1464 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1465 # been removed from largs).
1467 # The while loop will usually consume 1 or more arguments per pass.
1468 # If it consumes 1 (eg. arg is an option that takes no arguments),
1469 # then after _process_arg() is done the situation is:
1471 # largs = subset of [arg0, ..., arg(i)]
1472 # rargs = [arg(i+1), ..., arg(N-1)]
1474 # If allow_interspersed_args is false, largs will always be
1475 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1476 # not a very interesting subset!
1478 def _match_long_opt(self, opt):
1479 """_match_long_opt(opt : string) -> string
1481 Determine which long option string 'opt' matches, ie. which one
1482 it is an unambiguous abbrevation for. Raises BadOptionError if
1483 'opt' doesn't unambiguously match any long option string.
1485 return _match_abbrev(opt, self._long_opt)
1487 def _process_long_opt(self, rargs, values):
1490 # Value explicitly attached to arg? Pretend it's the next
1493 (opt, next_arg) = arg.split("=", 1)
1494 rargs.insert(0, next_arg)
1495 had_explicit_value = True
1498 had_explicit_value = False
1500 opt = self._match_long_opt(opt)
1501 option = self._long_opt[opt]
1502 if option.takes_value():
1503 nargs = option.nargs
1504 if len(rargs) < nargs:
1506 self.error(_("%s option requires an argument") % opt)
1508 self.error(_("%s option requires %d arguments")
1511 value = rargs.pop(0)
1513 value = tuple(rargs[0:nargs])
1516 elif had_explicit_value:
1517 self.error(_("%s option does not take a value") % opt)
1522 option.process(opt, value, values, self)
1524 def _process_short_opts(self, rargs, values):
1530 option = self._short_opt.get(opt)
1531 i = i + 1 # we have consumed a character
1534 raise BadOptionError(opt)
1535 if option.takes_value():
1536 # Any characters left in arg? Pretend they're the
1537 # next arg, and stop consuming characters of arg.
1539 rargs.insert(0, arg[i:])
1542 nargs = option.nargs
1543 if len(rargs) < nargs:
1545 self.error(_("%s option requires an argument") % opt)
1547 self.error(_("%s option requires %d arguments")
1550 value = rargs.pop(0)
1552 value = tuple(rargs[0:nargs])
1555 else: # option doesn't take a value
1558 option.process(opt, value, values, self)
1564 # -- Feedback methods ----------------------------------------------
1566 def get_prog_name(self):
1567 if self.prog is None:
1568 return os.path.basename(sys.argv[0])
1572 def expand_prog_name(self, s):
1573 return s.replace("%prog", self.get_prog_name())
1575 def get_description(self):
1576 return self.expand_prog_name(self.description)
1578 def exit(self, status=0, msg=None):
1580 sys.stderr.write(msg)
1583 def error(self, msg):
1584 """error(msg : string)
1586 Print a usage message incorporating 'msg' to stderr and exit.
1587 If you override this in a subclass, it should not return -- it
1588 should either exit or raise an exception.
1590 self.print_usage(sys.stderr)
1591 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
1593 def get_usage(self):
1595 return self.formatter.format_usage(
1596 self.expand_prog_name(self.usage))
1600 def print_usage(self, file=None):
1601 """print_usage(file : file = stdout)
1603 Print the usage message for the current program (self.usage) to
1604 'file' (default stdout). Any occurence of the string "%prog" in
1605 self.usage is replaced with the name of the current program
1606 (basename of sys.argv[0]). Does nothing if self.usage is empty
1610 file.write(self.get_usage() + '\n')
1612 def get_version(self):
1614 return self.expand_prog_name(self.version)
1618 def print_version(self, file=None):
1619 """print_version(file : file = stdout)
1621 Print the version message for this program (self.version) to
1622 'file' (default stdout). As with print_usage(), any occurence
1623 of "%prog" in self.version is replaced by the current program's
1624 name. Does nothing if self.version is empty or undefined.
1627 file.write(self.get_version() + '\n')
1629 def format_option_help(self, formatter=None):
1630 if formatter is None:
1631 formatter = self.formatter
1632 formatter.store_option_strings(self)
1634 result.append(formatter.format_heading(_("Options")))
1636 if self.option_list:
1637 result.append(OptionContainer.format_option_help(self, formatter))
1639 for group in self.option_groups:
1640 result.append(group.format_help(formatter))
1643 # Drop the last "\n", or the header if no options or option groups:
1644 return "".join(result[:-1])
1646 def format_epilog(self, formatter):
1647 return formatter.format_epilog(self.epilog)
1649 def format_help(self, formatter=None):
1650 if formatter is None:
1651 formatter = self.formatter
1654 result.append(self.get_usage() + "\n")
1655 if self.description:
1656 result.append(self.format_description(formatter) + "\n")
1657 result.append(self.format_option_help(formatter))
1658 result.append(self.format_epilog(formatter))
1659 return "".join(result)
1661 # used by test suite
1662 def _get_encoding(self, file):
1663 encoding = getattr(file, "encoding", None)
1665 encoding = sys.getdefaultencoding()
1668 def print_help(self, file=None):
1669 """print_help(file : file = stdout)
1671 Print an extended help message, listing all options and any
1672 help text provided with them, to 'file' (default stdout).
1676 encoding = self._get_encoding(file)
1677 file.write(encode_wrapper(self.format_help(), encoding, "replace"))
1679 # class OptionParser
1682 def _match_abbrev(s, wordmap):
1683 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1685 Return the string key in 'wordmap' for which 's' is an unambiguous
1686 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1687 'words', raise BadOptionError.
1689 # Is there an exact match?
1693 # Isolate all words with s as a prefix.
1694 possibilities = [w for w in wordmap.keys() if w[:len(s)] == s]
1695 # No exact match, so there had better be just one possibility.
1696 if len(possibilities) == 1:
1697 return possibilities[0]
1698 elif not possibilities:
1699 raise BadOptionError(s)
1701 # More than one possible completion: ambiguous prefix.
1702 possibilities.sort()
1703 raise AmbiguousOptionError(s, possibilities)
1706 # Some day, there might be many Option classes. As of Optik 1.3, the
1707 # preferred way to instantiate Options is indirectly, via make_option(),
1708 # which will become a factory function when there are many Option
1710 make_option = Option
1714 # indent-tabs-mode:nil
1716 # vim: set expandtab tabstop=4 shiftwidth=4: