Catch situations where currentframe() returns None. See SF patch #1447410, this is...
[python.git] / Lib / optparse.py
blobae3d00dc51635ec4fef0b7fab23c60645f631b68
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).
14 """
16 # Python developers: please do not make changes to this file, since
17 # it is automatically generated from the Optik source code.
19 __version__ = "1.5a2"
21 __all__ = ['Option',
22 'SUPPRESS_HELP',
23 'SUPPRESS_USAGE',
24 'Values',
25 'OptionContainer',
26 'OptionGroup',
27 'OptionParser',
28 'HelpFormatter',
29 'IndentedHelpFormatter',
30 'TitledHelpFormatter',
31 'OptParseError',
32 'OptionError',
33 'OptionConflictError',
34 'OptionValueError',
35 'BadOptionError']
37 __copyright__ = """
38 Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved.
39 Copyright (c) 2002-2004 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
43 met:
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.
67 """
69 import sys, os
70 import textwrap
71 try:
72 from gettext import gettext as _
73 except ImportError:
74 _ = lambda arg: arg
76 def _repr(self):
77 return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
80 # This file was generated from:
81 # Id: option_parser.py 421 2004-10-26 00:45:16Z greg
82 # Id: option.py 422 2004-10-26 00:53:47Z greg
83 # Id: help.py 367 2004-07-24 23:21:21Z gward
84 # Id: errors.py 367 2004-07-24 23:21:21Z gward
86 class OptParseError (Exception):
87 def __init__(self, msg):
88 self.msg = msg
90 def __str__(self):
91 return self.msg
94 class OptionError (OptParseError):
95 """
96 Raised if an Option instance is created with invalid or
97 inconsistent arguments.
98 """
100 def __init__(self, msg, option):
101 self.msg = msg
102 self.option_id = str(option)
104 def __str__(self):
105 if self.option_id:
106 return "option %s: %s" % (self.option_id, self.msg)
107 else:
108 return self.msg
110 class OptionConflictError (OptionError):
112 Raised if conflicting options are added to an OptionParser.
115 class OptionValueError (OptParseError):
117 Raised if an invalid option value is encountered on the command
118 line.
121 class BadOptionError (OptParseError):
123 Raised if an invalid or ambiguous option is seen on the command-line.
127 class HelpFormatter:
130 Abstract base class for formatting option help. OptionParser
131 instances should use one of the HelpFormatter subclasses for
132 formatting help; by default IndentedHelpFormatter is used.
134 Instance attributes:
135 parser : OptionParser
136 the controlling OptionParser instance
137 indent_increment : int
138 the number of columns to indent per nesting level
139 max_help_position : int
140 the maximum starting column for option help text
141 help_position : int
142 the calculated starting column for option help text;
143 initially the same as the maximum
144 width : int
145 total number of columns for output (pass None to constructor for
146 this value to be taken from the $COLUMNS environment variable)
147 level : int
148 current indentation level
149 current_indent : int
150 current indentation level (in columns)
151 help_width : int
152 number of columns available for option help text (calculated)
153 default_tag : str
154 text to replace with each option's default value, "%default"
155 by default. Set to false value to disable default value expansion.
156 option_strings : { Option : str }
157 maps Option instances to the snippet of help text explaining
158 the syntax of that option, e.g. "-h, --help" or
159 "-fFILE, --file=FILE"
160 _short_opt_fmt : str
161 format string controlling how short options with values are
162 printed in help text. Must be either "%s%s" ("-fFILE") or
163 "%s %s" ("-f FILE"), because those are the two syntaxes that
164 Optik supports.
165 _long_opt_fmt : str
166 similar but for long options; must be either "%s %s" ("--file FILE")
167 or "%s=%s" ("--file=FILE").
170 NO_DEFAULT_VALUE = "none"
172 def __init__(self,
173 indent_increment,
174 max_help_position,
175 width,
176 short_first):
177 self.parser = None
178 self.indent_increment = indent_increment
179 self.help_position = self.max_help_position = max_help_position
180 if width is None:
181 try:
182 width = int(os.environ['COLUMNS'])
183 except (KeyError, ValueError):
184 width = 80
185 width -= 2
186 self.width = width
187 self.current_indent = 0
188 self.level = 0
189 self.help_width = None # computed later
190 self.short_first = short_first
191 self.default_tag = "%default"
192 self.option_strings = {}
193 self._short_opt_fmt = "%s %s"
194 self._long_opt_fmt = "%s=%s"
196 def set_parser(self, parser):
197 self.parser = parser
199 def set_short_opt_delimiter(self, delim):
200 if delim not in ("", " "):
201 raise ValueError(
202 "invalid metavar delimiter for short options: %r" % delim)
203 self._short_opt_fmt = "%s" + delim + "%s"
205 def set_long_opt_delimiter(self, delim):
206 if delim not in ("=", " "):
207 raise ValueError(
208 "invalid metavar delimiter for long options: %r" % delim)
209 self._long_opt_fmt = "%s" + delim + "%s"
211 def indent(self):
212 self.current_indent += self.indent_increment
213 self.level += 1
215 def dedent(self):
216 self.current_indent -= self.indent_increment
217 assert self.current_indent >= 0, "Indent decreased below 0."
218 self.level -= 1
220 def format_usage(self, usage):
221 raise NotImplementedError, "subclasses must implement"
223 def format_heading(self, heading):
224 raise NotImplementedError, "subclasses must implement"
226 def format_description(self, description):
227 if not description:
228 return ""
229 desc_width = self.width - self.current_indent
230 indent = " "*self.current_indent
231 return textwrap.fill(description,
232 desc_width,
233 initial_indent=indent,
234 subsequent_indent=indent) + "\n"
236 def expand_default(self, option):
237 if self.parser is None or not self.default_tag:
238 return option.help
240 default_value = self.parser.defaults.get(option.dest)
241 if default_value is NO_DEFAULT or default_value is None:
242 default_value = self.NO_DEFAULT_VALUE
244 return option.help.replace(self.default_tag, str(default_value))
246 def format_option(self, option):
247 # The help for each option consists of two parts:
248 # * the opt strings and metavars
249 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
250 # * the user-supplied help string
251 # eg. ("turn on expert mode", "read data from FILENAME")
253 # If possible, we write both of these on the same line:
254 # -x turn on expert mode
256 # But if the opt string list is too long, we put the help
257 # string on a second line, indented to the same column it would
258 # start in if it fit on the first line.
259 # -fFILENAME, --file=FILENAME
260 # read data from FILENAME
261 result = []
262 opts = self.option_strings[option]
263 opt_width = self.help_position - self.current_indent - 2
264 if len(opts) > opt_width:
265 opts = "%*s%s\n" % (self.current_indent, "", opts)
266 indent_first = self.help_position
267 else: # start help on same line as opts
268 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
269 indent_first = 0
270 result.append(opts)
271 if option.help:
272 help_text = self.expand_default(option)
273 help_lines = textwrap.wrap(help_text, self.help_width)
274 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
275 result.extend(["%*s%s\n" % (self.help_position, "", line)
276 for line in help_lines[1:]])
277 elif opts[-1] != "\n":
278 result.append("\n")
279 return "".join(result)
281 def store_option_strings(self, parser):
282 self.indent()
283 max_len = 0
284 for opt in parser.option_list:
285 strings = self.format_option_strings(opt)
286 self.option_strings[opt] = strings
287 max_len = max(max_len, len(strings) + self.current_indent)
288 self.indent()
289 for group in parser.option_groups:
290 for opt in group.option_list:
291 strings = self.format_option_strings(opt)
292 self.option_strings[opt] = strings
293 max_len = max(max_len, len(strings) + self.current_indent)
294 self.dedent()
295 self.dedent()
296 self.help_position = min(max_len + 2, self.max_help_position)
297 self.help_width = self.width - self.help_position
299 def format_option_strings(self, option):
300 """Return a comma-separated list of option strings & metavariables."""
301 if option.takes_value():
302 metavar = option.metavar or option.dest.upper()
303 short_opts = [self._short_opt_fmt % (sopt, metavar)
304 for sopt in option._short_opts]
305 long_opts = [self._long_opt_fmt % (lopt, metavar)
306 for lopt in option._long_opts]
307 else:
308 short_opts = option._short_opts
309 long_opts = option._long_opts
311 if self.short_first:
312 opts = short_opts + long_opts
313 else:
314 opts = long_opts + short_opts
316 return ", ".join(opts)
318 class IndentedHelpFormatter (HelpFormatter):
319 """Format help with indented section bodies.
322 def __init__(self,
323 indent_increment=2,
324 max_help_position=24,
325 width=None,
326 short_first=1):
327 HelpFormatter.__init__(
328 self, indent_increment, max_help_position, width, short_first)
330 def format_usage(self, usage):
331 return _("usage: %s\n") % usage
333 def format_heading(self, heading):
334 return "%*s%s:\n" % (self.current_indent, "", heading)
337 class TitledHelpFormatter (HelpFormatter):
338 """Format help with underlined section headers.
341 def __init__(self,
342 indent_increment=0,
343 max_help_position=24,
344 width=None,
345 short_first=0):
346 HelpFormatter.__init__ (
347 self, indent_increment, max_help_position, width, short_first)
349 def format_usage(self, usage):
350 return "%s %s\n" % (self.format_heading(_("Usage")), usage)
352 def format_heading(self, heading):
353 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
356 _builtin_cvt = { "int" : (int, _("integer")),
357 "long" : (long, _("long integer")),
358 "float" : (float, _("floating-point")),
359 "complex" : (complex, _("complex")) }
361 def check_builtin(option, opt, value):
362 (cvt, what) = _builtin_cvt[option.type]
363 try:
364 return cvt(value)
365 except ValueError:
366 raise OptionValueError(
367 _("option %s: invalid %s value: %r") % (opt, what, value))
369 def check_choice(option, opt, value):
370 if value in option.choices:
371 return value
372 else:
373 choices = ", ".join(map(repr, option.choices))
374 raise OptionValueError(
375 _("option %s: invalid choice: %r (choose from %s)")
376 % (opt, value, choices))
378 # Not supplying a default is different from a default of None,
379 # so we need an explicit "not supplied" value.
380 NO_DEFAULT = ("NO", "DEFAULT")
383 class Option:
385 Instance attributes:
386 _short_opts : [string]
387 _long_opts : [string]
389 action : string
390 type : string
391 dest : string
392 default : any
393 nargs : int
394 const : any
395 choices : [string]
396 callback : function
397 callback_args : (any*)
398 callback_kwargs : { string : any }
399 help : string
400 metavar : string
403 # The list of instance attributes that may be set through
404 # keyword args to the constructor.
405 ATTRS = ['action',
406 'type',
407 'dest',
408 'default',
409 'nargs',
410 'const',
411 'choices',
412 'callback',
413 'callback_args',
414 'callback_kwargs',
415 'help',
416 'metavar']
418 # The set of actions allowed by option parsers. Explicitly listed
419 # here so the constructor can validate its arguments.
420 ACTIONS = ("store",
421 "store_const",
422 "store_true",
423 "store_false",
424 "append",
425 "count",
426 "callback",
427 "help",
428 "version")
430 # The set of actions that involve storing a value somewhere;
431 # also listed just for constructor argument validation. (If
432 # the action is one of these, there must be a destination.)
433 STORE_ACTIONS = ("store",
434 "store_const",
435 "store_true",
436 "store_false",
437 "append",
438 "count")
440 # The set of actions for which it makes sense to supply a value
441 # type, ie. which may consume an argument from the command line.
442 TYPED_ACTIONS = ("store",
443 "append",
444 "callback")
446 # The set of actions which *require* a value type, ie. that
447 # always consume an argument from the command line.
448 ALWAYS_TYPED_ACTIONS = ("store",
449 "append")
451 # The set of known types for option parsers. Again, listed here for
452 # constructor argument validation.
453 TYPES = ("string", "int", "long", "float", "complex", "choice")
455 # Dictionary of argument checking functions, which convert and
456 # validate option arguments according to the option type.
458 # Signature of checking functions is:
459 # check(option : Option, opt : string, value : string) -> any
460 # where
461 # option is the Option instance calling the checker
462 # opt is the actual option seen on the command-line
463 # (eg. "-a", "--file")
464 # value is the option argument seen on the command-line
466 # The return value should be in the appropriate Python type
467 # for option.type -- eg. an integer if option.type == "int".
469 # If no checker is defined for a type, arguments will be
470 # unchecked and remain strings.
471 TYPE_CHECKER = { "int" : check_builtin,
472 "long" : check_builtin,
473 "float" : check_builtin,
474 "complex": check_builtin,
475 "choice" : check_choice,
479 # CHECK_METHODS is a list of unbound method objects; they are called
480 # by the constructor, in order, after all attributes are
481 # initialized. The list is created and filled in later, after all
482 # the methods are actually defined. (I just put it here because I
483 # like to define and document all class attributes in the same
484 # place.) Subclasses that add another _check_*() method should
485 # define their own CHECK_METHODS list that adds their check method
486 # to those from this class.
487 CHECK_METHODS = None
490 # -- Constructor/initialization methods ----------------------------
492 def __init__(self, *opts, **attrs):
493 # Set _short_opts, _long_opts attrs from 'opts' tuple.
494 # Have to be set now, in case no option strings are supplied.
495 self._short_opts = []
496 self._long_opts = []
497 opts = self._check_opt_strings(opts)
498 self._set_opt_strings(opts)
500 # Set all other attrs (action, type, etc.) from 'attrs' dict
501 self._set_attrs(attrs)
503 # Check all the attributes we just set. There are lots of
504 # complicated interdependencies, but luckily they can be farmed
505 # out to the _check_*() methods listed in CHECK_METHODS -- which
506 # could be handy for subclasses! The one thing these all share
507 # is that they raise OptionError if they discover a problem.
508 for checker in self.CHECK_METHODS:
509 checker(self)
511 def _check_opt_strings(self, opts):
512 # Filter out None because early versions of Optik had exactly
513 # one short option and one long option, either of which
514 # could be None.
515 opts = filter(None, opts)
516 if not opts:
517 raise TypeError("at least one option string must be supplied")
518 return opts
520 def _set_opt_strings(self, opts):
521 for opt in opts:
522 if len(opt) < 2:
523 raise OptionError(
524 "invalid option string %r: "
525 "must be at least two characters long" % opt, self)
526 elif len(opt) == 2:
527 if not (opt[0] == "-" and opt[1] != "-"):
528 raise OptionError(
529 "invalid short option string %r: "
530 "must be of the form -x, (x any non-dash char)" % opt,
531 self)
532 self._short_opts.append(opt)
533 else:
534 if not (opt[0:2] == "--" and opt[2] != "-"):
535 raise OptionError(
536 "invalid long option string %r: "
537 "must start with --, followed by non-dash" % opt,
538 self)
539 self._long_opts.append(opt)
541 def _set_attrs(self, attrs):
542 for attr in self.ATTRS:
543 if attrs.has_key(attr):
544 setattr(self, attr, attrs[attr])
545 del attrs[attr]
546 else:
547 if attr == 'default':
548 setattr(self, attr, NO_DEFAULT)
549 else:
550 setattr(self, attr, None)
551 if attrs:
552 raise OptionError(
553 "invalid keyword arguments: %s" % ", ".join(attrs.keys()),
554 self)
557 # -- Constructor validation methods --------------------------------
559 def _check_action(self):
560 if self.action is None:
561 self.action = "store"
562 elif self.action not in self.ACTIONS:
563 raise OptionError("invalid action: %r" % self.action, self)
565 def _check_type(self):
566 if self.type is None:
567 if self.action in self.ALWAYS_TYPED_ACTIONS:
568 if self.choices is not None:
569 # The "choices" attribute implies "choice" type.
570 self.type = "choice"
571 else:
572 # No type given? "string" is the most sensible default.
573 self.type = "string"
574 else:
575 # Allow type objects as an alternative to their names.
576 if type(self.type) is type:
577 self.type = self.type.__name__
578 if self.type == "str":
579 self.type = "string"
581 if self.type not in self.TYPES:
582 raise OptionError("invalid option type: %r" % self.type, self)
583 if self.action not in self.TYPED_ACTIONS:
584 raise OptionError(
585 "must not supply a type for action %r" % self.action, self)
587 def _check_choice(self):
588 if self.type == "choice":
589 if self.choices is None:
590 raise OptionError(
591 "must supply a list of choices for type 'choice'", self)
592 elif type(self.choices) not in (tuple, list):
593 raise OptionError(
594 "choices must be a list of strings ('%s' supplied)"
595 % str(type(self.choices)).split("'")[1], self)
596 elif self.choices is not None:
597 raise OptionError(
598 "must not supply choices for type %r" % self.type, self)
600 def _check_dest(self):
601 # No destination given, and we need one for this action. The
602 # self.type check is for callbacks that take a value.
603 takes_value = (self.action in self.STORE_ACTIONS or
604 self.type is not None)
605 if self.dest is None and takes_value:
607 # Glean a destination from the first long option string,
608 # or from the first short option string if no long options.
609 if self._long_opts:
610 # eg. "--foo-bar" -> "foo_bar"
611 self.dest = self._long_opts[0][2:].replace('-', '_')
612 else:
613 self.dest = self._short_opts[0][1]
615 def _check_const(self):
616 if self.action != "store_const" and self.const is not None:
617 raise OptionError(
618 "'const' must not be supplied for action %r" % self.action,
619 self)
621 def _check_nargs(self):
622 if self.action in self.TYPED_ACTIONS:
623 if self.nargs is None:
624 self.nargs = 1
625 elif self.nargs is not None:
626 raise OptionError(
627 "'nargs' must not be supplied for action %r" % self.action,
628 self)
630 def _check_callback(self):
631 if self.action == "callback":
632 if not callable(self.callback):
633 raise OptionError(
634 "callback not callable: %r" % self.callback, self)
635 if (self.callback_args is not None and
636 type(self.callback_args) is not tuple):
637 raise OptionError(
638 "callback_args, if supplied, must be a tuple: not %r"
639 % self.callback_args, self)
640 if (self.callback_kwargs is not None and
641 type(self.callback_kwargs) is not dict):
642 raise OptionError(
643 "callback_kwargs, if supplied, must be a dict: not %r"
644 % self.callback_kwargs, self)
645 else:
646 if self.callback is not None:
647 raise OptionError(
648 "callback supplied (%r) for non-callback option"
649 % self.callback, self)
650 if self.callback_args is not None:
651 raise OptionError(
652 "callback_args supplied for non-callback option", self)
653 if self.callback_kwargs is not None:
654 raise OptionError(
655 "callback_kwargs supplied for non-callback option", self)
658 CHECK_METHODS = [_check_action,
659 _check_type,
660 _check_choice,
661 _check_dest,
662 _check_const,
663 _check_nargs,
664 _check_callback]
667 # -- Miscellaneous methods -----------------------------------------
669 def __str__(self):
670 return "/".join(self._short_opts + self._long_opts)
672 __repr__ = _repr
674 def takes_value(self):
675 return self.type is not None
677 def get_opt_string(self):
678 if self._long_opts:
679 return self._long_opts[0]
680 else:
681 return self._short_opts[0]
684 # -- Processing methods --------------------------------------------
686 def check_value(self, opt, value):
687 checker = self.TYPE_CHECKER.get(self.type)
688 if checker is None:
689 return value
690 else:
691 return checker(self, opt, value)
693 def convert_value(self, opt, value):
694 if value is not None:
695 if self.nargs == 1:
696 return self.check_value(opt, value)
697 else:
698 return tuple([self.check_value(opt, v) for v in value])
700 def process(self, opt, value, values, parser):
702 # First, convert the value(s) to the right type. Howl if any
703 # value(s) are bogus.
704 value = self.convert_value(opt, value)
706 # And then take whatever action is expected of us.
707 # This is a separate method to make life easier for
708 # subclasses to add new actions.
709 return self.take_action(
710 self.action, self.dest, opt, value, values, parser)
712 def take_action(self, action, dest, opt, value, values, parser):
713 if action == "store":
714 setattr(values, dest, value)
715 elif action == "store_const":
716 setattr(values, dest, self.const)
717 elif action == "store_true":
718 setattr(values, dest, True)
719 elif action == "store_false":
720 setattr(values, dest, False)
721 elif action == "append":
722 values.ensure_value(dest, []).append(value)
723 elif action == "count":
724 setattr(values, dest, values.ensure_value(dest, 0) + 1)
725 elif action == "callback":
726 args = self.callback_args or ()
727 kwargs = self.callback_kwargs or {}
728 self.callback(self, opt, value, parser, *args, **kwargs)
729 elif action == "help":
730 parser.print_help()
731 parser.exit()
732 elif action == "version":
733 parser.print_version()
734 parser.exit()
735 else:
736 raise RuntimeError, "unknown action %r" % self.action
738 return 1
740 # class Option
743 SUPPRESS_HELP = "SUPPRESS"+"HELP"
744 SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
746 # For compatibility with Python 2.2
747 try:
748 True, False
749 except NameError:
750 (True, False) = (1, 0)
751 try:
752 basestring
753 except NameError:
754 basestring = (str, unicode)
757 class Values:
759 def __init__(self, defaults=None):
760 if defaults:
761 for (attr, val) in defaults.items():
762 setattr(self, attr, val)
764 def __str__(self):
765 return str(self.__dict__)
767 __repr__ = _repr
769 def __eq__(self, other):
770 if isinstance(other, Values):
771 return self.__dict__ == other.__dict__
772 elif isinstance(other, dict):
773 return self.__dict__ == other
774 else:
775 return False
777 def __ne__(self, other):
778 return not (self == other)
780 def _update_careful(self, dict):
782 Update the option values from an arbitrary dictionary, but only
783 use keys from dict that already have a corresponding attribute
784 in self. Any keys in dict without a corresponding attribute
785 are silently ignored.
787 for attr in dir(self):
788 if dict.has_key(attr):
789 dval = dict[attr]
790 if dval is not None:
791 setattr(self, attr, dval)
793 def _update_loose(self, dict):
795 Update the option values from an arbitrary dictionary,
796 using all keys from the dictionary regardless of whether
797 they have a corresponding attribute in self or not.
799 self.__dict__.update(dict)
801 def _update(self, dict, mode):
802 if mode == "careful":
803 self._update_careful(dict)
804 elif mode == "loose":
805 self._update_loose(dict)
806 else:
807 raise ValueError, "invalid update mode: %r" % mode
809 def read_module(self, modname, mode="careful"):
810 __import__(modname)
811 mod = sys.modules[modname]
812 self._update(vars(mod), mode)
814 def read_file(self, filename, mode="careful"):
815 vars = {}
816 execfile(filename, vars)
817 self._update(vars, mode)
819 def ensure_value(self, attr, value):
820 if not hasattr(self, attr) or getattr(self, attr) is None:
821 setattr(self, attr, value)
822 return getattr(self, attr)
825 class OptionContainer:
828 Abstract base class.
830 Class attributes:
831 standard_option_list : [Option]
832 list of standard options that will be accepted by all instances
833 of this parser class (intended to be overridden by subclasses).
835 Instance attributes:
836 option_list : [Option]
837 the list of Option objects contained by this OptionContainer
838 _short_opt : { string : Option }
839 dictionary mapping short option strings, eg. "-f" or "-X",
840 to the Option instances that implement them. If an Option
841 has multiple short option strings, it will appears in this
842 dictionary multiple times. [1]
843 _long_opt : { string : Option }
844 dictionary mapping long option strings, eg. "--file" or
845 "--exclude", to the Option instances that implement them.
846 Again, a given Option can occur multiple times in this
847 dictionary. [1]
848 defaults : { string : any }
849 dictionary mapping option destination names to default
850 values for each destination [1]
852 [1] These mappings are common to (shared by) all components of the
853 controlling OptionParser, where they are initially created.
857 def __init__(self, option_class, conflict_handler, description):
858 # Initialize the option list and related data structures.
859 # This method must be provided by subclasses, and it must
860 # initialize at least the following instance attributes:
861 # option_list, _short_opt, _long_opt, defaults.
862 self._create_option_list()
864 self.option_class = option_class
865 self.set_conflict_handler(conflict_handler)
866 self.set_description(description)
868 def _create_option_mappings(self):
869 # For use by OptionParser constructor -- create the master
870 # option mappings used by this OptionParser and all
871 # OptionGroups that it owns.
872 self._short_opt = {} # single letter -> Option instance
873 self._long_opt = {} # long option -> Option instance
874 self.defaults = {} # maps option dest -> default value
877 def _share_option_mappings(self, parser):
878 # For use by OptionGroup constructor -- use shared option
879 # mappings from the OptionParser that owns this OptionGroup.
880 self._short_opt = parser._short_opt
881 self._long_opt = parser._long_opt
882 self.defaults = parser.defaults
884 def set_conflict_handler(self, handler):
885 if handler not in ("error", "resolve"):
886 raise ValueError, "invalid conflict_resolution value %r" % handler
887 self.conflict_handler = handler
889 def set_description(self, description):
890 self.description = description
892 def get_description(self):
893 return self.description
896 # -- Option-adding methods -----------------------------------------
898 def _check_conflict(self, option):
899 conflict_opts = []
900 for opt in option._short_opts:
901 if self._short_opt.has_key(opt):
902 conflict_opts.append((opt, self._short_opt[opt]))
903 for opt in option._long_opts:
904 if self._long_opt.has_key(opt):
905 conflict_opts.append((opt, self._long_opt[opt]))
907 if conflict_opts:
908 handler = self.conflict_handler
909 if handler == "error":
910 raise OptionConflictError(
911 "conflicting option string(s): %s"
912 % ", ".join([co[0] for co in conflict_opts]),
913 option)
914 elif handler == "resolve":
915 for (opt, c_option) in conflict_opts:
916 if opt.startswith("--"):
917 c_option._long_opts.remove(opt)
918 del self._long_opt[opt]
919 else:
920 c_option._short_opts.remove(opt)
921 del self._short_opt[opt]
922 if not (c_option._short_opts or c_option._long_opts):
923 c_option.container.option_list.remove(c_option)
925 def add_option(self, *args, **kwargs):
926 """add_option(Option)
927 add_option(opt_str, ..., kwarg=val, ...)
929 if type(args[0]) is str:
930 option = self.option_class(*args, **kwargs)
931 elif len(args) == 1 and not kwargs:
932 option = args[0]
933 if not isinstance(option, Option):
934 raise TypeError, "not an Option instance: %r" % option
935 else:
936 raise TypeError, "invalid arguments"
938 self._check_conflict(option)
940 self.option_list.append(option)
941 option.container = self
942 for opt in option._short_opts:
943 self._short_opt[opt] = option
944 for opt in option._long_opts:
945 self._long_opt[opt] = option
947 if option.dest is not None: # option has a dest, we need a default
948 if option.default is not NO_DEFAULT:
949 self.defaults[option.dest] = option.default
950 elif not self.defaults.has_key(option.dest):
951 self.defaults[option.dest] = None
953 return option
955 def add_options(self, option_list):
956 for option in option_list:
957 self.add_option(option)
959 # -- Option query/removal methods ----------------------------------
961 def get_option(self, opt_str):
962 return (self._short_opt.get(opt_str) or
963 self._long_opt.get(opt_str))
965 def has_option(self, opt_str):
966 return (self._short_opt.has_key(opt_str) or
967 self._long_opt.has_key(opt_str))
969 def remove_option(self, opt_str):
970 option = self._short_opt.get(opt_str)
971 if option is None:
972 option = self._long_opt.get(opt_str)
973 if option is None:
974 raise ValueError("no such option %r" % opt_str)
976 for opt in option._short_opts:
977 del self._short_opt[opt]
978 for opt in option._long_opts:
979 del self._long_opt[opt]
980 option.container.option_list.remove(option)
983 # -- Help-formatting methods ---------------------------------------
985 def format_option_help(self, formatter):
986 if not self.option_list:
987 return ""
988 result = []
989 for option in self.option_list:
990 if not option.help is SUPPRESS_HELP:
991 result.append(formatter.format_option(option))
992 return "".join(result)
994 def format_description(self, formatter):
995 return formatter.format_description(self.get_description())
997 def format_help(self, formatter):
998 result = []
999 if self.description:
1000 result.append(self.format_description(formatter))
1001 if self.option_list:
1002 result.append(self.format_option_help(formatter))
1003 return "\n".join(result)
1006 class OptionGroup (OptionContainer):
1008 def __init__(self, parser, title, description=None):
1009 self.parser = parser
1010 OptionContainer.__init__(
1011 self, parser.option_class, parser.conflict_handler, description)
1012 self.title = title
1014 def _create_option_list(self):
1015 self.option_list = []
1016 self._share_option_mappings(self.parser)
1018 def set_title(self, title):
1019 self.title = title
1021 # -- Help-formatting methods ---------------------------------------
1023 def format_help(self, formatter):
1024 result = formatter.format_heading(self.title)
1025 formatter.indent()
1026 result += OptionContainer.format_help(self, formatter)
1027 formatter.dedent()
1028 return result
1031 class OptionParser (OptionContainer):
1034 Class attributes:
1035 standard_option_list : [Option]
1036 list of standard options that will be accepted by all instances
1037 of this parser class (intended to be overridden by subclasses).
1039 Instance attributes:
1040 usage : string
1041 a usage string for your program. Before it is displayed
1042 to the user, "%prog" will be expanded to the name of
1043 your program (self.prog or os.path.basename(sys.argv[0])).
1044 prog : string
1045 the name of the current program (to override
1046 os.path.basename(sys.argv[0])).
1048 option_groups : [OptionGroup]
1049 list of option groups in this parser (option groups are
1050 irrelevant for parsing the command-line, but very useful
1051 for generating help)
1053 allow_interspersed_args : bool = true
1054 if true, positional arguments may be interspersed with options.
1055 Assuming -a and -b each take a single argument, the command-line
1056 -ablah foo bar -bboo baz
1057 will be interpreted the same as
1058 -ablah -bboo -- foo bar baz
1059 If this flag were false, that command line would be interpreted as
1060 -ablah -- foo bar -bboo baz
1061 -- ie. we stop processing options as soon as we see the first
1062 non-option argument. (This is the tradition followed by
1063 Python's getopt module, Perl's Getopt::Std, and other argument-
1064 parsing libraries, but it is generally annoying to users.)
1066 process_default_values : bool = true
1067 if true, option default values are processed similarly to option
1068 values from the command line: that is, they are passed to the
1069 type-checking function for the option's type (as long as the
1070 default value is a string). (This really only matters if you
1071 have defined custom types; see SF bug #955889.) Set it to false
1072 to restore the behaviour of Optik 1.4.1 and earlier.
1074 rargs : [string]
1075 the argument list currently being parsed. Only set when
1076 parse_args() is active, and continually trimmed down as
1077 we consume arguments. Mainly there for the benefit of
1078 callback options.
1079 largs : [string]
1080 the list of leftover arguments that we have skipped while
1081 parsing options. If allow_interspersed_args is false, this
1082 list is always empty.
1083 values : Values
1084 the set of option values currently being accumulated. Only
1085 set when parse_args() is active. Also mainly for callbacks.
1087 Because of the 'rargs', 'largs', and 'values' attributes,
1088 OptionParser is not thread-safe. If, for some perverse reason, you
1089 need to parse command-line arguments simultaneously in different
1090 threads, use different OptionParser instances.
1094 standard_option_list = []
1096 def __init__(self,
1097 usage=None,
1098 option_list=None,
1099 option_class=Option,
1100 version=None,
1101 conflict_handler="error",
1102 description=None,
1103 formatter=None,
1104 add_help_option=True,
1105 prog=None):
1106 OptionContainer.__init__(
1107 self, option_class, conflict_handler, description)
1108 self.set_usage(usage)
1109 self.prog = prog
1110 self.version = version
1111 self.allow_interspersed_args = True
1112 self.process_default_values = True
1113 if formatter is None:
1114 formatter = IndentedHelpFormatter()
1115 self.formatter = formatter
1116 self.formatter.set_parser(self)
1118 # Populate the option list; initial sources are the
1119 # standard_option_list class attribute, the 'option_list'
1120 # argument, and (if applicable) the _add_version_option() and
1121 # _add_help_option() methods.
1122 self._populate_option_list(option_list,
1123 add_help=add_help_option)
1125 self._init_parsing_state()
1127 # -- Private methods -----------------------------------------------
1128 # (used by our or OptionContainer's constructor)
1130 def _create_option_list(self):
1131 self.option_list = []
1132 self.option_groups = []
1133 self._create_option_mappings()
1135 def _add_help_option(self):
1136 self.add_option("-h", "--help",
1137 action="help",
1138 help=_("show this help message and exit"))
1140 def _add_version_option(self):
1141 self.add_option("--version",
1142 action="version",
1143 help=_("show program's version number and exit"))
1145 def _populate_option_list(self, option_list, add_help=True):
1146 if self.standard_option_list:
1147 self.add_options(self.standard_option_list)
1148 if option_list:
1149 self.add_options(option_list)
1150 if self.version:
1151 self._add_version_option()
1152 if add_help:
1153 self._add_help_option()
1155 def _init_parsing_state(self):
1156 # These are set in parse_args() for the convenience of callbacks.
1157 self.rargs = None
1158 self.largs = None
1159 self.values = None
1162 # -- Simple modifier methods ---------------------------------------
1164 def set_usage(self, usage):
1165 if usage is None:
1166 self.usage = _("%prog [options]")
1167 elif usage is SUPPRESS_USAGE:
1168 self.usage = None
1169 # For backwards compatibility with Optik 1.3 and earlier.
1170 elif usage.startswith("usage:" + " "):
1171 self.usage = usage[7:]
1172 else:
1173 self.usage = usage
1175 def enable_interspersed_args(self):
1176 self.allow_interspersed_args = True
1178 def disable_interspersed_args(self):
1179 self.allow_interspersed_args = False
1181 def set_process_default_values(self, process):
1182 self.process_default_values = process
1184 def set_default(self, dest, value):
1185 self.defaults[dest] = value
1187 def set_defaults(self, **kwargs):
1188 self.defaults.update(kwargs)
1190 def _get_all_options(self):
1191 options = self.option_list[:]
1192 for group in self.option_groups:
1193 options.extend(group.option_list)
1194 return options
1196 def get_default_values(self):
1197 if not self.process_default_values:
1198 # Old, pre-Optik 1.5 behaviour.
1199 return Values(self.defaults)
1201 defaults = self.defaults.copy()
1202 for option in self._get_all_options():
1203 default = defaults.get(option.dest)
1204 if isinstance(default, basestring):
1205 opt_str = option.get_opt_string()
1206 defaults[option.dest] = option.check_value(opt_str, default)
1208 return Values(defaults)
1211 # -- OptionGroup methods -------------------------------------------
1213 def add_option_group(self, *args, **kwargs):
1214 # XXX lots of overlap with OptionContainer.add_option()
1215 if type(args[0]) is str:
1216 group = OptionGroup(self, *args, **kwargs)
1217 elif len(args) == 1 and not kwargs:
1218 group = args[0]
1219 if not isinstance(group, OptionGroup):
1220 raise TypeError, "not an OptionGroup instance: %r" % group
1221 if group.parser is not self:
1222 raise ValueError, "invalid OptionGroup (wrong parser)"
1223 else:
1224 raise TypeError, "invalid arguments"
1226 self.option_groups.append(group)
1227 return group
1229 def get_option_group(self, opt_str):
1230 option = (self._short_opt.get(opt_str) or
1231 self._long_opt.get(opt_str))
1232 if option and option.container is not self:
1233 return option.container
1234 return None
1237 # -- Option-parsing methods ----------------------------------------
1239 def _get_args(self, args):
1240 if args is None:
1241 return sys.argv[1:]
1242 else:
1243 return args[:] # don't modify caller's list
1245 def parse_args(self, args=None, values=None):
1247 parse_args(args : [string] = sys.argv[1:],
1248 values : Values = None)
1249 -> (values : Values, args : [string])
1251 Parse the command-line options found in 'args' (default:
1252 sys.argv[1:]). Any errors result in a call to 'error()', which
1253 by default prints the usage message to stderr and calls
1254 sys.exit() with an error message. On success returns a pair
1255 (values, args) where 'values' is an Values instance (with all
1256 your option values) and 'args' is the list of arguments left
1257 over after parsing options.
1259 rargs = self._get_args(args)
1260 if values is None:
1261 values = self.get_default_values()
1263 # Store the halves of the argument list as attributes for the
1264 # convenience of callbacks:
1265 # rargs
1266 # the rest of the command-line (the "r" stands for
1267 # "remaining" or "right-hand")
1268 # largs
1269 # the leftover arguments -- ie. what's left after removing
1270 # options and their arguments (the "l" stands for "leftover"
1271 # or "left-hand")
1272 self.rargs = rargs
1273 self.largs = largs = []
1274 self.values = values
1276 try:
1277 stop = self._process_args(largs, rargs, values)
1278 except (BadOptionError, OptionValueError), err:
1279 self.error(err.msg)
1281 args = largs + rargs
1282 return self.check_values(values, args)
1284 def check_values(self, values, args):
1286 check_values(values : Values, args : [string])
1287 -> (values : Values, args : [string])
1289 Check that the supplied option values and leftover arguments are
1290 valid. Returns the option values and leftover arguments
1291 (possibly adjusted, possibly completely new -- whatever you
1292 like). Default implementation just returns the passed-in
1293 values; subclasses may override as desired.
1295 return (values, args)
1297 def _process_args(self, largs, rargs, values):
1298 """_process_args(largs : [string],
1299 rargs : [string],
1300 values : Values)
1302 Process command-line arguments and populate 'values', consuming
1303 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1304 false, stop at the first non-option argument. If true, accumulate any
1305 interspersed non-option arguments in 'largs'.
1307 while rargs:
1308 arg = rargs[0]
1309 # We handle bare "--" explicitly, and bare "-" is handled by the
1310 # standard arg handler since the short arg case ensures that the
1311 # len of the opt string is greater than 1.
1312 if arg == "--":
1313 del rargs[0]
1314 return
1315 elif arg[0:2] == "--":
1316 # process a single long option (possibly with value(s))
1317 self._process_long_opt(rargs, values)
1318 elif arg[:1] == "-" and len(arg) > 1:
1319 # process a cluster of short options (possibly with
1320 # value(s) for the last one only)
1321 self._process_short_opts(rargs, values)
1322 elif self.allow_interspersed_args:
1323 largs.append(arg)
1324 del rargs[0]
1325 else:
1326 return # stop now, leave this arg in rargs
1328 # Say this is the original argument list:
1329 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1331 # (we are about to process arg(i)).
1333 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1334 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1335 # been removed from largs).
1337 # The while loop will usually consume 1 or more arguments per pass.
1338 # If it consumes 1 (eg. arg is an option that takes no arguments),
1339 # then after _process_arg() is done the situation is:
1341 # largs = subset of [arg0, ..., arg(i)]
1342 # rargs = [arg(i+1), ..., arg(N-1)]
1344 # If allow_interspersed_args is false, largs will always be
1345 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1346 # not a very interesting subset!
1348 def _match_long_opt(self, opt):
1349 """_match_long_opt(opt : string) -> string
1351 Determine which long option string 'opt' matches, ie. which one
1352 it is an unambiguous abbrevation for. Raises BadOptionError if
1353 'opt' doesn't unambiguously match any long option string.
1355 return _match_abbrev(opt, self._long_opt)
1357 def _process_long_opt(self, rargs, values):
1358 arg = rargs.pop(0)
1360 # Value explicitly attached to arg? Pretend it's the next
1361 # argument.
1362 if "=" in arg:
1363 (opt, next_arg) = arg.split("=", 1)
1364 rargs.insert(0, next_arg)
1365 had_explicit_value = True
1366 else:
1367 opt = arg
1368 had_explicit_value = False
1370 opt = self._match_long_opt(opt)
1371 option = self._long_opt[opt]
1372 if option.takes_value():
1373 nargs = option.nargs
1374 if len(rargs) < nargs:
1375 if nargs == 1:
1376 self.error(_("%s option requires an argument") % opt)
1377 else:
1378 self.error(_("%s option requires %d arguments")
1379 % (opt, nargs))
1380 elif nargs == 1:
1381 value = rargs.pop(0)
1382 else:
1383 value = tuple(rargs[0:nargs])
1384 del rargs[0:nargs]
1386 elif had_explicit_value:
1387 self.error(_("%s option does not take a value") % opt)
1389 else:
1390 value = None
1392 option.process(opt, value, values, self)
1394 def _process_short_opts(self, rargs, values):
1395 arg = rargs.pop(0)
1396 stop = False
1397 i = 1
1398 for ch in arg[1:]:
1399 opt = "-" + ch
1400 option = self._short_opt.get(opt)
1401 i += 1 # we have consumed a character
1403 if not option:
1404 self.error(_("no such option: %s") % opt)
1405 if option.takes_value():
1406 # Any characters left in arg? Pretend they're the
1407 # next arg, and stop consuming characters of arg.
1408 if i < len(arg):
1409 rargs.insert(0, arg[i:])
1410 stop = True
1412 nargs = option.nargs
1413 if len(rargs) < nargs:
1414 if nargs == 1:
1415 self.error(_("%s option requires an argument") % opt)
1416 else:
1417 self.error(_("%s option requires %d arguments")
1418 % (opt, nargs))
1419 elif nargs == 1:
1420 value = rargs.pop(0)
1421 else:
1422 value = tuple(rargs[0:nargs])
1423 del rargs[0:nargs]
1425 else: # option doesn't take a value
1426 value = None
1428 option.process(opt, value, values, self)
1430 if stop:
1431 break
1434 # -- Feedback methods ----------------------------------------------
1436 def get_prog_name(self):
1437 if self.prog is None:
1438 return os.path.basename(sys.argv[0])
1439 else:
1440 return self.prog
1442 def expand_prog_name(self, s):
1443 return s.replace("%prog", self.get_prog_name())
1445 def get_description(self):
1446 return self.expand_prog_name(self.description)
1448 def exit(self, status=0, msg=None):
1449 if msg:
1450 sys.stderr.write(msg)
1451 sys.exit(status)
1453 def error(self, msg):
1454 """error(msg : string)
1456 Print a usage message incorporating 'msg' to stderr and exit.
1457 If you override this in a subclass, it should not return -- it
1458 should either exit or raise an exception.
1460 self.print_usage(sys.stderr)
1461 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
1463 def get_usage(self):
1464 if self.usage:
1465 return self.formatter.format_usage(
1466 self.expand_prog_name(self.usage))
1467 else:
1468 return ""
1470 def print_usage(self, file=None):
1471 """print_usage(file : file = stdout)
1473 Print the usage message for the current program (self.usage) to
1474 'file' (default stdout). Any occurence of the string "%prog" in
1475 self.usage is replaced with the name of the current program
1476 (basename of sys.argv[0]). Does nothing if self.usage is empty
1477 or not defined.
1479 if self.usage:
1480 print >>file, self.get_usage()
1482 def get_version(self):
1483 if self.version:
1484 return self.expand_prog_name(self.version)
1485 else:
1486 return ""
1488 def print_version(self, file=None):
1489 """print_version(file : file = stdout)
1491 Print the version message for this program (self.version) to
1492 'file' (default stdout). As with print_usage(), any occurence
1493 of "%prog" in self.version is replaced by the current program's
1494 name. Does nothing if self.version is empty or undefined.
1496 if self.version:
1497 print >>file, self.get_version()
1499 def format_option_help(self, formatter=None):
1500 if formatter is None:
1501 formatter = self.formatter
1502 formatter.store_option_strings(self)
1503 result = []
1504 result.append(formatter.format_heading(_("options")))
1505 formatter.indent()
1506 if self.option_list:
1507 result.append(OptionContainer.format_option_help(self, formatter))
1508 result.append("\n")
1509 for group in self.option_groups:
1510 result.append(group.format_help(formatter))
1511 result.append("\n")
1512 formatter.dedent()
1513 # Drop the last "\n", or the header if no options or option groups:
1514 return "".join(result[:-1])
1516 def format_help(self, formatter=None):
1517 if formatter is None:
1518 formatter = self.formatter
1519 result = []
1520 if self.usage:
1521 result.append(self.get_usage() + "\n")
1522 if self.description:
1523 result.append(self.format_description(formatter) + "\n")
1524 result.append(self.format_option_help(formatter))
1525 return "".join(result)
1527 def print_help(self, file=None):
1528 """print_help(file : file = stdout)
1530 Print an extended help message, listing all options and any
1531 help text provided with them, to 'file' (default stdout).
1533 if file is None:
1534 file = sys.stdout
1535 file.write(self.format_help())
1537 # class OptionParser
1540 def _match_abbrev(s, wordmap):
1541 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1543 Return the string key in 'wordmap' for which 's' is an unambiguous
1544 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1545 'words', raise BadOptionError.
1547 # Is there an exact match?
1548 if wordmap.has_key(s):
1549 return s
1550 else:
1551 # Isolate all words with s as a prefix.
1552 possibilities = [word for word in wordmap.keys()
1553 if word.startswith(s)]
1554 # No exact match, so there had better be just one possibility.
1555 if len(possibilities) == 1:
1556 return possibilities[0]
1557 elif not possibilities:
1558 raise BadOptionError(_("no such option: %s") % s)
1559 else:
1560 # More than one possible completion: ambiguous prefix.
1561 raise BadOptionError(_("ambiguous option: %s (%s?)")
1562 % (s, ", ".join(possibilities)))
1565 # Some day, there might be many Option classes. As of Optik 1.3, the
1566 # preferred way to instantiate Options is indirectly, via make_option(),
1567 # which will become a factory function when there are many Option
1568 # classes.
1569 make_option = Option