OILS / opy / _regtest / src / optparse.py View on Github | oilshell.org

1704 lines, 949 significant
1"""A powerful, extensible, and easy-to-use option parser.
2
3By Greg Ward <gward@python.net>
4
5Originally distributed as Optik.
6
7For support, use the optik-users@lists.sourceforge.net mailing list
8(http://lists.sourceforge.net/lists/listinfo/optik-users).
9
10Simple usage example:
11
12 from optparse import OptionParser
13
14 parser = OptionParser()
15 parser.add_option("-f", "--file", dest="filename",
16 help="write report to FILE", metavar="FILE")
17 parser.add_option("-q", "--quiet",
18 action="store_false", dest="verbose", default=True,
19 help="don't print status messages to stdout")
20
21 (options, args) = parser.parse_args()
22"""
23
24__version__ = "1.5.3"
25
26__all__ = ['Option',
27 'make_option',
28 'SUPPRESS_HELP',
29 'SUPPRESS_USAGE',
30 'Values',
31 'OptionContainer',
32 'OptionGroup',
33 'OptionParser',
34 'HelpFormatter',
35 'IndentedHelpFormatter',
36 'TitledHelpFormatter',
37 'OptParseError',
38 'OptionError',
39 'OptionConflictError',
40 'OptionValueError',
41 'BadOptionError']
42
43__copyright__ = """
44Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
45Copyright (c) 2002-2006 Python Software Foundation. All rights reserved.
46
47Redistribution and use in source and binary forms, with or without
48modification, are permitted provided that the following conditions are
49met:
50
51 * Redistributions of source code must retain the above copyright
52 notice, this list of conditions and the following disclaimer.
53
54 * Redistributions in binary form must reproduce the above copyright
55 notice, this list of conditions and the following disclaimer in the
56 documentation and/or other materials provided with the distribution.
57
58 * Neither the name of the author nor the names of its
59 contributors may be used to endorse or promote products derived from
60 this software without specific prior written permission.
61
62THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
63IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
64TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
65PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
66CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
67EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
68PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
69PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
70LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
71NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
72SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
73"""
74
75import sys, os
76import types
77import textwrap
78
79def _repr(self):
80 return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
81
82
83# This file was generated from:
84# Id: option_parser.py 527 2006-07-23 15:21:30Z greg
85# Id: option.py 522 2006-06-11 16:22:03Z gward
86# Id: help.py 527 2006-07-23 15:21:30Z greg
87# Id: errors.py 509 2006-04-20 00:58:24Z gward
88
89try:
90 from gettext import gettext
91except ImportError:
92 def gettext(message):
93 return message
94_ = gettext
95
96
97class OptParseError (Exception):
98 def __init__(self, msg):
99 self.msg = msg
100
101 def __str__(self):
102 return self.msg
103
104
105class OptionError (OptParseError):
106 """
107 Raised if an Option instance is created with invalid or
108 inconsistent arguments.
109 """
110
111 def __init__(self, msg, option):
112 self.msg = msg
113 self.option_id = str(option)
114
115 def __str__(self):
116 if self.option_id:
117 return "option %s: %s" % (self.option_id, self.msg)
118 else:
119 return self.msg
120
121class OptionConflictError (OptionError):
122 """
123 Raised if conflicting options are added to an OptionParser.
124 """
125
126class OptionValueError (OptParseError):
127 """
128 Raised if an invalid option value is encountered on the command
129 line.
130 """
131
132class BadOptionError (OptParseError):
133 """
134 Raised if an invalid option is seen on the command line.
135 """
136 def __init__(self, opt_str):
137 self.opt_str = opt_str
138
139 def __str__(self):
140 return _("no such option: %s") % self.opt_str
141
142class AmbiguousOptionError (BadOptionError):
143 """
144 Raised if an ambiguous option is seen on the command line.
145 """
146 def __init__(self, opt_str, possibilities):
147 BadOptionError.__init__(self, opt_str)
148 self.possibilities = possibilities
149
150 def __str__(self):
151 return (_("ambiguous option: %s (%s?)")
152 % (self.opt_str, ", ".join(self.possibilities)))
153
154
155class HelpFormatter:
156
157 """
158 Abstract base class for formatting option help. OptionParser
159 instances should use one of the HelpFormatter subclasses for
160 formatting help; by default IndentedHelpFormatter is used.
161
162 Instance attributes:
163 parser : OptionParser
164 the controlling OptionParser instance
165 indent_increment : int
166 the number of columns to indent per nesting level
167 max_help_position : int
168 the maximum starting column for option help text
169 help_position : int
170 the calculated starting column for option help text;
171 initially the same as the maximum
172 width : int
173 total number of columns for output (pass None to constructor for
174 this value to be taken from the $COLUMNS environment variable)
175 level : int
176 current indentation level
177 current_indent : int
178 current indentation level (in columns)
179 help_width : int
180 number of columns available for option help text (calculated)
181 default_tag : str
182 text to replace with each option's default value, "%default"
183 by default. Set to false value to disable default value expansion.
184 option_strings : { Option : str }
185 maps Option instances to the snippet of help text explaining
186 the syntax of that option, e.g. "-h, --help" or
187 "-fFILE, --file=FILE"
188 _short_opt_fmt : str
189 format string controlling how short options with values are
190 printed in help text. Must be either "%s%s" ("-fFILE") or
191 "%s %s" ("-f FILE"), because those are the two syntaxes that
192 Optik supports.
193 _long_opt_fmt : str
194 similar but for long options; must be either "%s %s" ("--file FILE")
195 or "%s=%s" ("--file=FILE").
196 """
197
198 NO_DEFAULT_VALUE = "none"
199
200 def __init__(self,
201 indent_increment,
202 max_help_position,
203 width,
204 short_first):
205 self.parser = None
206 self.indent_increment = indent_increment
207 if width is None:
208 try:
209 width = int(os.environ['COLUMNS'])
210 except (KeyError, ValueError):
211 width = 80
212 width -= 2
213 self.width = width
214 self.help_position = self.max_help_position = \
215 min(max_help_position, max(width - 20, indent_increment * 2))
216 self.current_indent = 0
217 self.level = 0
218 self.help_width = None # computed later
219 self.short_first = short_first
220 self.default_tag = "%default"
221 self.option_strings = {}
222 self._short_opt_fmt = "%s %s"
223 self._long_opt_fmt = "%s=%s"
224
225 def set_parser(self, parser):
226 self.parser = parser
227
228 def set_short_opt_delimiter(self, delim):
229 if delim not in ("", " "):
230 raise ValueError(
231 "invalid metavar delimiter for short options: %r" % delim)
232 self._short_opt_fmt = "%s" + delim + "%s"
233
234 def set_long_opt_delimiter(self, delim):
235 if delim not in ("=", " "):
236 raise ValueError(
237 "invalid metavar delimiter for long options: %r" % delim)
238 self._long_opt_fmt = "%s" + delim + "%s"
239
240 def indent(self):
241 self.current_indent += self.indent_increment
242 self.level += 1
243
244 def dedent(self):
245 self.current_indent -= self.indent_increment
246 assert self.current_indent >= 0, "Indent decreased below 0."
247 self.level -= 1
248
249 def format_usage(self, usage):
250 raise NotImplementedError, "subclasses must implement"
251
252 def format_heading(self, heading):
253 raise NotImplementedError, "subclasses must implement"
254
255 def _format_text(self, text):
256 """
257 Format a paragraph of free-form text for inclusion in the
258 help output at the current indentation level.
259 """
260 text_width = max(self.width - self.current_indent, 11)
261 indent = " "*self.current_indent
262 return textwrap.fill(text,
263 text_width,
264 initial_indent=indent,
265 subsequent_indent=indent)
266
267 def format_description(self, description):
268 if description:
269 return self._format_text(description) + "\n"
270 else:
271 return ""
272
273 def format_epilog(self, epilog):
274 if epilog:
275 return "\n" + self._format_text(epilog) + "\n"
276 else:
277 return ""
278
279
280 def expand_default(self, option):
281 if self.parser is None or not self.default_tag:
282 return option.help
283
284 default_value = self.parser.defaults.get(option.dest)
285 if default_value is NO_DEFAULT or default_value is None:
286 default_value = self.NO_DEFAULT_VALUE
287
288 return option.help.replace(self.default_tag, str(default_value))
289
290 def format_option(self, option):
291 # The help for each option consists of two parts:
292 # * the opt strings and metavars
293 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
294 # * the user-supplied help string
295 # eg. ("turn on expert mode", "read data from FILENAME")
296 #
297 # If possible, we write both of these on the same line:
298 # -x turn on expert mode
299 #
300 # But if the opt string list is too long, we put the help
301 # string on a second line, indented to the same column it would
302 # start in if it fit on the first line.
303 # -fFILENAME, --file=FILENAME
304 # read data from FILENAME
305 result = []
306 opts = self.option_strings[option]
307 opt_width = self.help_position - self.current_indent - 2
308 if len(opts) > opt_width:
309 opts = "%*s%s\n" % (self.current_indent, "", opts)
310 indent_first = self.help_position
311 else: # start help on same line as opts
312 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
313 indent_first = 0
314 result.append(opts)
315 if option.help:
316 help_text = self.expand_default(option)
317 help_lines = textwrap.wrap(help_text, self.help_width)
318 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
319 result.extend(["%*s%s\n" % (self.help_position, "", line)
320 for line in help_lines[1:]])
321 elif opts[-1] != "\n":
322 result.append("\n")
323 return "".join(result)
324
325 def store_option_strings(self, parser):
326 self.indent()
327 max_len = 0
328 for opt in parser.option_list:
329 strings = self.format_option_strings(opt)
330 self.option_strings[opt] = strings
331 max_len = max(max_len, len(strings) + self.current_indent)
332 self.indent()
333 for group in parser.option_groups:
334 for opt in group.option_list:
335 strings = self.format_option_strings(opt)
336 self.option_strings[opt] = strings
337 max_len = max(max_len, len(strings) + self.current_indent)
338 self.dedent()
339 self.dedent()
340 self.help_position = min(max_len + 2, self.max_help_position)
341 self.help_width = max(self.width - self.help_position, 11)
342
343 def format_option_strings(self, option):
344 """Return a comma-separated list of option strings & metavariables."""
345 if option.takes_value():
346 metavar = option.metavar or option.dest.upper()
347 short_opts = [self._short_opt_fmt % (sopt, metavar)
348 for sopt in option._short_opts]
349 long_opts = [self._long_opt_fmt % (lopt, metavar)
350 for lopt in option._long_opts]
351 else:
352 short_opts = option._short_opts
353 long_opts = option._long_opts
354
355 if self.short_first:
356 opts = short_opts + long_opts
357 else:
358 opts = long_opts + short_opts
359
360 return ", ".join(opts)
361
362class IndentedHelpFormatter (HelpFormatter):
363 """Format help with indented section bodies.
364 """
365
366 def __init__(self,
367 indent_increment=2,
368 max_help_position=24,
369 width=None,
370 short_first=1):
371 HelpFormatter.__init__(
372 self, indent_increment, max_help_position, width, short_first)
373
374 def format_usage(self, usage):
375 return _("Usage: %s\n") % usage
376
377 def format_heading(self, heading):
378 return "%*s%s:\n" % (self.current_indent, "", heading)
379
380
381class TitledHelpFormatter (HelpFormatter):
382 """Format help with underlined section headers.
383 """
384
385 def __init__(self,
386 indent_increment=0,
387 max_help_position=24,
388 width=None,
389 short_first=0):
390 HelpFormatter.__init__ (
391 self, indent_increment, max_help_position, width, short_first)
392
393 def format_usage(self, usage):
394 return "%s %s\n" % (self.format_heading(_("Usage")), usage)
395
396 def format_heading(self, heading):
397 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
398
399
400def _parse_num(val, type):
401 if val[:2].lower() == "0x": # hexadecimal
402 radix = 16
403 elif val[:2].lower() == "0b": # binary
404 radix = 2
405 val = val[2:] or "0" # have to remove "0b" prefix
406 elif val[:1] == "0": # octal
407 radix = 8
408 else: # decimal
409 radix = 10
410
411 return type(val, radix)
412
413def _parse_int(val):
414 return _parse_num(val, int)
415
416def _parse_long(val):
417 return _parse_num(val, long)
418
419_builtin_cvt = { "int" : (_parse_int, _("integer")),
420 "long" : (_parse_long, _("long integer")),
421 "float" : (float, _("floating-point")),
422 "complex" : (complex, _("complex")) }
423
424def check_builtin(option, opt, value):
425 (cvt, what) = _builtin_cvt[option.type]
426 try:
427 return cvt(value)
428 except ValueError:
429 raise OptionValueError(
430 _("option %s: invalid %s value: %r") % (opt, what, value))
431
432def check_choice(option, opt, value):
433 if value in option.choices:
434 return value
435 else:
436 choices = ", ".join(map(repr, option.choices))
437 raise OptionValueError(
438 _("option %s: invalid choice: %r (choose from %s)")
439 % (opt, value, choices))
440
441# Not supplying a default is different from a default of None,
442# so we need an explicit "not supplied" value.
443NO_DEFAULT = ("NO", "DEFAULT")
444
445
446class Option:
447 """
448 Instance attributes:
449 _short_opts : [string]
450 _long_opts : [string]
451
452 action : string
453 type : string
454 dest : string
455 default : any
456 nargs : int
457 const : any
458 choices : [string]
459 callback : function
460 callback_args : (any*)
461 callback_kwargs : { string : any }
462 help : string
463 metavar : string
464 """
465
466 # The list of instance attributes that may be set through
467 # keyword args to the constructor.
468 ATTRS = ['action',
469 'type',
470 'dest',
471 'default',
472 'nargs',
473 'const',
474 'choices',
475 'callback',
476 'callback_args',
477 'callback_kwargs',
478 'help',
479 'metavar']
480
481 # The set of actions allowed by option parsers. Explicitly listed
482 # here so the constructor can validate its arguments.
483 ACTIONS = ("store",
484 "store_const",
485 "store_true",
486 "store_false",
487 "append",
488 "append_const",
489 "count",
490 "callback",
491 "help",
492 "version")
493
494 # The set of actions that involve storing a value somewhere;
495 # also listed just for constructor argument validation. (If
496 # the action is one of these, there must be a destination.)
497 STORE_ACTIONS = ("store",
498 "store_const",
499 "store_true",
500 "store_false",
501 "append",
502 "append_const",
503 "count")
504
505 # The set of actions for which it makes sense to supply a value
506 # type, ie. which may consume an argument from the command line.
507 TYPED_ACTIONS = ("store",
508 "append",
509 "callback")
510
511 # The set of actions which *require* a value type, ie. that
512 # always consume an argument from the command line.
513 ALWAYS_TYPED_ACTIONS = ("store",
514 "append")
515
516 # The set of actions which take a 'const' attribute.
517 CONST_ACTIONS = ("store_const",
518 "append_const")
519
520 # The set of known types for option parsers. Again, listed here for
521 # constructor argument validation.
522 TYPES = ("string", "int", "long", "float", "complex", "choice")
523
524 # Dictionary of argument checking functions, which convert and
525 # validate option arguments according to the option type.
526 #
527 # Signature of checking functions is:
528 # check(option : Option, opt : string, value : string) -> any
529 # where
530 # option is the Option instance calling the checker
531 # opt is the actual option seen on the command-line
532 # (eg. "-a", "--file")
533 # value is the option argument seen on the command-line
534 #
535 # The return value should be in the appropriate Python type
536 # for option.type -- eg. an integer if option.type == "int".
537 #
538 # If no checker is defined for a type, arguments will be
539 # unchecked and remain strings.
540 TYPE_CHECKER = { "int" : check_builtin,
541 "long" : check_builtin,
542 "float" : check_builtin,
543 "complex": check_builtin,
544 "choice" : check_choice,
545 }
546
547
548 # CHECK_METHODS is a list of unbound method objects; they are called
549 # by the constructor, in order, after all attributes are
550 # initialized. The list is created and filled in later, after all
551 # the methods are actually defined. (I just put it here because I
552 # like to define and document all class attributes in the same
553 # place.) Subclasses that add another _check_*() method should
554 # define their own CHECK_METHODS list that adds their check method
555 # to those from this class.
556 CHECK_METHODS = None
557
558
559 # -- Constructor/initialization methods ----------------------------
560
561 def __init__(self, *opts, **attrs):
562 # Set _short_opts, _long_opts attrs from 'opts' tuple.
563 # Have to be set now, in case no option strings are supplied.
564 self._short_opts = []
565 self._long_opts = []
566 opts = self._check_opt_strings(opts)
567 self._set_opt_strings(opts)
568
569 # Set all other attrs (action, type, etc.) from 'attrs' dict
570 self._set_attrs(attrs)
571
572 # Check all the attributes we just set. There are lots of
573 # complicated interdependencies, but luckily they can be farmed
574 # out to the _check_*() methods listed in CHECK_METHODS -- which
575 # could be handy for subclasses! The one thing these all share
576 # is that they raise OptionError if they discover a problem.
577 for checker in self.CHECK_METHODS:
578 checker(self)
579
580 def _check_opt_strings(self, opts):
581 # Filter out None because early versions of Optik had exactly
582 # one short option and one long option, either of which
583 # could be None.
584 opts = filter(None, opts)
585 if not opts:
586 raise TypeError("at least one option string must be supplied")
587 return opts
588
589 def _set_opt_strings(self, opts):
590 for opt in opts:
591 if len(opt) < 2:
592 raise OptionError(
593 "invalid option string %r: "
594 "must be at least two characters long" % opt, self)
595 elif len(opt) == 2:
596 if not (opt[0] == "-" and opt[1] != "-"):
597 raise OptionError(
598 "invalid short option string %r: "
599 "must be of the form -x, (x any non-dash char)" % opt,
600 self)
601 self._short_opts.append(opt)
602 else:
603 if not (opt[0:2] == "--" and opt[2] != "-"):
604 raise OptionError(
605 "invalid long option string %r: "
606 "must start with --, followed by non-dash" % opt,
607 self)
608 self._long_opts.append(opt)
609
610 def _set_attrs(self, attrs):
611 for attr in self.ATTRS:
612 if attr in attrs:
613 setattr(self, attr, attrs[attr])
614 del attrs[attr]
615 else:
616 if attr == 'default':
617 setattr(self, attr, NO_DEFAULT)
618 else:
619 setattr(self, attr, None)
620 if attrs:
621 attrs = attrs.keys()
622 attrs.sort()
623 raise OptionError(
624 "invalid keyword arguments: %s" % ", ".join(attrs),
625 self)
626
627
628 # -- Constructor validation methods --------------------------------
629
630 def _check_action(self):
631 if self.action is None:
632 self.action = "store"
633 elif self.action not in self.ACTIONS:
634 raise OptionError("invalid action: %r" % self.action, self)
635
636 def _check_type(self):
637 if self.type is None:
638 if self.action in self.ALWAYS_TYPED_ACTIONS:
639 if self.choices is not None:
640 # The "choices" attribute implies "choice" type.
641 self.type = "choice"
642 else:
643 # No type given? "string" is the most sensible default.
644 self.type = "string"
645 else:
646 # Allow type objects or builtin type conversion functions
647 # (int, str, etc.) as an alternative to their names. (The
648 # complicated check of __builtin__ is only necessary for
649 # Python 2.1 and earlier, and is short-circuited by the
650 # first check on modern Pythons.)
651 import __builtin__
652 if ( type(self.type) is types.TypeType or
653 (hasattr(self.type, "__name__") and
654 getattr(__builtin__, self.type.__name__, None) is self.type) ):
655 self.type = self.type.__name__
656
657 if self.type == "str":
658 self.type = "string"
659
660 if self.type not in self.TYPES:
661 raise OptionError("invalid option type: %r" % self.type, self)
662 if self.action not in self.TYPED_ACTIONS:
663 raise OptionError(
664 "must not supply a type for action %r" % self.action, self)
665
666 def _check_choice(self):
667 if self.type == "choice":
668 if self.choices is None:
669 raise OptionError(
670 "must supply a list of choices for type 'choice'", self)
671 elif type(self.choices) not in (types.TupleType, types.ListType):
672 raise OptionError(
673 "choices must be a list of strings ('%s' supplied)"
674 % str(type(self.choices)).split("'")[1], self)
675 elif self.choices is not None:
676 raise OptionError(
677 "must not supply choices for type %r" % self.type, self)
678
679 def _check_dest(self):
680 # No destination given, and we need one for this action. The
681 # self.type check is for callbacks that take a value.
682 takes_value = (self.action in self.STORE_ACTIONS or
683 self.type is not None)
684 if self.dest is None and takes_value:
685
686 # Glean a destination from the first long option string,
687 # or from the first short option string if no long options.
688 if self._long_opts:
689 # eg. "--foo-bar" -> "foo_bar"
690 self.dest = self._long_opts[0][2:].replace('-', '_')
691 else:
692 self.dest = self._short_opts[0][1]
693
694 def _check_const(self):
695 if self.action not in self.CONST_ACTIONS and self.const is not None:
696 raise OptionError(
697 "'const' must not be supplied for action %r" % self.action,
698 self)
699
700 def _check_nargs(self):
701 if self.action in self.TYPED_ACTIONS:
702 if self.nargs is None:
703 self.nargs = 1
704 elif self.nargs is not None:
705 raise OptionError(
706 "'nargs' must not be supplied for action %r" % self.action,
707 self)
708
709 def _check_callback(self):
710 if self.action == "callback":
711 if not hasattr(self.callback, '__call__'):
712 raise OptionError(
713 "callback not callable: %r" % self.callback, self)
714 if (self.callback_args is not None and
715 type(self.callback_args) is not types.TupleType):
716 raise OptionError(
717 "callback_args, if supplied, must be a tuple: not %r"
718 % self.callback_args, self)
719 if (self.callback_kwargs is not None and
720 type(self.callback_kwargs) is not types.DictType):
721 raise OptionError(
722 "callback_kwargs, if supplied, must be a dict: not %r"
723 % self.callback_kwargs, self)
724 else:
725 if self.callback is not None:
726 raise OptionError(
727 "callback supplied (%r) for non-callback option"
728 % self.callback, self)
729 if self.callback_args is not None:
730 raise OptionError(
731 "callback_args supplied for non-callback option", self)
732 if self.callback_kwargs is not None:
733 raise OptionError(
734 "callback_kwargs supplied for non-callback option", self)
735
736
737 CHECK_METHODS = [_check_action,
738 _check_type,
739 _check_choice,
740 _check_dest,
741 _check_const,
742 _check_nargs,
743 _check_callback]
744
745
746 # -- Miscellaneous methods -----------------------------------------
747
748 def __str__(self):
749 return "/".join(self._short_opts + self._long_opts)
750
751 __repr__ = _repr
752
753 def takes_value(self):
754 return self.type is not None
755
756 def get_opt_string(self):
757 if self._long_opts:
758 return self._long_opts[0]
759 else:
760 return self._short_opts[0]
761
762
763 # -- Processing methods --------------------------------------------
764
765 def check_value(self, opt, value):
766 checker = self.TYPE_CHECKER.get(self.type)
767 if checker is None:
768 return value
769 else:
770 return checker(self, opt, value)
771
772 def convert_value(self, opt, value):
773 if value is not None:
774 if self.nargs == 1:
775 return self.check_value(opt, value)
776 else:
777 return tuple([self.check_value(opt, v) for v in value])
778
779 def process(self, opt, value, values, parser):
780
781 # First, convert the value(s) to the right type. Howl if any
782 # value(s) are bogus.
783 value = self.convert_value(opt, value)
784
785 # And then take whatever action is expected of us.
786 # This is a separate method to make life easier for
787 # subclasses to add new actions.
788 return self.take_action(
789 self.action, self.dest, opt, value, values, parser)
790
791 def take_action(self, action, dest, opt, value, values, parser):
792 if action == "store":
793 setattr(values, dest, value)
794 elif action == "store_const":
795 setattr(values, dest, self.const)
796 elif action == "store_true":
797 setattr(values, dest, True)
798 elif action == "store_false":
799 setattr(values, dest, False)
800 elif action == "append":
801 values.ensure_value(dest, []).append(value)
802 elif action == "append_const":
803 values.ensure_value(dest, []).append(self.const)
804 elif action == "count":
805 setattr(values, dest, values.ensure_value(dest, 0) + 1)
806 elif action == "callback":
807 args = self.callback_args or ()
808 kwargs = self.callback_kwargs or {}
809 self.callback(self, opt, value, parser, *args, **kwargs)
810 elif action == "help":
811 parser.print_help()
812 parser.exit()
813 elif action == "version":
814 parser.print_version()
815 parser.exit()
816 else:
817 raise ValueError("unknown action %r" % self.action)
818
819 return 1
820
821# class Option
822
823
824SUPPRESS_HELP = "SUPPRESS"+"HELP"
825SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
826
827try:
828 basestring
829except NameError:
830 def isbasestring(x):
831 return isinstance(x, (types.StringType, types.UnicodeType))
832else:
833 def isbasestring(x):
834 return isinstance(x, basestring)
835
836class Values:
837
838 def __init__(self, defaults=None):
839 if defaults:
840 for (attr, val) in defaults.items():
841 setattr(self, attr, val)
842
843 def __str__(self):
844 return str(self.__dict__)
845
846 __repr__ = _repr
847
848 def __cmp__(self, other):
849 if isinstance(other, Values):
850 return cmp(self.__dict__, other.__dict__)
851 elif isinstance(other, types.DictType):
852 return cmp(self.__dict__, other)
853 else:
854 return -1
855
856 def _update_careful(self, dict):
857 """
858 Update the option values from an arbitrary dictionary, but only
859 use keys from dict that already have a corresponding attribute
860 in self. Any keys in dict without a corresponding attribute
861 are silently ignored.
862 """
863 for attr in dir(self):
864 if attr in dict:
865 dval = dict[attr]
866 if dval is not None:
867 setattr(self, attr, dval)
868
869 def _update_loose(self, dict):
870 """
871 Update the option values from an arbitrary dictionary,
872 using all keys from the dictionary regardless of whether
873 they have a corresponding attribute in self or not.
874 """
875 self.__dict__.update(dict)
876
877 def _update(self, dict, mode):
878 if mode == "careful":
879 self._update_careful(dict)
880 elif mode == "loose":
881 self._update_loose(dict)
882 else:
883 raise ValueError, "invalid update mode: %r" % mode
884
885 def read_module(self, modname, mode="careful"):
886 __import__(modname)
887 mod = sys.modules[modname]
888 self._update(vars(mod), mode)
889
890 def read_file(self, filename, mode="careful"):
891 vars = {}
892 execfile(filename, vars)
893 self._update(vars, mode)
894
895 def ensure_value(self, attr, value):
896 if not hasattr(self, attr) or getattr(self, attr) is None:
897 setattr(self, attr, value)
898 return getattr(self, attr)
899
900
901class OptionContainer:
902
903 """
904 Abstract base class.
905
906 Class attributes:
907 standard_option_list : [Option]
908 list of standard options that will be accepted by all instances
909 of this parser class (intended to be overridden by subclasses).
910
911 Instance attributes:
912 option_list : [Option]
913 the list of Option objects contained by this OptionContainer
914 _short_opt : { string : Option }
915 dictionary mapping short option strings, eg. "-f" or "-X",
916 to the Option instances that implement them. If an Option
917 has multiple short option strings, it will appear in this
918 dictionary multiple times. [1]
919 _long_opt : { string : Option }
920 dictionary mapping long option strings, eg. "--file" or
921 "--exclude", to the Option instances that implement them.
922 Again, a given Option can occur multiple times in this
923 dictionary. [1]
924 defaults : { string : any }
925 dictionary mapping option destination names to default
926 values for each destination [1]
927
928 [1] These mappings are common to (shared by) all components of the
929 controlling OptionParser, where they are initially created.
930
931 """
932
933 def __init__(self, option_class, conflict_handler, description):
934 # Initialize the option list and related data structures.
935 # This method must be provided by subclasses, and it must
936 # initialize at least the following instance attributes:
937 # option_list, _short_opt, _long_opt, defaults.
938 self._create_option_list()
939
940 self.option_class = option_class
941 self.set_conflict_handler(conflict_handler)
942 self.set_description(description)
943
944 def _create_option_mappings(self):
945 # For use by OptionParser constructor -- create the master
946 # option mappings used by this OptionParser and all
947 # OptionGroups that it owns.
948 self._short_opt = {} # single letter -> Option instance
949 self._long_opt = {} # long option -> Option instance
950 self.defaults = {} # maps option dest -> default value
951
952
953 def _share_option_mappings(self, parser):
954 # For use by OptionGroup constructor -- use shared option
955 # mappings from the OptionParser that owns this OptionGroup.
956 self._short_opt = parser._short_opt
957 self._long_opt = parser._long_opt
958 self.defaults = parser.defaults
959
960 def set_conflict_handler(self, handler):
961 if handler not in ("error", "resolve"):
962 raise ValueError, "invalid conflict_resolution value %r" % handler
963 self.conflict_handler = handler
964
965 def set_description(self, description):
966 self.description = description
967
968 def get_description(self):
969 return self.description
970
971
972 def destroy(self):
973 """see OptionParser.destroy()."""
974 del self._short_opt
975 del self._long_opt
976 del self.defaults
977
978
979 # -- Option-adding methods -----------------------------------------
980
981 def _check_conflict(self, option):
982 conflict_opts = []
983 for opt in option._short_opts:
984 if opt in self._short_opt:
985 conflict_opts.append((opt, self._short_opt[opt]))
986 for opt in option._long_opts:
987 if opt in self._long_opt:
988 conflict_opts.append((opt, self._long_opt[opt]))
989
990 if conflict_opts:
991 handler = self.conflict_handler
992 if handler == "error":
993 raise OptionConflictError(
994 "conflicting option string(s): %s"
995 % ", ".join([co[0] for co in conflict_opts]),
996 option)
997 elif handler == "resolve":
998 for (opt, c_option) in conflict_opts:
999 if opt.startswith("--"):
1000 c_option._long_opts.remove(opt)
1001 del self._long_opt[opt]
1002 else:
1003 c_option._short_opts.remove(opt)
1004 del self._short_opt[opt]
1005 if not (c_option._short_opts or c_option._long_opts):
1006 c_option.container.option_list.remove(c_option)
1007
1008 def add_option(self, *args, **kwargs):
1009 """add_option(Option)
1010 add_option(opt_str, ..., kwarg=val, ...)
1011 """
1012 if type(args[0]) in types.StringTypes:
1013 option = self.option_class(*args, **kwargs)
1014 elif len(args) == 1 and not kwargs:
1015 option = args[0]
1016 if not isinstance(option, Option):
1017 raise TypeError, "not an Option instance: %r" % option
1018 else:
1019 raise TypeError, "invalid arguments"
1020
1021 self._check_conflict(option)
1022
1023 self.option_list.append(option)
1024 option.container = self
1025 for opt in option._short_opts:
1026 self._short_opt[opt] = option
1027 for opt in option._long_opts:
1028 self._long_opt[opt] = option
1029
1030 if option.dest is not None: # option has a dest, we need a default
1031 if option.default is not NO_DEFAULT:
1032 self.defaults[option.dest] = option.default
1033 elif option.dest not in self.defaults:
1034 self.defaults[option.dest] = None
1035
1036 return option
1037
1038 def add_options(self, option_list):
1039 for option in option_list:
1040 self.add_option(option)
1041
1042 # -- Option query/removal methods ----------------------------------
1043
1044 def get_option(self, opt_str):
1045 return (self._short_opt.get(opt_str) or
1046 self._long_opt.get(opt_str))
1047
1048 def has_option(self, opt_str):
1049 return (opt_str in self._short_opt or
1050 opt_str in self._long_opt)
1051
1052 def remove_option(self, opt_str):
1053 option = self._short_opt.get(opt_str)
1054 if option is None:
1055 option = self._long_opt.get(opt_str)
1056 if option is None:
1057 raise ValueError("no such option %r" % opt_str)
1058
1059 for opt in option._short_opts:
1060 del self._short_opt[opt]
1061 for opt in option._long_opts:
1062 del self._long_opt[opt]
1063 option.container.option_list.remove(option)
1064
1065
1066 # -- Help-formatting methods ---------------------------------------
1067
1068 def format_option_help(self, formatter):
1069 if not self.option_list:
1070 return ""
1071 result = []
1072 for option in self.option_list:
1073 if not option.help is SUPPRESS_HELP:
1074 result.append(formatter.format_option(option))
1075 return "".join(result)
1076
1077 def format_description(self, formatter):
1078 return formatter.format_description(self.get_description())
1079
1080 def format_help(self, formatter):
1081 result = []
1082 if self.description:
1083 result.append(self.format_description(formatter))
1084 if self.option_list:
1085 result.append(self.format_option_help(formatter))
1086 return "\n".join(result)
1087
1088
1089class OptionGroup (OptionContainer):
1090
1091 def __init__(self, parser, title, description=None):
1092 self.parser = parser
1093 OptionContainer.__init__(
1094 self, parser.option_class, parser.conflict_handler, description)
1095 self.title = title
1096
1097 def _create_option_list(self):
1098 self.option_list = []
1099 self._share_option_mappings(self.parser)
1100
1101 def set_title(self, title):
1102 self.title = title
1103
1104 def destroy(self):
1105 """see OptionParser.destroy()."""
1106 OptionContainer.destroy(self)
1107 del self.option_list
1108
1109 # -- Help-formatting methods ---------------------------------------
1110
1111 def format_help(self, formatter):
1112 result = formatter.format_heading(self.title)
1113 formatter.indent()
1114 result += OptionContainer.format_help(self, formatter)
1115 formatter.dedent()
1116 return result
1117
1118
1119class OptionParser (OptionContainer):
1120
1121 """
1122 Class attributes:
1123 standard_option_list : [Option]
1124 list of standard options that will be accepted by all instances
1125 of this parser class (intended to be overridden by subclasses).
1126
1127 Instance attributes:
1128 usage : string
1129 a usage string for your program. Before it is displayed
1130 to the user, "%prog" will be expanded to the name of
1131 your program (self.prog or os.path.basename(sys.argv[0])).
1132 prog : string
1133 the name of the current program (to override
1134 os.path.basename(sys.argv[0])).
1135 description : string
1136 A paragraph of text giving a brief overview of your program.
1137 optparse reformats this paragraph to fit the current terminal
1138 width and prints it when the user requests help (after usage,
1139 but before the list of options).
1140 epilog : string
1141 paragraph of help text to print after option help
1142
1143 option_groups : [OptionGroup]
1144 list of option groups in this parser (option groups are
1145 irrelevant for parsing the command-line, but very useful
1146 for generating help)
1147
1148 allow_interspersed_args : bool = true
1149 if true, positional arguments may be interspersed with options.
1150 Assuming -a and -b each take a single argument, the command-line
1151 -ablah foo bar -bboo baz
1152 will be interpreted the same as
1153 -ablah -bboo -- foo bar baz
1154 If this flag were false, that command line would be interpreted as
1155 -ablah -- foo bar -bboo baz
1156 -- ie. we stop processing options as soon as we see the first
1157 non-option argument. (This is the tradition followed by
1158 Python's getopt module, Perl's Getopt::Std, and other argument-
1159 parsing libraries, but it is generally annoying to users.)
1160
1161 process_default_values : bool = true
1162 if true, option default values are processed similarly to option
1163 values from the command line: that is, they are passed to the
1164 type-checking function for the option's type (as long as the
1165 default value is a string). (This really only matters if you
1166 have defined custom types; see SF bug #955889.) Set it to false
1167 to restore the behaviour of Optik 1.4.1 and earlier.
1168
1169 rargs : [string]
1170 the argument list currently being parsed. Only set when
1171 parse_args() is active, and continually trimmed down as
1172 we consume arguments. Mainly there for the benefit of
1173 callback options.
1174 largs : [string]
1175 the list of leftover arguments that we have skipped while
1176 parsing options. If allow_interspersed_args is false, this
1177 list is always empty.
1178 values : Values
1179 the set of option values currently being accumulated. Only
1180 set when parse_args() is active. Also mainly for callbacks.
1181
1182 Because of the 'rargs', 'largs', and 'values' attributes,
1183 OptionParser is not thread-safe. If, for some perverse reason, you
1184 need to parse command-line arguments simultaneously in different
1185 threads, use different OptionParser instances.
1186
1187 """
1188
1189 standard_option_list = []
1190
1191 def __init__(self,
1192 usage=None,
1193 option_list=None,
1194 option_class=Option,
1195 version=None,
1196 conflict_handler="error",
1197 description=None,
1198 formatter=None,
1199 add_help_option=True,
1200 prog=None,
1201 epilog=None):
1202 OptionContainer.__init__(
1203 self, option_class, conflict_handler, description)
1204 self.set_usage(usage)
1205 self.prog = prog
1206 self.version = version
1207 self.allow_interspersed_args = True
1208 self.process_default_values = True
1209 if formatter is None:
1210 formatter = IndentedHelpFormatter()
1211 self.formatter = formatter
1212 self.formatter.set_parser(self)
1213 self.epilog = epilog
1214
1215 # Populate the option list; initial sources are the
1216 # standard_option_list class attribute, the 'option_list'
1217 # argument, and (if applicable) the _add_version_option() and
1218 # _add_help_option() methods.
1219 self._populate_option_list(option_list,
1220 add_help=add_help_option)
1221
1222 self._init_parsing_state()
1223
1224
1225 def destroy(self):
1226 """
1227 Declare that you are done with this OptionParser. This cleans up
1228 reference cycles so the OptionParser (and all objects referenced by
1229 it) can be garbage-collected promptly. After calling destroy(), the
1230 OptionParser is unusable.
1231 """
1232 OptionContainer.destroy(self)
1233 for group in self.option_groups:
1234 group.destroy()
1235 del self.option_list
1236 del self.option_groups
1237 del self.formatter
1238
1239
1240 # -- Private methods -----------------------------------------------
1241 # (used by our or OptionContainer's constructor)
1242
1243 def _create_option_list(self):
1244 self.option_list = []
1245 self.option_groups = []
1246 self._create_option_mappings()
1247
1248 def _add_help_option(self):
1249 self.add_option("-h", "--help",
1250 action="help",
1251 help=_("show this help message and exit"))
1252
1253 def _add_version_option(self):
1254 self.add_option("--version",
1255 action="version",
1256 help=_("show program's version number and exit"))
1257
1258 def _populate_option_list(self, option_list, add_help=True):
1259 if self.standard_option_list:
1260 self.add_options(self.standard_option_list)
1261 if option_list:
1262 self.add_options(option_list)
1263 if self.version:
1264 self._add_version_option()
1265 if add_help:
1266 self._add_help_option()
1267
1268 def _init_parsing_state(self):
1269 # These are set in parse_args() for the convenience of callbacks.
1270 self.rargs = None
1271 self.largs = None
1272 self.values = None
1273
1274
1275 # -- Simple modifier methods ---------------------------------------
1276
1277 def set_usage(self, usage):
1278 if usage is None:
1279 self.usage = _("%prog [options]")
1280 elif usage is SUPPRESS_USAGE:
1281 self.usage = None
1282 # For backwards compatibility with Optik 1.3 and earlier.
1283 elif usage.lower().startswith("usage: "):
1284 self.usage = usage[7:]
1285 else:
1286 self.usage = usage
1287
1288 def enable_interspersed_args(self):
1289 """Set parsing to not stop on the first non-option, allowing
1290 interspersing switches with command arguments. This is the
1291 default behavior. See also disable_interspersed_args() and the
1292 class documentation description of the attribute
1293 allow_interspersed_args."""
1294 self.allow_interspersed_args = True
1295
1296 def disable_interspersed_args(self):
1297 """Set parsing to stop on the first non-option. Use this if
1298 you have a command processor which runs another command that
1299 has options of its own and you want to make sure these options
1300 don't get confused.
1301 """
1302 self.allow_interspersed_args = False
1303
1304 def set_process_default_values(self, process):
1305 self.process_default_values = process
1306
1307 def set_default(self, dest, value):
1308 self.defaults[dest] = value
1309
1310 def set_defaults(self, **kwargs):
1311 self.defaults.update(kwargs)
1312
1313 def _get_all_options(self):
1314 options = self.option_list[:]
1315 for group in self.option_groups:
1316 options.extend(group.option_list)
1317 return options
1318
1319 def get_default_values(self):
1320 if not self.process_default_values:
1321 # Old, pre-Optik 1.5 behaviour.
1322 return Values(self.defaults)
1323
1324 defaults = self.defaults.copy()
1325 for option in self._get_all_options():
1326 default = defaults.get(option.dest)
1327 if isbasestring(default):
1328 opt_str = option.get_opt_string()
1329 defaults[option.dest] = option.check_value(opt_str, default)
1330
1331 return Values(defaults)
1332
1333
1334 # -- OptionGroup methods -------------------------------------------
1335
1336 def add_option_group(self, *args, **kwargs):
1337 # XXX lots of overlap with OptionContainer.add_option()
1338 if type(args[0]) is types.StringType:
1339 group = OptionGroup(self, *args, **kwargs)
1340 elif len(args) == 1 and not kwargs:
1341 group = args[0]
1342 if not isinstance(group, OptionGroup):
1343 raise TypeError, "not an OptionGroup instance: %r" % group
1344 if group.parser is not self:
1345 raise ValueError, "invalid OptionGroup (wrong parser)"
1346 else:
1347 raise TypeError, "invalid arguments"
1348
1349 self.option_groups.append(group)
1350 return group
1351
1352 def get_option_group(self, opt_str):
1353 option = (self._short_opt.get(opt_str) or
1354 self._long_opt.get(opt_str))
1355 if option and option.container is not self:
1356 return option.container
1357 return None
1358
1359
1360 # -- Option-parsing methods ----------------------------------------
1361
1362 def _get_args(self, args):
1363 if args is None:
1364 return sys.argv[1:]
1365 else:
1366 return args[:] # don't modify caller's list
1367
1368 def parse_args(self, args=None, values=None):
1369 """
1370 parse_args(args : [string] = sys.argv[1:],
1371 values : Values = None)
1372 -> (values : Values, args : [string])
1373
1374 Parse the command-line options found in 'args' (default:
1375 sys.argv[1:]). Any errors result in a call to 'error()', which
1376 by default prints the usage message to stderr and calls
1377 sys.exit() with an error message. On success returns a pair
1378 (values, args) where 'values' is a Values instance (with all
1379 your option values) and 'args' is the list of arguments left
1380 over after parsing options.
1381 """
1382 rargs = self._get_args(args)
1383 if values is None:
1384 values = self.get_default_values()
1385
1386 # Store the halves of the argument list as attributes for the
1387 # convenience of callbacks:
1388 # rargs
1389 # the rest of the command-line (the "r" stands for
1390 # "remaining" or "right-hand")
1391 # largs
1392 # the leftover arguments -- ie. what's left after removing
1393 # options and their arguments (the "l" stands for "leftover"
1394 # or "left-hand")
1395 self.rargs = rargs
1396 self.largs = largs = []
1397 self.values = values
1398
1399 try:
1400 stop = self._process_args(largs, rargs, values)
1401 except (BadOptionError, OptionValueError), err:
1402 self.error(str(err))
1403
1404 args = largs + rargs
1405 return self.check_values(values, args)
1406
1407 def check_values(self, values, args):
1408 """
1409 check_values(values : Values, args : [string])
1410 -> (values : Values, args : [string])
1411
1412 Check that the supplied option values and leftover arguments are
1413 valid. Returns the option values and leftover arguments
1414 (possibly adjusted, possibly completely new -- whatever you
1415 like). Default implementation just returns the passed-in
1416 values; subclasses may override as desired.
1417 """
1418 return (values, args)
1419
1420 def _process_args(self, largs, rargs, values):
1421 """_process_args(largs : [string],
1422 rargs : [string],
1423 values : Values)
1424
1425 Process command-line arguments and populate 'values', consuming
1426 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1427 false, stop at the first non-option argument. If true, accumulate any
1428 interspersed non-option arguments in 'largs'.
1429 """
1430 while rargs:
1431 arg = rargs[0]
1432 # We handle bare "--" explicitly, and bare "-" is handled by the
1433 # standard arg handler since the short arg case ensures that the
1434 # len of the opt string is greater than 1.
1435 if arg == "--":
1436 del rargs[0]
1437 return
1438 elif arg[0:2] == "--":
1439 # process a single long option (possibly with value(s))
1440 self._process_long_opt(rargs, values)
1441 elif arg[:1] == "-" and len(arg) > 1:
1442 # process a cluster of short options (possibly with
1443 # value(s) for the last one only)
1444 self._process_short_opts(rargs, values)
1445 elif self.allow_interspersed_args:
1446 largs.append(arg)
1447 del rargs[0]
1448 else:
1449 return # stop now, leave this arg in rargs
1450
1451 # Say this is the original argument list:
1452 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1453 # ^
1454 # (we are about to process arg(i)).
1455 #
1456 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1457 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1458 # been removed from largs).
1459 #
1460 # The while loop will usually consume 1 or more arguments per pass.
1461 # If it consumes 1 (eg. arg is an option that takes no arguments),
1462 # then after _process_arg() is done the situation is:
1463 #
1464 # largs = subset of [arg0, ..., arg(i)]
1465 # rargs = [arg(i+1), ..., arg(N-1)]
1466 #
1467 # If allow_interspersed_args is false, largs will always be
1468 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1469 # not a very interesting subset!
1470
1471 def _match_long_opt(self, opt):
1472 """_match_long_opt(opt : string) -> string
1473
1474 Determine which long option string 'opt' matches, ie. which one
1475 it is an unambiguous abbreviation for. Raises BadOptionError if
1476 'opt' doesn't unambiguously match any long option string.
1477 """
1478 return _match_abbrev(opt, self._long_opt)
1479
1480 def _process_long_opt(self, rargs, values):
1481 arg = rargs.pop(0)
1482
1483 # Value explicitly attached to arg? Pretend it's the next
1484 # argument.
1485 if "=" in arg:
1486 (opt, next_arg) = arg.split("=", 1)
1487 rargs.insert(0, next_arg)
1488 had_explicit_value = True
1489 else:
1490 opt = arg
1491 had_explicit_value = False
1492
1493 opt = self._match_long_opt(opt)
1494 option = self._long_opt[opt]
1495 if option.takes_value():
1496 nargs = option.nargs
1497 if len(rargs) < nargs:
1498 if nargs == 1:
1499 self.error(_("%s option requires an argument") % opt)
1500 else:
1501 self.error(_("%s option requires %d arguments")
1502 % (opt, nargs))
1503 elif nargs == 1:
1504 value = rargs.pop(0)
1505 else:
1506 value = tuple(rargs[0:nargs])
1507 del rargs[0:nargs]
1508
1509 elif had_explicit_value:
1510 self.error(_("%s option does not take a value") % opt)
1511
1512 else:
1513 value = None
1514
1515 option.process(opt, value, values, self)
1516
1517 def _process_short_opts(self, rargs, values):
1518 arg = rargs.pop(0)
1519 stop = False
1520 i = 1
1521 for ch in arg[1:]:
1522 opt = "-" + ch
1523 option = self._short_opt.get(opt)
1524 i += 1 # we have consumed a character
1525
1526 if not option:
1527 raise BadOptionError(opt)
1528 if option.takes_value():
1529 # Any characters left in arg? Pretend they're the
1530 # next arg, and stop consuming characters of arg.
1531 if i < len(arg):
1532 rargs.insert(0, arg[i:])
1533 stop = True
1534
1535 nargs = option.nargs
1536 if len(rargs) < nargs:
1537 if nargs == 1:
1538 self.error(_("%s option requires an argument") % opt)
1539 else:
1540 self.error(_("%s option requires %d arguments")
1541 % (opt, nargs))
1542 elif nargs == 1:
1543 value = rargs.pop(0)
1544 else:
1545 value = tuple(rargs[0:nargs])
1546 del rargs[0:nargs]
1547
1548 else: # option doesn't take a value
1549 value = None
1550
1551 option.process(opt, value, values, self)
1552
1553 if stop:
1554 break
1555
1556
1557 # -- Feedback methods ----------------------------------------------
1558
1559 def get_prog_name(self):
1560 if self.prog is None:
1561 return os.path.basename(sys.argv[0])
1562 else:
1563 return self.prog
1564
1565 def expand_prog_name(self, s):
1566 return s.replace("%prog", self.get_prog_name())
1567
1568 def get_description(self):
1569 return self.expand_prog_name(self.description)
1570
1571 def exit(self, status=0, msg=None):
1572 if msg:
1573 sys.stderr.write(msg)
1574 sys.exit(status)
1575
1576 def error(self, msg):
1577 """error(msg : string)
1578
1579 Print a usage message incorporating 'msg' to stderr and exit.
1580 If you override this in a subclass, it should not return -- it
1581 should either exit or raise an exception.
1582 """
1583 self.print_usage(sys.stderr)
1584 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
1585
1586 def get_usage(self):
1587 if self.usage:
1588 return self.formatter.format_usage(
1589 self.expand_prog_name(self.usage))
1590 else:
1591 return ""
1592
1593 def print_usage(self, file=None):
1594 """print_usage(file : file = stdout)
1595
1596 Print the usage message for the current program (self.usage) to
1597 'file' (default stdout). Any occurrence of the string "%prog" in
1598 self.usage is replaced with the name of the current program
1599 (basename of sys.argv[0]). Does nothing if self.usage is empty
1600 or not defined.
1601 """
1602 if self.usage:
1603 print >>file, self.get_usage()
1604
1605 def get_version(self):
1606 if self.version:
1607 return self.expand_prog_name(self.version)
1608 else:
1609 return ""
1610
1611 def print_version(self, file=None):
1612 """print_version(file : file = stdout)
1613
1614 Print the version message for this program (self.version) to
1615 'file' (default stdout). As with print_usage(), any occurrence
1616 of "%prog" in self.version is replaced by the current program's
1617 name. Does nothing if self.version is empty or undefined.
1618 """
1619 if self.version:
1620 print >>file, self.get_version()
1621
1622 def format_option_help(self, formatter=None):
1623 if formatter is None:
1624 formatter = self.formatter
1625 formatter.store_option_strings(self)
1626 result = []
1627 result.append(formatter.format_heading(_("Options")))
1628 formatter.indent()
1629 if self.option_list:
1630 result.append(OptionContainer.format_option_help(self, formatter))
1631 result.append("\n")
1632 for group in self.option_groups:
1633 result.append(group.format_help(formatter))
1634 result.append("\n")
1635 formatter.dedent()
1636 # Drop the last "\n", or the header if no options or option groups:
1637 return "".join(result[:-1])
1638
1639 def format_epilog(self, formatter):
1640 return formatter.format_epilog(self.epilog)
1641
1642 def format_help(self, formatter=None):
1643 if formatter is None:
1644 formatter = self.formatter
1645 result = []
1646 if self.usage:
1647 result.append(self.get_usage() + "\n")
1648 if self.description:
1649 result.append(self.format_description(formatter) + "\n")
1650 result.append(self.format_option_help(formatter))
1651 result.append(self.format_epilog(formatter))
1652 return "".join(result)
1653
1654 # used by test suite
1655 def _get_encoding(self, file):
1656 encoding = getattr(file, "encoding", None)
1657 if not encoding:
1658 encoding = sys.getdefaultencoding()
1659 return encoding
1660
1661 def print_help(self, file=None):
1662 """print_help(file : file = stdout)
1663
1664 Print an extended help message, listing all options and any
1665 help text provided with them, to 'file' (default stdout).
1666 """
1667 if file is None:
1668 file = sys.stdout
1669 encoding = self._get_encoding(file)
1670 file.write(self.format_help().encode(encoding, "replace"))
1671
1672# class OptionParser
1673
1674
1675def _match_abbrev(s, wordmap):
1676 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1677
1678 Return the string key in 'wordmap' for which 's' is an unambiguous
1679 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1680 'words', raise BadOptionError.
1681 """
1682 # Is there an exact match?
1683 if s in wordmap:
1684 return s
1685 else:
1686 # Isolate all words with s as a prefix.
1687 possibilities = [word for word in wordmap.keys()
1688 if word.startswith(s)]
1689 # No exact match, so there had better be just one possibility.
1690 if len(possibilities) == 1:
1691 return possibilities[0]
1692 elif not possibilities:
1693 raise BadOptionError(s)
1694 else:
1695 # More than one possible completion: ambiguous prefix.
1696 possibilities.sort()
1697 raise AmbiguousOptionError(s, possibilities)
1698
1699
1700# Some day, there might be many Option classes. As of Optik 1.3, the
1701# preferred way to instantiate Options is indirectly, via make_option(),
1702# which will become a factory function when there are many Option
1703# classes.
1704make_option = Option