]>
git.proxmox.com Git - mirror_edk2.git/blob - AppPkg/Applications/Python/Python-2.7.10/Lib/optparse.py
1 """A powerful, extensible, and easy-to-use option parser.
3 By Greg Ward <gward@python.net>
5 Originally distributed as Optik.
7 For support, use the optik-users@lists.sourceforge.net mailing list
8 (http://lists.sourceforge.net/lists/listinfo/optik-users).
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()
35 'IndentedHelpFormatter',
36 'TitledHelpFormatter',
39 'OptionConflictError',
44 Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
45 Copyright (c) 2002-2006 Python Software Foundation. All rights reserved.
47 Redistribution and use in source and binary forms, with or without
48 modification, are permitted provided that the following conditions are
51 * Redistributions of source code must retain the above copyright
52 notice, this list of conditions and the following disclaimer.
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.
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.
62 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
63 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
64 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
65 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
66 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
67 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
68 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
69 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
70 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
71 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
72 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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
90 from gettext
import gettext
97 class OptParseError (Exception):
98 def __init__(self
, msg
):
105 class OptionError (OptParseError
):
107 Raised if an Option instance is created with invalid or
108 inconsistent arguments.
111 def __init__(self
, msg
, option
):
113 self
.option_id
= str(option
)
117 return "option %s: %s" % (self
.option_id
, self
.msg
)
121 class OptionConflictError (OptionError
):
123 Raised if conflicting options are added to an OptionParser.
126 class OptionValueError (OptParseError
):
128 Raised if an invalid option value is encountered on the command
132 class BadOptionError (OptParseError
):
134 Raised if an invalid option is seen on the command line.
136 def __init__(self
, opt_str
):
137 self
.opt_str
= opt_str
140 return _("no such option: %s") % self
.opt_str
142 class AmbiguousOptionError (BadOptionError
):
144 Raised if an ambiguous option is seen on the command line.
146 def __init__(self
, opt_str
, possibilities
):
147 BadOptionError
.__init
__(self
, opt_str
)
148 self
.possibilities
= possibilities
151 return (_("ambiguous option: %s (%s?)")
152 % (self
.opt_str
, ", ".join(self
.possibilities
)))
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.
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
170 the calculated starting column for option help text;
171 initially the same as the maximum
173 total number of columns for output (pass None to constructor for
174 this value to be taken from the $COLUMNS environment variable)
176 current indentation level
178 current indentation level (in columns)
180 number of columns available for option help text (calculated)
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"
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
194 similar but for long options; must be either "%s %s" ("--file FILE")
195 or "%s=%s" ("--file=FILE").
198 NO_DEFAULT_VALUE
= "none"
206 self
.indent_increment
= indent_increment
209 width
= int(os
.environ
['COLUMNS'])
210 except (KeyError, ValueError):
214 self
.help_position
= self
.max_help_position
= \
215 min(max_help_position
, max(width
- 20, indent_increment
* 2))
216 self
.current_indent
= 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"
225 def set_parser(self
, parser
):
228 def set_short_opt_delimiter(self
, delim
):
229 if delim
not in ("", " "):
231 "invalid metavar delimiter for short options: %r" % delim
)
232 self
._short
_opt
_fmt
= "%s" + delim
+ "%s"
234 def set_long_opt_delimiter(self
, delim
):
235 if delim
not in ("=", " "):
237 "invalid metavar delimiter for long options: %r" % delim
)
238 self
._long
_opt
_fmt
= "%s" + delim
+ "%s"
241 self
.current_indent
+= self
.indent_increment
245 self
.current_indent
-= self
.indent_increment
246 assert self
.current_indent
>= 0, "Indent decreased below 0."
249 def format_usage(self
, usage
):
250 raise NotImplementedError, "subclasses must implement"
252 def format_heading(self
, heading
):
253 raise NotImplementedError, "subclasses must implement"
255 def _format_text(self
, text
):
257 Format a paragraph of free-form text for inclusion in the
258 help output at the current indentation level.
260 text_width
= max(self
.width
- self
.current_indent
, 11)
261 indent
= " "*self
.current_indent
262 return textwrap
.fill(text
,
264 initial_indent
=indent
,
265 subsequent_indent
=indent
)
267 def format_description(self
, description
):
269 return self
._format
_text
(description
) + "\n"
273 def format_epilog(self
, epilog
):
275 return "\n" + self
._format
_text
(epilog
) + "\n"
280 def expand_default(self
, option
):
281 if self
.parser
is None or not self
.default_tag
:
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
288 return option
.help.replace(self
.default_tag
, str(default_value
))
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")
297 # If possible, we write both of these on the same line:
298 # -x turn on expert mode
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
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
)
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":
323 return "".join(result
)
325 def store_option_strings(self
, parser
):
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
)
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
)
340 self
.help_position
= min(max_len
+ 2, self
.max_help_position
)
341 self
.help_width
= max(self
.width
- self
.help_position
, 11)
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
]
352 short_opts
= option
._short
_opts
353 long_opts
= option
._long
_opts
356 opts
= short_opts
+ long_opts
358 opts
= long_opts
+ short_opts
360 return ", ".join(opts
)
362 class IndentedHelpFormatter (HelpFormatter
):
363 """Format help with indented section bodies.
368 max_help_position
=24,
371 HelpFormatter
.__init
__(
372 self
, indent_increment
, max_help_position
, width
, short_first
)
374 def format_usage(self
, usage
):
375 return _("Usage: %s\n") % usage
377 def format_heading(self
, heading
):
378 return "%*s%s:\n" % (self
.current_indent
, "", heading
)
381 class TitledHelpFormatter (HelpFormatter
):
382 """Format help with underlined section headers.
387 max_help_position
=24,
390 HelpFormatter
.__init
__ (
391 self
, indent_increment
, max_help_position
, width
, short_first
)
393 def format_usage(self
, usage
):
394 return "%s %s\n" % (self
.format_heading(_("Usage")), usage
)
396 def format_heading(self
, heading
):
397 return "%s\n%s\n" % (heading
, "=-"[self
.level
] * len(heading
))
400 def _parse_num(val
, type):
401 if val
[:2].lower() == "0x": # hexadecimal
403 elif val
[:2].lower() == "0b": # binary
405 val
= val
[2:] or "0" # have to remove "0b" prefix
406 elif val
[:1] == "0": # octal
411 return type(val
, radix
)
414 return _parse_num(val
, int)
416 def _parse_long(val
):
417 return _parse_num(val
, long)
419 _builtin_cvt
= { "int" : (_parse_int
, _("integer")),
420 "long" : (_parse_long
, _("long integer")),
421 "float" : (float, _("floating-point")),
422 "complex" : (complex, _("complex")) }
424 def check_builtin(option
, opt
, value
):
425 (cvt
, what
) = _builtin_cvt
[option
.type]
429 raise OptionValueError(
430 _("option %s: invalid %s value: %r") % (opt
, what
, value
))
432 def check_choice(option
, opt
, value
):
433 if value
in option
.choices
:
436 choices
= ", ".join(map(repr, option
.choices
))
437 raise OptionValueError(
438 _("option %s: invalid choice: %r (choose from %s)")
439 % (opt
, value
, choices
))
441 # Not supplying a default is different from a default of None,
442 # so we need an explicit "not supplied" value.
443 NO_DEFAULT
= ("NO", "DEFAULT")
449 _short_opts : [string]
450 _long_opts : [string]
460 callback_args : (any*)
461 callback_kwargs : { string : any }
466 # The list of instance attributes that may be set through
467 # keyword args to the constructor.
481 # The set of actions allowed by option parsers. Explicitly listed
482 # here so the constructor can validate its arguments.
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",
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",
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",
516 # The set of actions which take a 'const' attribute.
517 CONST_ACTIONS
= ("store_const",
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")
524 # Dictionary of argument checking functions, which convert and
525 # validate option arguments according to the option type.
527 # Signature of checking functions is:
528 # check(option : Option, opt : string, value : string) -> any
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
535 # The return value should be in the appropriate Python type
536 # for option.type -- eg. an integer if option.type == "int".
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
,
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.
559 # -- Constructor/initialization methods ----------------------------
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
= []
566 opts
= self
._check
_opt
_strings
(opts
)
567 self
._set
_opt
_strings
(opts
)
569 # Set all other attrs (action, type, etc.) from 'attrs' dict
570 self
._set
_attrs
(attrs
)
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
:
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
584 opts
= filter(None, opts
)
586 raise TypeError("at least one option string must be supplied")
589 def _set_opt_strings(self
, opts
):
593 "invalid option string %r: "
594 "must be at least two characters long" % opt
, self
)
596 if not (opt
[0] == "-" and opt
[1] != "-"):
598 "invalid short option string %r: "
599 "must be of the form -x, (x any non-dash char)" % opt
,
601 self
._short
_opts
.append(opt
)
603 if not (opt
[0:2] == "--" and opt
[2] != "-"):
605 "invalid long option string %r: "
606 "must start with --, followed by non-dash" % opt
,
608 self
._long
_opts
.append(opt
)
610 def _set_attrs(self
, attrs
):
611 for attr
in self
.ATTRS
:
613 setattr(self
, attr
, attrs
[attr
])
616 if attr
== 'default':
617 setattr(self
, attr
, NO_DEFAULT
)
619 setattr(self
, attr
, None)
624 "invalid keyword arguments: %s" % ", ".join(attrs
),
628 # -- Constructor validation methods --------------------------------
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
)
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.
643 # No type given? "string" is the most sensible default.
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.)
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
__
657 if self
.type == "str":
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
:
664 "must not supply a type for action %r" % self
.action
, self
)
666 def _check_choice(self
):
667 if self
.type == "choice":
668 if self
.choices
is None:
670 "must supply a list of choices for type 'choice'", self
)
671 elif type(self
.choices
) not in (types
.TupleType
, types
.ListType
):
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:
677 "must not supply choices for type %r" % self
.type, self
)
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
:
686 # Glean a destination from the first long option string,
687 # or from the first short option string if no long options.
689 # eg. "--foo-bar" -> "foo_bar"
690 self
.dest
= self
._long
_opts
[0][2:].replace('-', '_')
692 self
.dest
= self
._short
_opts
[0][1]
694 def _check_const(self
):
695 if self
.action
not in self
.CONST_ACTIONS
and self
.const
is not None:
697 "'const' must not be supplied for action %r" % self
.action
,
700 def _check_nargs(self
):
701 if self
.action
in self
.TYPED_ACTIONS
:
702 if self
.nargs
is None:
704 elif self
.nargs
is not None:
706 "'nargs' must not be supplied for action %r" % self
.action
,
709 def _check_callback(self
):
710 if self
.action
== "callback":
711 if not hasattr(self
.callback
, '__call__'):
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
):
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
):
722 "callback_kwargs, if supplied, must be a dict: not %r"
723 % self
.callback_kwargs
, self
)
725 if self
.callback
is not None:
727 "callback supplied (%r) for non-callback option"
728 % self
.callback
, self
)
729 if self
.callback_args
is not None:
731 "callback_args supplied for non-callback option", self
)
732 if self
.callback_kwargs
is not None:
734 "callback_kwargs supplied for non-callback option", self
)
737 CHECK_METHODS
= [_check_action
,
746 # -- Miscellaneous methods -----------------------------------------
749 return "/".join(self
._short
_opts
+ self
._long
_opts
)
753 def takes_value(self
):
754 return self
.type is not None
756 def get_opt_string(self
):
758 return self
._long
_opts
[0]
760 return self
._short
_opts
[0]
763 # -- Processing methods --------------------------------------------
765 def check_value(self
, opt
, value
):
766 checker
= self
.TYPE_CHECKER
.get(self
.type)
770 return checker(self
, opt
, value
)
772 def convert_value(self
, opt
, value
):
773 if value
is not None:
775 return self
.check_value(opt
, value
)
777 return tuple([self
.check_value(opt
, v
) for v
in value
])
779 def process(self
, opt
, value
, values
, parser
):
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
)
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
)
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":
813 elif action
== "version":
814 parser
.print_version()
817 raise ValueError("unknown action %r" % self
.action
)
824 SUPPRESS_HELP
= "SUPPRESS"+"HELP"
825 SUPPRESS_USAGE
= "SUPPRESS"+"USAGE"
831 return isinstance(x
, (types
.StringType
, types
.UnicodeType
))
834 return isinstance(x
, basestring
)
838 def __init__(self
, defaults
=None):
840 for (attr
, val
) in defaults
.items():
841 setattr(self
, attr
, val
)
844 return str(self
.__dict
__)
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
)
856 def _update_careful(self
, dict):
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.
863 for attr
in dir(self
):
867 setattr(self
, attr
, dval
)
869 def _update_loose(self
, dict):
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.
875 self
.__dict
__.update(dict)
877 def _update(self
, dict, mode
):
878 if mode
== "careful":
879 self
._update
_careful
(dict)
880 elif mode
== "loose":
881 self
._update
_loose
(dict)
883 raise ValueError, "invalid update mode: %r" % mode
885 def read_module(self
, modname
, mode
="careful"):
887 mod
= sys
.modules
[modname
]
888 self
._update
(vars(mod
), mode
)
890 def read_file(self
, filename
, mode
="careful"):
892 execfile(filename
, vars)
893 self
._update
(vars, mode
)
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
)
901 class OptionContainer
:
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).
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 appears 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
924 defaults : { string : any }
925 dictionary mapping option destination names to default
926 values for each destination [1]
928 [1] These mappings are common to (shared by) all components of the
929 controlling OptionParser, where they are initially created.
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
()
940 self
.option_class
= option_class
941 self
.set_conflict_handler(conflict_handler
)
942 self
.set_description(description
)
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
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
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
965 def set_description(self
, description
):
966 self
.description
= description
968 def get_description(self
):
969 return self
.description
973 """see OptionParser.destroy()."""
979 # -- Option-adding methods -----------------------------------------
981 def _check_conflict(self
, option
):
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
]))
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
]),
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
]
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
)
1008 def add_option(self
, *args
, **kwargs
):
1009 """add_option(Option)
1010 add_option(opt_str, ..., kwarg=val, ...)
1012 if type(args
[0]) in types
.StringTypes
:
1013 option
= self
.option_class(*args
, **kwargs
)
1014 elif len(args
) == 1 and not kwargs
:
1016 if not isinstance(option
, Option
):
1017 raise TypeError, "not an Option instance: %r" % option
1019 raise TypeError, "invalid arguments"
1021 self
._check
_conflict
(option
)
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
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
1038 def add_options(self
, option_list
):
1039 for option
in option_list
:
1040 self
.add_option(option
)
1042 # -- Option query/removal methods ----------------------------------
1044 def get_option(self
, opt_str
):
1045 return (self
._short
_opt
.get(opt_str
) or
1046 self
._long
_opt
.get(opt_str
))
1048 def has_option(self
, opt_str
):
1049 return (opt_str
in self
._short
_opt
or
1050 opt_str
in self
._long
_opt
)
1052 def remove_option(self
, opt_str
):
1053 option
= self
._short
_opt
.get(opt_str
)
1055 option
= self
._long
_opt
.get(opt_str
)
1057 raise ValueError("no such option %r" % opt_str
)
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
)
1066 # -- Help-formatting methods ---------------------------------------
1068 def format_option_help(self
, formatter
):
1069 if not self
.option_list
:
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
)
1077 def format_description(self
, formatter
):
1078 return formatter
.format_description(self
.get_description())
1080 def format_help(self
, formatter
):
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
)
1089 class OptionGroup (OptionContainer
):
1091 def __init__(self
, parser
, title
, description
=None):
1092 self
.parser
= parser
1093 OptionContainer
.__init
__(
1094 self
, parser
.option_class
, parser
.conflict_handler
, description
)
1097 def _create_option_list(self
):
1098 self
.option_list
= []
1099 self
._share
_option
_mappings
(self
.parser
)
1101 def set_title(self
, title
):
1105 """see OptionParser.destroy()."""
1106 OptionContainer
.destroy(self
)
1107 del self
.option_list
1109 # -- Help-formatting methods ---------------------------------------
1111 def format_help(self
, formatter
):
1112 result
= formatter
.format_heading(self
.title
)
1114 result
+= OptionContainer
.format_help(self
, formatter
)
1119 class OptionParser (OptionContainer
):
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).
1127 Instance attributes:
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])).
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).
1141 paragraph of help text to print after option help
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)
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.)
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.
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
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.
1179 the set of option values currently being accumulated. Only
1180 set when parse_args() is active. Also mainly for callbacks.
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.
1189 standard_option_list
= []
1194 option_class
=Option
,
1196 conflict_handler
="error",
1199 add_help_option
=True,
1202 OptionContainer
.__init
__(
1203 self
, option_class
, conflict_handler
, description
)
1204 self
.set_usage(usage
)
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
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
)
1222 self
._init
_parsing
_state
()
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.
1232 OptionContainer
.destroy(self
)
1233 for group
in self
.option_groups
:
1235 del self
.option_list
1236 del self
.option_groups
1240 # -- Private methods -----------------------------------------------
1241 # (used by our or OptionContainer's constructor)
1243 def _create_option_list(self
):
1244 self
.option_list
= []
1245 self
.option_groups
= []
1246 self
._create
_option
_mappings
()
1248 def _add_help_option(self
):
1249 self
.add_option("-h", "--help",
1251 help=_("show this help message and exit"))
1253 def _add_version_option(self
):
1254 self
.add_option("--version",
1256 help=_("show program's version number and exit"))
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
)
1262 self
.add_options(option_list
)
1264 self
._add
_version
_option
()
1266 self
._add
_help
_option
()
1268 def _init_parsing_state(self
):
1269 # These are set in parse_args() for the convenience of callbacks.
1275 # -- Simple modifier methods ---------------------------------------
1277 def set_usage(self
, usage
):
1279 self
.usage
= _("%prog [options]")
1280 elif usage
is SUPPRESS_USAGE
:
1282 # For backwards compatibility with Optik 1.3 and earlier.
1283 elif usage
.lower().startswith("usage: "):
1284 self
.usage
= usage
[7:]
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
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
1302 self
.allow_interspersed_args
= False
1304 def set_process_default_values(self
, process
):
1305 self
.process_default_values
= process
1307 def set_default(self
, dest
, value
):
1308 self
.defaults
[dest
] = value
1310 def set_defaults(self
, **kwargs
):
1311 self
.defaults
.update(kwargs
)
1313 def _get_all_options(self
):
1314 options
= self
.option_list
[:]
1315 for group
in self
.option_groups
:
1316 options
.extend(group
.option_list
)
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
)
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
)
1331 return Values(defaults
)
1334 # -- OptionGroup methods -------------------------------------------
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
:
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)"
1347 raise TypeError, "invalid arguments"
1349 self
.option_groups
.append(group
)
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
1360 # -- Option-parsing methods ----------------------------------------
1362 def _get_args(self
, args
):
1366 return args
[:] # don't modify caller's list
1368 def parse_args(self
, args
=None, values
=None):
1370 parse_args(args : [string] = sys.argv[1:],
1371 values : Values = None)
1372 -> (values : Values, args : [string])
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 an Values instance (with all
1379 your option values) and 'args' is the list of arguments left
1380 over after parsing options.
1382 rargs
= self
._get
_args
(args
)
1384 values
= self
.get_default_values()
1386 # Store the halves of the argument list as attributes for the
1387 # convenience of callbacks:
1389 # the rest of the command-line (the "r" stands for
1390 # "remaining" or "right-hand")
1392 # the leftover arguments -- ie. what's left after removing
1393 # options and their arguments (the "l" stands for "leftover"
1396 self
.largs
= largs
= []
1397 self
.values
= values
1400 stop
= self
._process
_args
(largs
, rargs
, values
)
1401 except (BadOptionError
, OptionValueError
), err
:
1402 self
.error(str(err
))
1404 args
= largs
+ rargs
1405 return self
.check_values(values
, args
)
1407 def check_values(self
, values
, args
):
1409 check_values(values : Values, args : [string])
1410 -> (values : Values, args : [string])
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.
1418 return (values
, args
)
1420 def _process_args(self
, largs
, rargs
, values
):
1421 """_process_args(largs : [string],
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'.
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.
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
:
1449 return # stop now, leave this arg in rargs
1451 # Say this is the original argument list:
1452 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1454 # (we are about to process arg(i)).
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).
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:
1464 # largs = subset of [arg0, ..., arg(i)]
1465 # rargs = [arg(i+1), ..., arg(N-1)]
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!
1471 def _match_long_opt(self
, opt
):
1472 """_match_long_opt(opt : string) -> string
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.
1478 return _match_abbrev(opt
, self
._long
_opt
)
1480 def _process_long_opt(self
, rargs
, values
):
1483 # Value explicitly attached to arg? Pretend it's the next
1486 (opt
, next_arg
) = arg
.split("=", 1)
1487 rargs
.insert(0, next_arg
)
1488 had_explicit_value
= True
1491 had_explicit_value
= False
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
:
1499 self
.error(_("%s option requires an argument") % opt
)
1501 self
.error(_("%s option requires %d arguments")
1504 value
= rargs
.pop(0)
1506 value
= tuple(rargs
[0:nargs
])
1509 elif had_explicit_value
:
1510 self
.error(_("%s option does not take a value") % opt
)
1515 option
.process(opt
, value
, values
, self
)
1517 def _process_short_opts(self
, rargs
, values
):
1523 option
= self
._short
_opt
.get(opt
)
1524 i
+= 1 # we have consumed a character
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.
1532 rargs
.insert(0, arg
[i
:])
1535 nargs
= option
.nargs
1536 if len(rargs
) < nargs
:
1538 self
.error(_("%s option requires an argument") % opt
)
1540 self
.error(_("%s option requires %d arguments")
1543 value
= rargs
.pop(0)
1545 value
= tuple(rargs
[0:nargs
])
1548 else: # option doesn't take a value
1551 option
.process(opt
, value
, values
, self
)
1557 # -- Feedback methods ----------------------------------------------
1559 def get_prog_name(self
):
1560 if self
.prog
is None:
1561 return os
.path
.basename(sys
.argv
[0])
1565 def expand_prog_name(self
, s
):
1566 return s
.replace("%prog", self
.get_prog_name())
1568 def get_description(self
):
1569 return self
.expand_prog_name(self
.description
)
1571 def exit(self
, status
=0, msg
=None):
1573 sys
.stderr
.write(msg
)
1576 def error(self
, msg
):
1577 """error(msg : string)
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.
1583 self
.print_usage(sys
.stderr
)
1584 self
.exit(2, "%s: error: %s\n" % (self
.get_prog_name(), msg
))
1586 def get_usage(self
):
1588 return self
.formatter
.format_usage(
1589 self
.expand_prog_name(self
.usage
))
1593 def print_usage(self
, file=None):
1594 """print_usage(file : file = stdout)
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
1603 print >>file, self
.get_usage()
1605 def get_version(self
):
1607 return self
.expand_prog_name(self
.version
)
1611 def print_version(self
, file=None):
1612 """print_version(file : file = stdout)
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.
1620 print >>file, self
.get_version()
1622 def format_option_help(self
, formatter
=None):
1623 if formatter
is None:
1624 formatter
= self
.formatter
1625 formatter
.store_option_strings(self
)
1627 result
.append(formatter
.format_heading(_("Options")))
1629 if self
.option_list
:
1630 result
.append(OptionContainer
.format_option_help(self
, formatter
))
1632 for group
in self
.option_groups
:
1633 result
.append(group
.format_help(formatter
))
1636 # Drop the last "\n", or the header if no options or option groups:
1637 return "".join(result
[:-1])
1639 def format_epilog(self
, formatter
):
1640 return formatter
.format_epilog(self
.epilog
)
1642 def format_help(self
, formatter
=None):
1643 if formatter
is None:
1644 formatter
= self
.formatter
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
)
1654 # used by test suite
1655 def _get_encoding(self
, file):
1656 encoding
= getattr(file, "encoding", None)
1658 encoding
= sys
.getdefaultencoding()
1661 def print_help(self
, file=None):
1662 """print_help(file : file = stdout)
1664 Print an extended help message, listing all options and any
1665 help text provided with them, to 'file' (default stdout).
1669 encoding
= self
._get
_encoding
(file)
1670 file.write(self
.format_help().encode(encoding
, "replace"))
1672 # class OptionParser
1675 def _match_abbrev(s
, wordmap
):
1676 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
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.
1682 # Is there an exact match?
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
)
1695 # More than one possible completion: ambiguous prefix.
1696 possibilities
.sort()
1697 raise AmbiguousOptionError(s
, possibilities
)
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
1704 make_option
= Option