Release 0.5: set version number to 0.5
[docutils.git] / extras / optparse.py
blobc21663c555b27e62b5d1f8f8b126a9bd979f2315
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.4.1+"
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-2003 Gregory P. Ward. All rights reserved.
39 Copyright (c) 2002-2003 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 types
71 import textwrap
73 # This file was generated from:
74 # Id: option_parser.py,v 1.57 2003/08/27 02:35:41 goodger Exp
75 # Id: option.py,v 1.26 2003/05/08 01:20:36 gward Exp
76 # Id: help.py,v 1.6 2003/08/27 02:35:41 goodger Exp
77 # Id: errors.py,v 1.7 2003/04/21 01:53:28 gward Exp
79 class OptParseError (Exception):
80 def __init__ (self, msg):
81 self.msg = msg
83 def __str__ (self):
84 return self.msg
87 class OptionError (OptParseError):
88 """
89 Raised if an Option instance is created with invalid or
90 inconsistent arguments.
91 """
93 def __init__ (self, msg, option):
94 self.msg = msg
95 self.option_id = str(option)
97 def __str__ (self):
98 if self.option_id:
99 return "option %s: %s" % (self.option_id, self.msg)
100 else:
101 return self.msg
103 class OptionConflictError (OptionError):
105 Raised if conflicting options are added to an OptionParser.
108 class OptionValueError (OptParseError):
110 Raised if an invalid option value is encountered on the command
111 line.
114 class BadOptionError (OptParseError):
116 Raised if an invalid or ambiguous option is seen on the command-line.
120 class HelpFormatter:
123 Abstract base class for formatting option help. OptionParser
124 instances should use one of the HelpFormatter subclasses for
125 formatting help; by default IndentedHelpFormatter is used.
127 Instance attributes:
128 indent_increment : int
129 the number of columns to indent per nesting level
130 max_help_position : int
131 the maximum starting column for option help text
132 help_position : int
133 the calculated starting column for option help text;
134 initially the same as the maximum
135 width : int
136 total number of columns for output
137 level : int
138 current indentation level
139 current_indent : int
140 current indentation level (in columns)
141 help_width : int
142 number of columns available for option help text (calculated)
145 def __init__ (self,
146 indent_increment,
147 max_help_position,
148 width,
149 short_first):
150 self.indent_increment = indent_increment
151 self.help_position = self.max_help_position = max_help_position
152 self.width = width
153 self.current_indent = 0
154 self.level = 0
155 self.help_width = width - max_help_position
156 self.short_first = short_first
158 def indent (self):
159 self.current_indent += self.indent_increment
160 self.level += 1
162 def dedent (self):
163 self.current_indent -= self.indent_increment
164 assert self.current_indent >= 0, "Indent decreased below 0."
165 self.level -= 1
167 def format_usage (self, usage):
168 raise NotImplementedError, "subclasses must implement"
170 def format_heading (self, heading):
171 raise NotImplementedError, "subclasses must implement"
173 def format_description (self, description):
174 desc_width = self.width - self.current_indent
175 indent = " "*self.current_indent
176 return textwrap.fill(description, desc_width,
177 initial_indent=indent,
178 subsequent_indent=indent) + "\n"
180 def format_option (self, option):
181 # The help for each option consists of two parts:
182 # * the opt strings and metavars
183 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
184 # * the user-supplied help string
185 # eg. ("turn on expert mode", "read data from FILENAME")
187 # If possible, we write both of these on the same line:
188 # -x turn on expert mode
190 # But if the opt string list is too long, we put the help
191 # string on a second line, indented to the same column it would
192 # start in if it fit on the first line.
193 # -fFILENAME, --file=FILENAME
194 # read data from FILENAME
195 result = []
196 opts = option.option_strings
197 opt_width = self.help_position - self.current_indent - 2
198 if len(opts) > opt_width:
199 opts = "%*s%s\n" % (self.current_indent, "", opts)
200 indent_first = self.help_position
201 else: # start help on same line as opts
202 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
203 indent_first = 0
204 result.append(opts)
205 if option.help:
206 help_lines = textwrap.wrap(option.help, self.help_width)
207 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
208 result.extend(["%*s%s\n" % (self.help_position, "", line)
209 for line in help_lines[1:]])
210 elif opts[-1] != "\n":
211 result.append("\n")
212 return "".join(result)
214 def store_option_strings (self, parser):
215 self.indent()
216 max_len = 0
217 for opt in parser.option_list:
218 strings = self.format_option_strings(opt)
219 opt.option_strings = strings
220 max_len = max(max_len, len(strings) + self.current_indent)
221 self.indent()
222 for group in parser.option_groups:
223 for opt in group.option_list:
224 strings = self.format_option_strings(opt)
225 opt.option_strings = strings
226 max_len = max(max_len, len(strings) + self.current_indent)
227 self.dedent()
228 self.dedent()
229 self.help_position = min(max_len + 2, self.max_help_position)
231 def format_option_strings (self, option):
232 """Return a comma-separated list of option strings & metavariables."""
233 if option.takes_value():
234 metavar = option.metavar or option.dest.upper()
235 short_opts = [sopt + metavar for sopt in option._short_opts]
236 long_opts = [lopt + "=" + metavar for lopt in option._long_opts]
237 else:
238 short_opts = option._short_opts
239 long_opts = option._long_opts
241 if self.short_first:
242 opts = short_opts + long_opts
243 else:
244 opts = long_opts + short_opts
246 return ", ".join(opts)
248 class IndentedHelpFormatter (HelpFormatter):
249 """Format help with indented section bodies.
252 def __init__ (self,
253 indent_increment=2,
254 max_help_position=24,
255 width=78,
256 short_first=1):
257 HelpFormatter.__init__(
258 self, indent_increment, max_help_position, width, short_first)
260 def format_usage (self, usage):
261 return "usage: %s\n" % usage
263 def format_heading (self, heading):
264 return "%*s%s:\n" % (self.current_indent, "", heading)
267 class TitledHelpFormatter (HelpFormatter):
268 """Format help with underlined section headers.
271 def __init__ (self,
272 indent_increment=0,
273 max_help_position=24,
274 width=78,
275 short_first=0):
276 HelpFormatter.__init__ (
277 self, indent_increment, max_help_position, width, short_first)
279 def format_usage (self, usage):
280 return "%s %s\n" % (self.format_heading("Usage"), usage)
282 def format_heading (self, heading):
283 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
286 # Do the right thing with boolean values for all known Python versions.
287 try:
288 True, False
289 except NameError:
290 (True, False) = (1, 0)
292 _builtin_cvt = { "int" : (int, "integer"),
293 "long" : (long, "long integer"),
294 "float" : (float, "floating-point"),
295 "complex" : (complex, "complex") }
297 def check_builtin (option, opt, value):
298 (cvt, what) = _builtin_cvt[option.type]
299 try:
300 return cvt(value)
301 except ValueError:
302 raise OptionValueError(
303 #"%s: invalid %s argument %r" % (opt, what, value))
304 "option %s: invalid %s value: %r" % (opt, what, value))
306 def check_choice(option, opt, value):
307 if value in option.choices:
308 return value
309 else:
310 choices = ", ".join(map(repr, option.choices))
311 raise OptionValueError(
312 "option %s: invalid choice: %r (choose from %s)"
313 % (opt, value, choices))
315 # Not supplying a default is different from a default of None,
316 # so we need an explicit "not supplied" value.
317 NO_DEFAULT = "NO"+"DEFAULT"
320 class Option:
322 Instance attributes:
323 _short_opts : [string]
324 _long_opts : [string]
326 action : string
327 type : string
328 dest : string
329 default : any
330 nargs : int
331 const : any
332 choices : [string]
333 callback : function
334 callback_args : (any*)
335 callback_kwargs : { string : any }
336 help : string
337 metavar : string
340 # The list of instance attributes that may be set through
341 # keyword args to the constructor.
342 ATTRS = ['action',
343 'type',
344 'dest',
345 'default',
346 'nargs',
347 'const',
348 'choices',
349 'callback',
350 'callback_args',
351 'callback_kwargs',
352 'help',
353 'metavar']
355 # The set of actions allowed by option parsers. Explicitly listed
356 # here so the constructor can validate its arguments.
357 ACTIONS = ("store",
358 "store_const",
359 "store_true",
360 "store_false",
361 "append",
362 "count",
363 "callback",
364 "help",
365 "version")
367 # The set of actions that involve storing a value somewhere;
368 # also listed just for constructor argument validation. (If
369 # the action is one of these, there must be a destination.)
370 STORE_ACTIONS = ("store",
371 "store_const",
372 "store_true",
373 "store_false",
374 "append",
375 "count")
377 # The set of actions for which it makes sense to supply a value
378 # type, ie. where we expect an argument to this option.
379 TYPED_ACTIONS = ("store",
380 "append",
381 "callback")
383 # The set of known types for option parsers. Again, listed here for
384 # constructor argument validation.
385 TYPES = ("string", "int", "long", "float", "complex", "choice")
387 # Dictionary of argument checking functions, which convert and
388 # validate option arguments according to the option type.
390 # Signature of checking functions is:
391 # check(option : Option, opt : string, value : string) -> any
392 # where
393 # option is the Option instance calling the checker
394 # opt is the actual option seen on the command-line
395 # (eg. "-a", "--file")
396 # value is the option argument seen on the command-line
398 # The return value should be in the appropriate Python type
399 # for option.type -- eg. an integer if option.type == "int".
401 # If no checker is defined for a type, arguments will be
402 # unchecked and remain strings.
403 TYPE_CHECKER = { "int" : check_builtin,
404 "long" : check_builtin,
405 "float" : check_builtin,
406 "complex" : check_builtin,
407 "choice" : check_choice,
411 # CHECK_METHODS is a list of unbound method objects; they are called
412 # by the constructor, in order, after all attributes are
413 # initialized. The list is created and filled in later, after all
414 # the methods are actually defined. (I just put it here because I
415 # like to define and document all class attributes in the same
416 # place.) Subclasses that add another _check_*() method should
417 # define their own CHECK_METHODS list that adds their check method
418 # to those from this class.
419 CHECK_METHODS = None
422 # -- Constructor/initialization methods ----------------------------
424 def __init__ (self, *opts, **attrs):
425 # Set _short_opts, _long_opts attrs from 'opts' tuple.
426 # Have to be set now, in case no option strings are supplied.
427 self._short_opts = []
428 self._long_opts = []
429 opts = self._check_opt_strings(opts)
430 self._set_opt_strings(opts)
432 # Set all other attrs (action, type, etc.) from 'attrs' dict
433 self._set_attrs(attrs)
435 # Check all the attributes we just set. There are lots of
436 # complicated interdependencies, but luckily they can be farmed
437 # out to the _check_*() methods listed in CHECK_METHODS -- which
438 # could be handy for subclasses! The one thing these all share
439 # is that they raise OptionError if they discover a problem.
440 for checker in self.CHECK_METHODS:
441 checker(self)
443 def _check_opt_strings (self, opts):
444 # Filter out None because early versions of Optik had exactly
445 # one short option and one long option, either of which
446 # could be None.
447 opts = filter(None, opts)
448 if not opts:
449 raise TypeError("at least one option string must be supplied")
450 return opts
452 def _set_opt_strings (self, opts):
453 for opt in opts:
454 if len(opt) < 2:
455 raise OptionError(
456 "invalid option string %r: "
457 "must be at least two characters long" % opt, self)
458 elif len(opt) == 2:
459 if not (opt[0] == "-" and opt[1] != "-"):
460 raise OptionError(
461 "invalid short option string %r: "
462 "must be of the form -x, (x any non-dash char)" % opt,
463 self)
464 self._short_opts.append(opt)
465 else:
466 if not (opt[0:2] == "--" and opt[2] != "-"):
467 raise OptionError(
468 "invalid long option string %r: "
469 "must start with --, followed by non-dash" % opt,
470 self)
471 self._long_opts.append(opt)
473 def _set_attrs (self, attrs):
474 for attr in self.ATTRS:
475 if attrs.has_key(attr):
476 setattr(self, attr, attrs[attr])
477 del attrs[attr]
478 else:
479 if attr == 'default':
480 setattr(self, attr, NO_DEFAULT)
481 else:
482 setattr(self, attr, None)
483 if attrs:
484 raise OptionError(
485 "invalid keyword arguments: %s" % ", ".join(attrs.keys()),
486 self)
489 # -- Constructor validation methods --------------------------------
491 def _check_action (self):
492 if self.action is None:
493 self.action = "store"
494 elif self.action not in self.ACTIONS:
495 raise OptionError("invalid action: %r" % self.action, self)
497 def _check_type (self):
498 if self.type is None:
499 # XXX should factor out another class attr here: list of
500 # actions that *require* a type
501 if self.action in ("store", "append"):
502 if self.choices is not None:
503 # The "choices" attribute implies "choice" type.
504 self.type = "choice"
505 else:
506 # No type given? "string" is the most sensible default.
507 self.type = "string"
508 else:
509 if self.type not in self.TYPES:
510 raise OptionError("invalid option type: %r" % self.type, self)
511 if self.action not in self.TYPED_ACTIONS:
512 raise OptionError(
513 "must not supply a type for action %r" % self.action, self)
515 def _check_choice(self):
516 if self.type == "choice":
517 if self.choices is None:
518 raise OptionError(
519 "must supply a list of choices for type 'choice'", self)
520 elif type(self.choices) not in (types.TupleType, types.ListType):
521 raise OptionError(
522 "choices must be a list of strings ('%s' supplied)"
523 % str(type(self.choices)).split("'")[1], self)
524 elif self.choices is not None:
525 raise OptionError(
526 "must not supply choices for type %r" % self.type, self)
528 def _check_dest (self):
529 if self.action in self.STORE_ACTIONS and self.dest is None:
530 # No destination given, and we need one for this action.
531 # Glean a destination from the first long option string,
532 # or from the first short option string if no long options.
533 if self._long_opts:
534 # eg. "--foo-bar" -> "foo_bar"
535 self.dest = self._long_opts[0][2:].replace('-', '_')
536 else:
537 self.dest = self._short_opts[0][1]
539 def _check_const (self):
540 if self.action != "store_const" and self.const is not None:
541 raise OptionError(
542 "'const' must not be supplied for action %r" % self.action,
543 self)
545 def _check_nargs (self):
546 if self.action in self.TYPED_ACTIONS:
547 if self.nargs is None:
548 self.nargs = 1
549 elif self.nargs is not None:
550 raise OptionError(
551 "'nargs' must not be supplied for action %r" % self.action,
552 self)
554 def _check_callback (self):
555 if self.action == "callback":
556 if not callable(self.callback):
557 raise OptionError(
558 "callback not callable: %r" % self.callback, self)
559 if (self.callback_args is not None and
560 type(self.callback_args) is not types.TupleType):
561 raise OptionError(
562 "callback_args, if supplied, must be a tuple: not %r"
563 % self.callback_args, self)
564 if (self.callback_kwargs is not None and
565 type(self.callback_kwargs) is not types.DictType):
566 raise OptionError(
567 "callback_kwargs, if supplied, must be a dict: not %r"
568 % self.callback_kwargs, self)
569 else:
570 if self.callback is not None:
571 raise OptionError(
572 "callback supplied (%r) for non-callback option"
573 % self.callback, self)
574 if self.callback_args is not None:
575 raise OptionError(
576 "callback_args supplied for non-callback option", self)
577 if self.callback_kwargs is not None:
578 raise OptionError(
579 "callback_kwargs supplied for non-callback option", self)
582 CHECK_METHODS = [_check_action,
583 _check_type,
584 _check_choice,
585 _check_dest,
586 _check_const,
587 _check_nargs,
588 _check_callback]
591 # -- Miscellaneous methods -----------------------------------------
593 def __str__ (self):
594 return "/".join(self._short_opts + self._long_opts)
596 def takes_value (self):
597 return self.type is not None
600 # -- Processing methods --------------------------------------------
602 def check_value (self, opt, value):
603 checker = self.TYPE_CHECKER.get(self.type)
604 if checker is None:
605 return value
606 else:
607 return checker(self, opt, value)
609 def process (self, opt, value, values, parser):
611 # First, convert the value(s) to the right type. Howl if any
612 # value(s) are bogus.
613 if value is not None:
614 if self.nargs == 1:
615 value = self.check_value(opt, value)
616 else:
617 value = tuple([self.check_value(opt, v) for v in value])
619 # And then take whatever action is expected of us.
620 # This is a separate method to make life easier for
621 # subclasses to add new actions.
622 return self.take_action(
623 self.action, self.dest, opt, value, values, parser)
625 def take_action (self, action, dest, opt, value, values, parser):
626 if action == "store":
627 setattr(values, dest, value)
628 elif action == "store_const":
629 setattr(values, dest, self.const)
630 elif action == "store_true":
631 setattr(values, dest, True)
632 elif action == "store_false":
633 setattr(values, dest, False)
634 elif action == "append":
635 values.ensure_value(dest, []).append(value)
636 elif action == "count":
637 setattr(values, dest, values.ensure_value(dest, 0) + 1)
638 elif action == "callback":
639 args = self.callback_args or ()
640 kwargs = self.callback_kwargs or {}
641 self.callback(self, opt, value, parser, *args, **kwargs)
642 elif action == "help":
643 parser.print_help()
644 sys.exit(0)
645 elif action == "version":
646 parser.print_version()
647 sys.exit(0)
648 else:
649 raise RuntimeError, "unknown action %r" % self.action
651 return 1
653 # class Option
656 SUPPRESS_HELP = "SUPPRESS"+"HELP"
657 SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
660 class Values:
662 def __init__ (self, defaults=None):
663 if defaults:
664 for (attr, val) in defaults.items():
665 setattr(self, attr, val)
667 def __repr__ (self):
668 return ("<%s at 0x%x: %r>"
669 % (self.__class__.__name__, id(self), self.__dict__))
671 def _update_careful (self, dict):
673 Update the option values from an arbitrary dictionary, but only
674 use keys from dict that already have a corresponding attribute
675 in self. Any keys in dict without a corresponding attribute
676 are silently ignored.
678 for attr in dir(self):
679 if dict.has_key(attr):
680 dval = dict[attr]
681 if dval is not None:
682 setattr(self, attr, dval)
684 def _update_loose (self, dict):
686 Update the option values from an arbitrary dictionary,
687 using all keys from the dictionary regardless of whether
688 they have a corresponding attribute in self or not.
690 self.__dict__.update(dict)
692 def _update (self, dict, mode):
693 if mode == "careful":
694 self._update_careful(dict)
695 elif mode == "loose":
696 self._update_loose(dict)
697 else:
698 raise ValueError, "invalid update mode: %r" % mode
700 def read_module (self, modname, mode="careful"):
701 __import__(modname)
702 mod = sys.modules[modname]
703 self._update(vars(mod), mode)
705 def read_file (self, filename, mode="careful"):
706 vars = {}
707 execfile(filename, vars)
708 self._update(vars, mode)
710 def ensure_value (self, attr, value):
711 if not hasattr(self, attr) or getattr(self, attr) is None:
712 setattr(self, attr, value)
713 return getattr(self, attr)
716 class OptionContainer:
719 Abstract base class.
721 Class attributes:
722 standard_option_list : [Option]
723 list of standard options that will be accepted by all instances
724 of this parser class (intended to be overridden by subclasses).
726 Instance attributes:
727 option_list : [Option]
728 the list of Option objects contained by this OptionContainer
729 _short_opt : { string : Option }
730 dictionary mapping short option strings, eg. "-f" or "-X",
731 to the Option instances that implement them. If an Option
732 has multiple short option strings, it will appears in this
733 dictionary multiple times. [1]
734 _long_opt : { string : Option }
735 dictionary mapping long option strings, eg. "--file" or
736 "--exclude", to the Option instances that implement them.
737 Again, a given Option can occur multiple times in this
738 dictionary. [1]
739 defaults : { string : any }
740 dictionary mapping option destination names to default
741 values for each destination [1]
743 [1] These mappings are common to (shared by) all components of the
744 controlling OptionParser, where they are initially created.
748 def __init__ (self, option_class, conflict_handler, description):
749 # Initialize the option list and related data structures.
750 # This method must be provided by subclasses, and it must
751 # initialize at least the following instance attributes:
752 # option_list, _short_opt, _long_opt, defaults.
753 self._create_option_list()
755 self.option_class = option_class
756 self.set_conflict_handler(conflict_handler)
757 self.set_description(description)
759 def _create_option_mappings (self):
760 # For use by OptionParser constructor -- create the master
761 # option mappings used by this OptionParser and all
762 # OptionGroups that it owns.
763 self._short_opt = {} # single letter -> Option instance
764 self._long_opt = {} # long option -> Option instance
765 self.defaults = {} # maps option dest -> default value
768 def _share_option_mappings (self, parser):
769 # For use by OptionGroup constructor -- use shared option
770 # mappings from the OptionParser that owns this OptionGroup.
771 self._short_opt = parser._short_opt
772 self._long_opt = parser._long_opt
773 self.defaults = parser.defaults
775 def set_conflict_handler (self, handler):
776 if handler not in ("ignore", "error", "resolve"):
777 raise ValueError, "invalid conflict_resolution value %r" % handler
778 self.conflict_handler = handler
780 def set_description (self, description):
781 self.description = description
784 # -- Option-adding methods -----------------------------------------
786 def _check_conflict (self, option):
787 conflict_opts = []
788 for opt in option._short_opts:
789 if self._short_opt.has_key(opt):
790 conflict_opts.append((opt, self._short_opt[opt]))
791 for opt in option._long_opts:
792 if self._long_opt.has_key(opt):
793 conflict_opts.append((opt, self._long_opt[opt]))
795 if conflict_opts:
796 handler = self.conflict_handler
797 if handler == "ignore": # behaviour for Optik 1.0, 1.1
798 pass
799 elif handler == "error": # new in 1.2
800 raise OptionConflictError(
801 "conflicting option string(s): %s"
802 % ", ".join([co[0] for co in conflict_opts]),
803 option)
804 elif handler == "resolve": # new in 1.2
805 for (opt, c_option) in conflict_opts:
806 if opt.startswith("--"):
807 c_option._long_opts.remove(opt)
808 del self._long_opt[opt]
809 else:
810 c_option._short_opts.remove(opt)
811 del self._short_opt[opt]
812 if not (c_option._short_opts or c_option._long_opts):
813 c_option.container.option_list.remove(c_option)
815 def add_option (self, *args, **kwargs):
816 """add_option(Option)
817 add_option(opt_str, ..., kwarg=val, ...)
819 if type(args[0]) is types.StringType:
820 option = self.option_class(*args, **kwargs)
821 elif len(args) == 1 and not kwargs:
822 option = args[0]
823 if not isinstance(option, Option):
824 raise TypeError, "not an Option instance: %r" % option
825 else:
826 raise TypeError, "invalid arguments"
828 self._check_conflict(option)
830 self.option_list.append(option)
831 option.container = self
832 for opt in option._short_opts:
833 self._short_opt[opt] = option
834 for opt in option._long_opts:
835 self._long_opt[opt] = option
837 if option.dest is not None: # option has a dest, we need a default
838 if option.default is not NO_DEFAULT:
839 self.defaults[option.dest] = option.default
840 elif not self.defaults.has_key(option.dest):
841 self.defaults[option.dest] = None
843 return option
845 def add_options (self, option_list):
846 for option in option_list:
847 self.add_option(option)
849 # -- Option query/removal methods ----------------------------------
851 def get_option (self, opt_str):
852 return (self._short_opt.get(opt_str) or
853 self._long_opt.get(opt_str))
855 def has_option (self, opt_str):
856 return (self._short_opt.has_key(opt_str) or
857 self._long_opt.has_key(opt_str))
859 def remove_option (self, opt_str):
860 option = self._short_opt.get(opt_str)
861 if option is None:
862 option = self._long_opt.get(opt_str)
863 if option is None:
864 raise ValueError("no such option %r" % opt_str)
866 for opt in option._short_opts:
867 del self._short_opt[opt]
868 for opt in option._long_opts:
869 del self._long_opt[opt]
870 option.container.option_list.remove(option)
873 # -- Help-formatting methods ---------------------------------------
875 def format_option_help (self, formatter):
876 if not self.option_list:
877 return ""
878 result = []
879 for option in self.option_list:
880 if not option.help is SUPPRESS_HELP:
881 result.append(formatter.format_option(option))
882 return "".join(result)
884 def format_description (self, formatter):
885 if self.description:
886 return formatter.format_description(self.description)
887 else:
888 return ""
890 def format_help (self, formatter):
891 result = []
892 if self.description:
893 result.append(self.format_description(formatter))
894 if self.option_list:
895 result.append(self.format_option_help(formatter))
896 return "\n".join(result)
899 class OptionGroup (OptionContainer):
901 def __init__ (self, parser, title, description=None):
902 self.parser = parser
903 OptionContainer.__init__(
904 self, parser.option_class, parser.conflict_handler, description)
905 self.title = title
907 def _create_option_list (self):
908 self.option_list = []
909 self._share_option_mappings(self.parser)
911 def set_title (self, title):
912 self.title = title
914 # -- Help-formatting methods ---------------------------------------
916 def format_help (self, formatter):
917 result = formatter.format_heading(self.title)
918 formatter.indent()
919 result += OptionContainer.format_help(self, formatter)
920 formatter.dedent()
921 return result
924 class OptionParser (OptionContainer):
927 Class attributes:
928 standard_option_list : [Option]
929 list of standard options that will be accepted by all instances
930 of this parser class (intended to be overridden by subclasses).
932 Instance attributes:
933 usage : string
934 a usage string for your program. Before it is displayed
935 to the user, "%prog" will be expanded to the name of
936 your program (self.prog or os.path.basename(sys.argv[0])).
937 prog : string
938 the name of the current program (to override
939 os.path.basename(sys.argv[0])).
941 allow_interspersed_args : boolean = true
942 if true, positional arguments may be interspersed with options.
943 Assuming -a and -b each take a single argument, the command-line
944 -ablah foo bar -bboo baz
945 will be interpreted the same as
946 -ablah -bboo -- foo bar baz
947 If this flag were false, that command line would be interpreted as
948 -ablah -- foo bar -bboo baz
949 -- ie. we stop processing options as soon as we see the first
950 non-option argument. (This is the tradition followed by
951 Python's getopt module, Perl's Getopt::Std, and other argument-
952 parsing libraries, but it is generally annoying to users.)
954 rargs : [string]
955 the argument list currently being parsed. Only set when
956 parse_args() is active, and continually trimmed down as
957 we consume arguments. Mainly there for the benefit of
958 callback options.
959 largs : [string]
960 the list of leftover arguments that we have skipped while
961 parsing options. If allow_interspersed_args is false, this
962 list is always empty.
963 values : Values
964 the set of option values currently being accumulated. Only
965 set when parse_args() is active. Also mainly for callbacks.
967 Because of the 'rargs', 'largs', and 'values' attributes,
968 OptionParser is not thread-safe. If, for some perverse reason, you
969 need to parse command-line arguments simultaneously in different
970 threads, use different OptionParser instances.
974 standard_option_list = []
976 def __init__ (self,
977 usage=None,
978 option_list=None,
979 option_class=Option,
980 version=None,
981 conflict_handler="error",
982 description=None,
983 formatter=None,
984 add_help_option=1,
985 prog=None):
986 OptionContainer.__init__(
987 self, option_class, conflict_handler, description)
988 self.set_usage(usage)
989 self.prog = prog
990 self.version = version
991 self.allow_interspersed_args = 1
992 if formatter is None:
993 formatter = IndentedHelpFormatter()
994 self.formatter = formatter
996 # Populate the option list; initial sources are the
997 # standard_option_list class attribute, the 'option_list'
998 # argument, and (if applicable) the _add_version_option() and
999 # _add_help_option() methods.
1000 self._populate_option_list(option_list,
1001 add_help=add_help_option)
1003 self._init_parsing_state()
1005 # -- Private methods -----------------------------------------------
1006 # (used by our or OptionContainer's constructor)
1008 def _create_option_list (self):
1009 self.option_list = []
1010 self.option_groups = []
1011 self._create_option_mappings()
1013 def _add_help_option (self):
1014 self.add_option("-h", "--help",
1015 action="help",
1016 help="show this help message and exit")
1018 def _add_version_option (self):
1019 self.add_option("--version",
1020 action="version",
1021 help="show program's version number and exit")
1023 def _populate_option_list (self, option_list, add_help=1):
1024 if self.standard_option_list:
1025 self.add_options(self.standard_option_list)
1026 if option_list:
1027 self.add_options(option_list)
1028 if self.version:
1029 self._add_version_option()
1030 if add_help:
1031 self._add_help_option()
1033 def _init_parsing_state (self):
1034 # These are set in parse_args() for the convenience of callbacks.
1035 self.rargs = None
1036 self.largs = None
1037 self.values = None
1040 # -- Simple modifier methods ---------------------------------------
1042 def set_usage (self, usage):
1043 if usage is None:
1044 self.usage = "%prog [options]"
1045 elif usage is SUPPRESS_USAGE:
1046 self.usage = None
1047 elif usage.startswith("usage: "):
1048 # for backwards compatibility with Optik 1.3 and earlier
1049 self.usage = usage[7:]
1050 else:
1051 self.usage = usage
1053 def enable_interspersed_args (self):
1054 self.allow_interspersed_args = 1
1056 def disable_interspersed_args (self):
1057 self.allow_interspersed_args = 0
1059 def set_default (self, dest, value):
1060 self.defaults[dest] = value
1062 def set_defaults (self, **kwargs):
1063 self.defaults.update(kwargs)
1065 def get_default_values (self):
1066 return Values(self.defaults)
1069 # -- OptionGroup methods -------------------------------------------
1071 def add_option_group (self, *args, **kwargs):
1072 # XXX lots of overlap with OptionContainer.add_option()
1073 if type(args[0]) is types.StringType:
1074 group = OptionGroup(self, *args, **kwargs)
1075 elif len(args) == 1 and not kwargs:
1076 group = args[0]
1077 if not isinstance(group, OptionGroup):
1078 raise TypeError, "not an OptionGroup instance: %r" % group
1079 if group.parser is not self:
1080 raise ValueError, "invalid OptionGroup (wrong parser)"
1081 else:
1082 raise TypeError, "invalid arguments"
1084 self.option_groups.append(group)
1085 return group
1087 def get_option_group (self, opt_str):
1088 option = (self._short_opt.get(opt_str) or
1089 self._long_opt.get(opt_str))
1090 if option and option.container is not self:
1091 return option.container
1092 return None
1095 # -- Option-parsing methods ----------------------------------------
1097 def _get_args (self, args):
1098 if args is None:
1099 return sys.argv[1:]
1100 else:
1101 return args[:] # don't modify caller's list
1103 def parse_args (self, args=None, values=None):
1105 parse_args(args : [string] = sys.argv[1:],
1106 values : Values = None)
1107 -> (values : Values, args : [string])
1109 Parse the command-line options found in 'args' (default:
1110 sys.argv[1:]). Any errors result in a call to 'error()', which
1111 by default prints the usage message to stderr and calls
1112 sys.exit() with an error message. On success returns a pair
1113 (values, args) where 'values' is an Values instance (with all
1114 your option values) and 'args' is the list of arguments left
1115 over after parsing options.
1117 rargs = self._get_args(args)
1118 if values is None:
1119 values = self.get_default_values()
1121 # Store the halves of the argument list as attributes for the
1122 # convenience of callbacks:
1123 # rargs
1124 # the rest of the command-line (the "r" stands for
1125 # "remaining" or "right-hand")
1126 # largs
1127 # the leftover arguments -- ie. what's left after removing
1128 # options and their arguments (the "l" stands for "leftover"
1129 # or "left-hand")
1130 self.rargs = rargs
1131 self.largs = largs = []
1132 self.values = values
1134 try:
1135 stop = self._process_args(largs, rargs, values)
1136 except (BadOptionError, OptionValueError), err:
1137 self.error(err.msg)
1139 args = largs + rargs
1140 return self.check_values(values, args)
1142 def check_values (self, values, args):
1144 check_values(values : Values, args : [string])
1145 -> (values : Values, args : [string])
1147 Check that the supplied option values and leftover arguments are
1148 valid. Returns the option values and leftover arguments
1149 (possibly adjusted, possibly completely new -- whatever you
1150 like). Default implementation just returns the passed-in
1151 values; subclasses may override as desired.
1153 return (values, args)
1155 def _process_args (self, largs, rargs, values):
1156 """_process_args(largs : [string],
1157 rargs : [string],
1158 values : Values)
1160 Process command-line arguments and populate 'values', consuming
1161 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1162 false, stop at the first non-option argument. If true, accumulate any
1163 interspersed non-option arguments in 'largs'.
1165 while rargs:
1166 arg = rargs[0]
1167 # We handle bare "--" explicitly, and bare "-" is handled by the
1168 # standard arg handler since the short arg case ensures that the
1169 # len of the opt string is greater than 1.
1170 if arg == "--":
1171 del rargs[0]
1172 return
1173 elif arg[0:2] == "--":
1174 # process a single long option (possibly with value(s))
1175 self._process_long_opt(rargs, values)
1176 elif arg[:1] == "-" and len(arg) > 1:
1177 # process a cluster of short options (possibly with
1178 # value(s) for the last one only)
1179 self._process_short_opts(rargs, values)
1180 elif self.allow_interspersed_args:
1181 largs.append(arg)
1182 del rargs[0]
1183 else:
1184 return # stop now, leave this arg in rargs
1186 # Say this is the original argument list:
1187 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1189 # (we are about to process arg(i)).
1191 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1192 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1193 # been removed from largs).
1195 # The while loop will usually consume 1 or more arguments per pass.
1196 # If it consumes 1 (eg. arg is an option that takes no arguments),
1197 # then after _process_arg() is done the situation is:
1199 # largs = subset of [arg0, ..., arg(i)]
1200 # rargs = [arg(i+1), ..., arg(N-1)]
1202 # If allow_interspersed_args is false, largs will always be
1203 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1204 # not a very interesting subset!
1206 def _match_long_opt (self, opt):
1207 """_match_long_opt(opt : string) -> string
1209 Determine which long option string 'opt' matches, ie. which one
1210 it is an unambiguous abbrevation for. Raises BadOptionError if
1211 'opt' doesn't unambiguously match any long option string.
1213 return _match_abbrev(opt, self._long_opt)
1215 def _process_long_opt (self, rargs, values):
1216 arg = rargs.pop(0)
1218 # Value explicitly attached to arg? Pretend it's the next
1219 # argument.
1220 if "=" in arg:
1221 (opt, next_arg) = arg.split("=", 1)
1222 rargs.insert(0, next_arg)
1223 had_explicit_value = 1
1224 else:
1225 opt = arg
1226 had_explicit_value = 0
1228 opt = self._match_long_opt(opt)
1229 option = self._long_opt[opt]
1230 if option.takes_value():
1231 nargs = option.nargs
1232 if len(rargs) < nargs:
1233 if nargs == 1:
1234 self.error("%s option requires a value" % opt)
1235 else:
1236 self.error("%s option requires %d values"
1237 % (opt, nargs))
1238 elif nargs == 1:
1239 value = rargs.pop(0)
1240 else:
1241 value = tuple(rargs[0:nargs])
1242 del rargs[0:nargs]
1244 elif had_explicit_value:
1245 self.error("%s option does not take a value" % opt)
1247 else:
1248 value = None
1250 option.process(opt, value, values, self)
1252 def _process_short_opts (self, rargs, values):
1253 arg = rargs.pop(0)
1254 stop = 0
1255 i = 1
1256 for ch in arg[1:]:
1257 opt = "-" + ch
1258 option = self._short_opt.get(opt)
1259 i += 1 # we have consumed a character
1261 if not option:
1262 self.error("no such option: %s" % opt)
1263 if option.takes_value():
1264 # Any characters left in arg? Pretend they're the
1265 # next arg, and stop consuming characters of arg.
1266 if i < len(arg):
1267 rargs.insert(0, arg[i:])
1268 stop = 1
1270 nargs = option.nargs
1271 if len(rargs) < nargs:
1272 if nargs == 1:
1273 self.error("%s option requires a value" % opt)
1274 else:
1275 self.error("%s option requires %s values"
1276 % (opt, nargs))
1277 elif nargs == 1:
1278 value = rargs.pop(0)
1279 else:
1280 value = tuple(rargs[0:nargs])
1281 del rargs[0:nargs]
1283 else: # option doesn't take a value
1284 value = None
1286 option.process(opt, value, values, self)
1288 if stop:
1289 break
1292 # -- Feedback methods ----------------------------------------------
1294 def get_prog_name (self):
1295 if self.prog is None:
1296 return os.path.basename(sys.argv[0])
1297 else:
1298 return self.prog
1300 def error (self, msg):
1301 """error(msg : string)
1303 Print a usage message incorporating 'msg' to stderr and exit.
1304 If you override this in a subclass, it should not return -- it
1305 should either exit or raise an exception.
1307 self.print_usage(sys.stderr)
1308 sys.stderr.write("%s: error: %s\n" % (self.get_prog_name(), msg))
1309 sys.exit(2) # command-line usage error
1311 def get_usage (self):
1312 if self.usage:
1313 return self.formatter.format_usage(
1314 self.usage.replace("%prog", self.get_prog_name()))
1315 else:
1316 return ""
1318 def print_usage (self, file=None):
1319 """print_usage(file : file = stdout)
1321 Print the usage message for the current program (self.usage) to
1322 'file' (default stdout). Any occurence of the string "%prog" in
1323 self.usage is replaced with the name of the current program
1324 (basename of sys.argv[0]). Does nothing if self.usage is empty
1325 or not defined.
1327 if self.usage:
1328 print >>file, self.get_usage()
1330 def get_version (self):
1331 if self.version:
1332 return self.version.replace("%prog", self.get_prog_name())
1333 else:
1334 return ""
1336 def print_version (self, file=None):
1337 """print_version(file : file = stdout)
1339 Print the version message for this program (self.version) to
1340 'file' (default stdout). As with print_usage(), any occurence
1341 of "%prog" in self.version is replaced by the current program's
1342 name. Does nothing if self.version is empty or undefined.
1344 if self.version:
1345 print >>file, self.get_version()
1347 def format_option_help (self, formatter=None):
1348 if formatter is None:
1349 formatter = self.formatter
1350 formatter.store_option_strings(self)
1351 result = []
1352 result.append(formatter.format_heading("Options"))
1353 formatter.indent()
1354 if self.option_list:
1355 result.append(OptionContainer.format_option_help(self, formatter))
1356 result.append("\n")
1357 for group in self.option_groups:
1358 result.append(group.format_help(formatter))
1359 result.append("\n")
1360 formatter.dedent()
1361 # Drop the last "\n", or the header if no options or option groups:
1362 return "".join(result[:-1])
1364 def format_help (self, formatter=None):
1365 if formatter is None:
1366 formatter = self.formatter
1367 result = []
1368 if self.usage:
1369 result.append(self.get_usage() + "\n")
1370 if self.description:
1371 result.append(self.format_description(formatter) + "\n")
1372 result.append(self.format_option_help(formatter))
1373 return "".join(result)
1375 def print_help (self, file=None):
1376 """print_help(file : file = stdout)
1378 Print an extended help message, listing all options and any
1379 help text provided with them, to 'file' (default stdout).
1381 if file is None:
1382 file = sys.stdout
1383 file.write(self.format_help())
1385 # class OptionParser
1388 def _match_abbrev (s, wordmap):
1389 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1391 Return the string key in 'wordmap' for which 's' is an unambiguous
1392 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1393 'words', raise BadOptionError.
1395 # Is there an exact match?
1396 if wordmap.has_key(s):
1397 return s
1398 else:
1399 # Isolate all words with s as a prefix.
1400 possibilities = [word for word in wordmap.keys()
1401 if word.startswith(s)]
1402 # No exact match, so there had better be just one possibility.
1403 if len(possibilities) == 1:
1404 return possibilities[0]
1405 elif not possibilities:
1406 raise BadOptionError("no such option: %s" % s)
1407 else:
1408 # More than one possible completion: ambiguous prefix.
1409 raise BadOptionError("ambiguous option: %s (%s?)"
1410 % (s, ", ".join(possibilities)))
1413 # Some day, there might be many Option classes. As of Optik 1.3, the
1414 # preferred way to instantiate Options is indirectly, via make_option(),
1415 # which will become a factory function when there are many Option
1416 # classes.
1417 make_option = Option