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