1 """optparse - a powerful, extensible, and easy-to-use option parser.
3 By Greg Ward <gward@python.net>
5 Originally distributed as Optik; see http://optik.sourceforge.net/ .
7 If you have problems with this module, please do not file bugs,
8 patches, or feature requests with Python; instead, use Optik's
9 SourceForge project page:
10 http://sourceforge.net/projects/optik
12 For support, use the optik-users@lists.sourceforge.net mailing list
13 (http://lists.sourceforge.net/lists/listinfo/optik-users).
16 # Python developers: please do not make changes to this file, since
17 # it is automatically generated from the Optik source code.
29 'IndentedHelpFormatter',
30 'TitledHelpFormatter',
33 'OptionConflictError',
38 Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved.
39 Copyright (c) 2002-2004 Python Software Foundation. All rights reserved.
41 Redistribution and use in source and binary forms, with or without
42 modification, are permitted provided that the following conditions are
45 * Redistributions of source code must retain the above copyright
46 notice, this list of conditions and the following disclaimer.
48 * Redistributions in binary form must reproduce the above copyright
49 notice, this list of conditions and the following disclaimer in the
50 documentation and/or other materials provided with the distribution.
52 * Neither the name of the author nor the names of its
53 contributors may be used to endorse or promote products derived from
54 this software without specific prior written permission.
56 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
57 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
59 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
60 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
61 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
62 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
63 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
64 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
65 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
66 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
72 from gettext
import gettext
as _
77 return "<%s at 0x%x: %s>" % (self
.__class
__.__name
__, id(self
), self
)
80 # This file was generated from:
81 # Id: option_parser.py 421 2004-10-26 00:45:16Z greg
82 # Id: option.py 422 2004-10-26 00:53:47Z greg
83 # Id: help.py 367 2004-07-24 23:21:21Z gward
84 # Id: errors.py 367 2004-07-24 23:21:21Z gward
86 class OptParseError (Exception):
87 def __init__(self
, msg
):
94 class OptionError (OptParseError
):
96 Raised if an Option instance is created with invalid or
97 inconsistent arguments.
100 def __init__(self
, msg
, option
):
102 self
.option_id
= str(option
)
106 return "option %s: %s" % (self
.option_id
, self
.msg
)
110 class OptionConflictError (OptionError
):
112 Raised if conflicting options are added to an OptionParser.
115 class OptionValueError (OptParseError
):
117 Raised if an invalid option value is encountered on the command
121 class BadOptionError (OptParseError
):
123 Raised if an invalid or ambiguous option is seen on the command-line.
130 Abstract base class for formatting option help. OptionParser
131 instances should use one of the HelpFormatter subclasses for
132 formatting help; by default IndentedHelpFormatter is used.
135 parser : OptionParser
136 the controlling OptionParser instance
137 indent_increment : int
138 the number of columns to indent per nesting level
139 max_help_position : int
140 the maximum starting column for option help text
142 the calculated starting column for option help text;
143 initially the same as the maximum
145 total number of columns for output (pass None to constructor for
146 this value to be taken from the $COLUMNS environment variable)
148 current indentation level
150 current indentation level (in columns)
152 number of columns available for option help text (calculated)
154 text to replace with each option's default value, "%default"
155 by default. Set to false value to disable default value expansion.
156 option_strings : { Option : str }
157 maps Option instances to the snippet of help text explaining
158 the syntax of that option, e.g. "-h, --help" or
159 "-fFILE, --file=FILE"
161 format string controlling how short options with values are
162 printed in help text. Must be either "%s%s" ("-fFILE") or
163 "%s %s" ("-f FILE"), because those are the two syntaxes that
166 similar but for long options; must be either "%s %s" ("--file FILE")
167 or "%s=%s" ("--file=FILE").
170 NO_DEFAULT_VALUE
= "none"
178 self
.indent_increment
= indent_increment
179 self
.help_position
= self
.max_help_position
= max_help_position
182 width
= int(os
.environ
['COLUMNS'])
183 except (KeyError, ValueError):
187 self
.current_indent
= 0
189 self
.help_width
= None # computed later
190 self
.short_first
= short_first
191 self
.default_tag
= "%default"
192 self
.option_strings
= {}
193 self
._short
_opt
_fmt
= "%s %s"
194 self
._long
_opt
_fmt
= "%s=%s"
196 def set_parser(self
, parser
):
199 def set_short_opt_delimiter(self
, delim
):
200 if delim
not in ("", " "):
202 "invalid metavar delimiter for short options: %r" % delim
)
203 self
._short
_opt
_fmt
= "%s" + delim
+ "%s"
205 def set_long_opt_delimiter(self
, delim
):
206 if delim
not in ("=", " "):
208 "invalid metavar delimiter for long options: %r" % delim
)
209 self
._long
_opt
_fmt
= "%s" + delim
+ "%s"
212 self
.current_indent
+= self
.indent_increment
216 self
.current_indent
-= self
.indent_increment
217 assert self
.current_indent
>= 0, "Indent decreased below 0."
220 def format_usage(self
, usage
):
221 raise NotImplementedError, "subclasses must implement"
223 def format_heading(self
, heading
):
224 raise NotImplementedError, "subclasses must implement"
226 def format_description(self
, description
):
229 desc_width
= self
.width
- self
.current_indent
230 indent
= " "*self
.current_indent
231 return textwrap
.fill(description
,
233 initial_indent
=indent
,
234 subsequent_indent
=indent
) + "\n"
236 def expand_default(self
, option
):
237 if self
.parser
is None or not self
.default_tag
:
240 default_value
= self
.parser
.defaults
.get(option
.dest
)
241 if default_value
is NO_DEFAULT
or default_value
is None:
242 default_value
= self
.NO_DEFAULT_VALUE
244 return option
.help.replace(self
.default_tag
, str(default_value
))
246 def format_option(self
, option
):
247 # The help for each option consists of two parts:
248 # * the opt strings and metavars
249 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
250 # * the user-supplied help string
251 # eg. ("turn on expert mode", "read data from FILENAME")
253 # If possible, we write both of these on the same line:
254 # -x turn on expert mode
256 # But if the opt string list is too long, we put the help
257 # string on a second line, indented to the same column it would
258 # start in if it fit on the first line.
259 # -fFILENAME, --file=FILENAME
260 # read data from FILENAME
262 opts
= self
.option_strings
[option
]
263 opt_width
= self
.help_position
- self
.current_indent
- 2
264 if len(opts
) > opt_width
:
265 opts
= "%*s%s\n" % (self
.current_indent
, "", opts
)
266 indent_first
= self
.help_position
267 else: # start help on same line as opts
268 opts
= "%*s%-*s " % (self
.current_indent
, "", opt_width
, opts
)
272 help_text
= self
.expand_default(option
)
273 help_lines
= textwrap
.wrap(help_text
, self
.help_width
)
274 result
.append("%*s%s\n" % (indent_first
, "", help_lines
[0]))
275 result
.extend(["%*s%s\n" % (self
.help_position
, "", line
)
276 for line
in help_lines
[1:]])
277 elif opts
[-1] != "\n":
279 return "".join(result
)
281 def store_option_strings(self
, parser
):
284 for opt
in parser
.option_list
:
285 strings
= self
.format_option_strings(opt
)
286 self
.option_strings
[opt
] = strings
287 max_len
= max(max_len
, len(strings
) + self
.current_indent
)
289 for group
in parser
.option_groups
:
290 for opt
in group
.option_list
:
291 strings
= self
.format_option_strings(opt
)
292 self
.option_strings
[opt
] = strings
293 max_len
= max(max_len
, len(strings
) + self
.current_indent
)
296 self
.help_position
= min(max_len
+ 2, self
.max_help_position
)
297 self
.help_width
= self
.width
- self
.help_position
299 def format_option_strings(self
, option
):
300 """Return a comma-separated list of option strings & metavariables."""
301 if option
.takes_value():
302 metavar
= option
.metavar
or option
.dest
.upper()
303 short_opts
= [self
._short
_opt
_fmt
% (sopt
, metavar
)
304 for sopt
in option
._short
_opts
]
305 long_opts
= [self
._long
_opt
_fmt
% (lopt
, metavar
)
306 for lopt
in option
._long
_opts
]
308 short_opts
= option
._short
_opts
309 long_opts
= option
._long
_opts
312 opts
= short_opts
+ long_opts
314 opts
= long_opts
+ short_opts
316 return ", ".join(opts
)
318 class IndentedHelpFormatter (HelpFormatter
):
319 """Format help with indented section bodies.
324 max_help_position
=24,
327 HelpFormatter
.__init
__(
328 self
, indent_increment
, max_help_position
, width
, short_first
)
330 def format_usage(self
, usage
):
331 return _("usage: %s\n") % usage
333 def format_heading(self
, heading
):
334 return "%*s%s:\n" % (self
.current_indent
, "", heading
)
337 class TitledHelpFormatter (HelpFormatter
):
338 """Format help with underlined section headers.
343 max_help_position
=24,
346 HelpFormatter
.__init
__ (
347 self
, indent_increment
, max_help_position
, width
, short_first
)
349 def format_usage(self
, usage
):
350 return "%s %s\n" % (self
.format_heading(_("Usage")), usage
)
352 def format_heading(self
, heading
):
353 return "%s\n%s\n" % (heading
, "=-"[self
.level
] * len(heading
))
356 _builtin_cvt
= { "int" : (int, _("integer")),
357 "long" : (long, _("long integer")),
358 "float" : (float, _("floating-point")),
359 "complex" : (complex, _("complex")) }
361 def check_builtin(option
, opt
, value
):
362 (cvt
, what
) = _builtin_cvt
[option
.type]
366 raise OptionValueError(
367 _("option %s: invalid %s value: %r") % (opt
, what
, value
))
369 def check_choice(option
, opt
, value
):
370 if value
in option
.choices
:
373 choices
= ", ".join(map(repr, option
.choices
))
374 raise OptionValueError(
375 _("option %s: invalid choice: %r (choose from %s)")
376 % (opt
, value
, choices
))
378 # Not supplying a default is different from a default of None,
379 # so we need an explicit "not supplied" value.
380 NO_DEFAULT
= ("NO", "DEFAULT")
386 _short_opts : [string]
387 _long_opts : [string]
397 callback_args : (any*)
398 callback_kwargs : { string : any }
403 # The list of instance attributes that may be set through
404 # keyword args to the constructor.
418 # The set of actions allowed by option parsers. Explicitly listed
419 # here so the constructor can validate its arguments.
430 # The set of actions that involve storing a value somewhere;
431 # also listed just for constructor argument validation. (If
432 # the action is one of these, there must be a destination.)
433 STORE_ACTIONS
= ("store",
440 # The set of actions for which it makes sense to supply a value
441 # type, ie. which may consume an argument from the command line.
442 TYPED_ACTIONS
= ("store",
446 # The set of actions which *require* a value type, ie. that
447 # always consume an argument from the command line.
448 ALWAYS_TYPED_ACTIONS
= ("store",
451 # The set of known types for option parsers. Again, listed here for
452 # constructor argument validation.
453 TYPES
= ("string", "int", "long", "float", "complex", "choice")
455 # Dictionary of argument checking functions, which convert and
456 # validate option arguments according to the option type.
458 # Signature of checking functions is:
459 # check(option : Option, opt : string, value : string) -> any
461 # option is the Option instance calling the checker
462 # opt is the actual option seen on the command-line
463 # (eg. "-a", "--file")
464 # value is the option argument seen on the command-line
466 # The return value should be in the appropriate Python type
467 # for option.type -- eg. an integer if option.type == "int".
469 # If no checker is defined for a type, arguments will be
470 # unchecked and remain strings.
471 TYPE_CHECKER
= { "int" : check_builtin
,
472 "long" : check_builtin
,
473 "float" : check_builtin
,
474 "complex": check_builtin
,
475 "choice" : check_choice
,
479 # CHECK_METHODS is a list of unbound method objects; they are called
480 # by the constructor, in order, after all attributes are
481 # initialized. The list is created and filled in later, after all
482 # the methods are actually defined. (I just put it here because I
483 # like to define and document all class attributes in the same
484 # place.) Subclasses that add another _check_*() method should
485 # define their own CHECK_METHODS list that adds their check method
486 # to those from this class.
490 # -- Constructor/initialization methods ----------------------------
492 def __init__(self
, *opts
, **attrs
):
493 # Set _short_opts, _long_opts attrs from 'opts' tuple.
494 # Have to be set now, in case no option strings are supplied.
495 self
._short
_opts
= []
497 opts
= self
._check
_opt
_strings
(opts
)
498 self
._set
_opt
_strings
(opts
)
500 # Set all other attrs (action, type, etc.) from 'attrs' dict
501 self
._set
_attrs
(attrs
)
503 # Check all the attributes we just set. There are lots of
504 # complicated interdependencies, but luckily they can be farmed
505 # out to the _check_*() methods listed in CHECK_METHODS -- which
506 # could be handy for subclasses! The one thing these all share
507 # is that they raise OptionError if they discover a problem.
508 for checker
in self
.CHECK_METHODS
:
511 def _check_opt_strings(self
, opts
):
512 # Filter out None because early versions of Optik had exactly
513 # one short option and one long option, either of which
515 opts
= filter(None, opts
)
517 raise TypeError("at least one option string must be supplied")
520 def _set_opt_strings(self
, opts
):
524 "invalid option string %r: "
525 "must be at least two characters long" % opt
, self
)
527 if not (opt
[0] == "-" and opt
[1] != "-"):
529 "invalid short option string %r: "
530 "must be of the form -x, (x any non-dash char)" % opt
,
532 self
._short
_opts
.append(opt
)
534 if not (opt
[0:2] == "--" and opt
[2] != "-"):
536 "invalid long option string %r: "
537 "must start with --, followed by non-dash" % opt
,
539 self
._long
_opts
.append(opt
)
541 def _set_attrs(self
, attrs
):
542 for attr
in self
.ATTRS
:
543 if attrs
.has_key(attr
):
544 setattr(self
, attr
, attrs
[attr
])
547 if attr
== 'default':
548 setattr(self
, attr
, NO_DEFAULT
)
550 setattr(self
, attr
, None)
553 "invalid keyword arguments: %s" % ", ".join(attrs
.keys()),
557 # -- Constructor validation methods --------------------------------
559 def _check_action(self
):
560 if self
.action
is None:
561 self
.action
= "store"
562 elif self
.action
not in self
.ACTIONS
:
563 raise OptionError("invalid action: %r" % self
.action
, self
)
565 def _check_type(self
):
566 if self
.type is None:
567 if self
.action
in self
.ALWAYS_TYPED_ACTIONS
:
568 if self
.choices
is not None:
569 # The "choices" attribute implies "choice" type.
572 # No type given? "string" is the most sensible default.
575 # Allow type objects as an alternative to their names.
576 if type(self
.type) is type:
577 self
.type = self
.type.__name
__
578 if self
.type == "str":
581 if self
.type not in self
.TYPES
:
582 raise OptionError("invalid option type: %r" % self
.type, self
)
583 if self
.action
not in self
.TYPED_ACTIONS
:
585 "must not supply a type for action %r" % self
.action
, self
)
587 def _check_choice(self
):
588 if self
.type == "choice":
589 if self
.choices
is None:
591 "must supply a list of choices for type 'choice'", self
)
592 elif type(self
.choices
) not in (tuple, list):
594 "choices must be a list of strings ('%s' supplied)"
595 % str(type(self
.choices
)).split("'")[1], self
)
596 elif self
.choices
is not None:
598 "must not supply choices for type %r" % self
.type, self
)
600 def _check_dest(self
):
601 # No destination given, and we need one for this action. The
602 # self.type check is for callbacks that take a value.
603 takes_value
= (self
.action
in self
.STORE_ACTIONS
or
604 self
.type is not None)
605 if self
.dest
is None and takes_value
:
607 # Glean a destination from the first long option string,
608 # or from the first short option string if no long options.
610 # eg. "--foo-bar" -> "foo_bar"
611 self
.dest
= self
._long
_opts
[0][2:].replace('-', '_')
613 self
.dest
= self
._short
_opts
[0][1]
615 def _check_const(self
):
616 if self
.action
!= "store_const" and self
.const
is not None:
618 "'const' must not be supplied for action %r" % self
.action
,
621 def _check_nargs(self
):
622 if self
.action
in self
.TYPED_ACTIONS
:
623 if self
.nargs
is None:
625 elif self
.nargs
is not None:
627 "'nargs' must not be supplied for action %r" % self
.action
,
630 def _check_callback(self
):
631 if self
.action
== "callback":
632 if not callable(self
.callback
):
634 "callback not callable: %r" % self
.callback
, self
)
635 if (self
.callback_args
is not None and
636 type(self
.callback_args
) is not tuple):
638 "callback_args, if supplied, must be a tuple: not %r"
639 % self
.callback_args
, self
)
640 if (self
.callback_kwargs
is not None and
641 type(self
.callback_kwargs
) is not dict):
643 "callback_kwargs, if supplied, must be a dict: not %r"
644 % self
.callback_kwargs
, self
)
646 if self
.callback
is not None:
648 "callback supplied (%r) for non-callback option"
649 % self
.callback
, self
)
650 if self
.callback_args
is not None:
652 "callback_args supplied for non-callback option", self
)
653 if self
.callback_kwargs
is not None:
655 "callback_kwargs supplied for non-callback option", self
)
658 CHECK_METHODS
= [_check_action
,
667 # -- Miscellaneous methods -----------------------------------------
670 return "/".join(self
._short
_opts
+ self
._long
_opts
)
674 def takes_value(self
):
675 return self
.type is not None
677 def get_opt_string(self
):
679 return self
._long
_opts
[0]
681 return self
._short
_opts
[0]
684 # -- Processing methods --------------------------------------------
686 def check_value(self
, opt
, value
):
687 checker
= self
.TYPE_CHECKER
.get(self
.type)
691 return checker(self
, opt
, value
)
693 def convert_value(self
, opt
, value
):
694 if value
is not None:
696 return self
.check_value(opt
, value
)
698 return tuple([self
.check_value(opt
, v
) for v
in value
])
700 def process(self
, opt
, value
, values
, parser
):
702 # First, convert the value(s) to the right type. Howl if any
703 # value(s) are bogus.
704 value
= self
.convert_value(opt
, value
)
706 # And then take whatever action is expected of us.
707 # This is a separate method to make life easier for
708 # subclasses to add new actions.
709 return self
.take_action(
710 self
.action
, self
.dest
, opt
, value
, values
, parser
)
712 def take_action(self
, action
, dest
, opt
, value
, values
, parser
):
713 if action
== "store":
714 setattr(values
, dest
, value
)
715 elif action
== "store_const":
716 setattr(values
, dest
, self
.const
)
717 elif action
== "store_true":
718 setattr(values
, dest
, True)
719 elif action
== "store_false":
720 setattr(values
, dest
, False)
721 elif action
== "append":
722 values
.ensure_value(dest
, []).append(value
)
723 elif action
== "count":
724 setattr(values
, dest
, values
.ensure_value(dest
, 0) + 1)
725 elif action
== "callback":
726 args
= self
.callback_args
or ()
727 kwargs
= self
.callback_kwargs
or {}
728 self
.callback(self
, opt
, value
, parser
, *args
, **kwargs
)
729 elif action
== "help":
732 elif action
== "version":
733 parser
.print_version()
736 raise RuntimeError, "unknown action %r" % self
.action
743 SUPPRESS_HELP
= "SUPPRESS"+"HELP"
744 SUPPRESS_USAGE
= "SUPPRESS"+"USAGE"
746 # For compatibility with Python 2.2
750 (True, False) = (1, 0)
754 basestring
= (str, unicode)
759 def __init__(self
, defaults
=None):
761 for (attr
, val
) in defaults
.items():
762 setattr(self
, attr
, val
)
765 return str(self
.__dict
__)
769 def __eq__(self
, other
):
770 if isinstance(other
, Values
):
771 return self
.__dict
__ == other
.__dict
__
772 elif isinstance(other
, dict):
773 return self
.__dict
__ == other
777 def __ne__(self
, other
):
778 return not (self
== other
)
780 def _update_careful(self
, dict):
782 Update the option values from an arbitrary dictionary, but only
783 use keys from dict that already have a corresponding attribute
784 in self. Any keys in dict without a corresponding attribute
785 are silently ignored.
787 for attr
in dir(self
):
788 if dict.has_key(attr
):
791 setattr(self
, attr
, dval
)
793 def _update_loose(self
, dict):
795 Update the option values from an arbitrary dictionary,
796 using all keys from the dictionary regardless of whether
797 they have a corresponding attribute in self or not.
799 self
.__dict
__.update(dict)
801 def _update(self
, dict, mode
):
802 if mode
== "careful":
803 self
._update
_careful
(dict)
804 elif mode
== "loose":
805 self
._update
_loose
(dict)
807 raise ValueError, "invalid update mode: %r" % mode
809 def read_module(self
, modname
, mode
="careful"):
811 mod
= sys
.modules
[modname
]
812 self
._update
(vars(mod
), mode
)
814 def read_file(self
, filename
, mode
="careful"):
816 execfile(filename
, vars)
817 self
._update
(vars, mode
)
819 def ensure_value(self
, attr
, value
):
820 if not hasattr(self
, attr
) or getattr(self
, attr
) is None:
821 setattr(self
, attr
, value
)
822 return getattr(self
, attr
)
825 class OptionContainer
:
831 standard_option_list : [Option]
832 list of standard options that will be accepted by all instances
833 of this parser class (intended to be overridden by subclasses).
836 option_list : [Option]
837 the list of Option objects contained by this OptionContainer
838 _short_opt : { string : Option }
839 dictionary mapping short option strings, eg. "-f" or "-X",
840 to the Option instances that implement them. If an Option
841 has multiple short option strings, it will appears in this
842 dictionary multiple times. [1]
843 _long_opt : { string : Option }
844 dictionary mapping long option strings, eg. "--file" or
845 "--exclude", to the Option instances that implement them.
846 Again, a given Option can occur multiple times in this
848 defaults : { string : any }
849 dictionary mapping option destination names to default
850 values for each destination [1]
852 [1] These mappings are common to (shared by) all components of the
853 controlling OptionParser, where they are initially created.
857 def __init__(self
, option_class
, conflict_handler
, description
):
858 # Initialize the option list and related data structures.
859 # This method must be provided by subclasses, and it must
860 # initialize at least the following instance attributes:
861 # option_list, _short_opt, _long_opt, defaults.
862 self
._create
_option
_list
()
864 self
.option_class
= option_class
865 self
.set_conflict_handler(conflict_handler
)
866 self
.set_description(description
)
868 def _create_option_mappings(self
):
869 # For use by OptionParser constructor -- create the master
870 # option mappings used by this OptionParser and all
871 # OptionGroups that it owns.
872 self
._short
_opt
= {} # single letter -> Option instance
873 self
._long
_opt
= {} # long option -> Option instance
874 self
.defaults
= {} # maps option dest -> default value
877 def _share_option_mappings(self
, parser
):
878 # For use by OptionGroup constructor -- use shared option
879 # mappings from the OptionParser that owns this OptionGroup.
880 self
._short
_opt
= parser
._short
_opt
881 self
._long
_opt
= parser
._long
_opt
882 self
.defaults
= parser
.defaults
884 def set_conflict_handler(self
, handler
):
885 if handler
not in ("error", "resolve"):
886 raise ValueError, "invalid conflict_resolution value %r" % handler
887 self
.conflict_handler
= handler
889 def set_description(self
, description
):
890 self
.description
= description
892 def get_description(self
):
893 return self
.description
896 # -- Option-adding methods -----------------------------------------
898 def _check_conflict(self
, option
):
900 for opt
in option
._short
_opts
:
901 if self
._short
_opt
.has_key(opt
):
902 conflict_opts
.append((opt
, self
._short
_opt
[opt
]))
903 for opt
in option
._long
_opts
:
904 if self
._long
_opt
.has_key(opt
):
905 conflict_opts
.append((opt
, self
._long
_opt
[opt
]))
908 handler
= self
.conflict_handler
909 if handler
== "error":
910 raise OptionConflictError(
911 "conflicting option string(s): %s"
912 % ", ".join([co
[0] for co
in conflict_opts
]),
914 elif handler
== "resolve":
915 for (opt
, c_option
) in conflict_opts
:
916 if opt
.startswith("--"):
917 c_option
._long
_opts
.remove(opt
)
918 del self
._long
_opt
[opt
]
920 c_option
._short
_opts
.remove(opt
)
921 del self
._short
_opt
[opt
]
922 if not (c_option
._short
_opts
or c_option
._long
_opts
):
923 c_option
.container
.option_list
.remove(c_option
)
925 def add_option(self
, *args
, **kwargs
):
926 """add_option(Option)
927 add_option(opt_str, ..., kwarg=val, ...)
929 if type(args
[0]) is str:
930 option
= self
.option_class(*args
, **kwargs
)
931 elif len(args
) == 1 and not kwargs
:
933 if not isinstance(option
, Option
):
934 raise TypeError, "not an Option instance: %r" % option
936 raise TypeError, "invalid arguments"
938 self
._check
_conflict
(option
)
940 self
.option_list
.append(option
)
941 option
.container
= self
942 for opt
in option
._short
_opts
:
943 self
._short
_opt
[opt
] = option
944 for opt
in option
._long
_opts
:
945 self
._long
_opt
[opt
] = option
947 if option
.dest
is not None: # option has a dest, we need a default
948 if option
.default
is not NO_DEFAULT
:
949 self
.defaults
[option
.dest
] = option
.default
950 elif not self
.defaults
.has_key(option
.dest
):
951 self
.defaults
[option
.dest
] = None
955 def add_options(self
, option_list
):
956 for option
in option_list
:
957 self
.add_option(option
)
959 # -- Option query/removal methods ----------------------------------
961 def get_option(self
, opt_str
):
962 return (self
._short
_opt
.get(opt_str
) or
963 self
._long
_opt
.get(opt_str
))
965 def has_option(self
, opt_str
):
966 return (self
._short
_opt
.has_key(opt_str
) or
967 self
._long
_opt
.has_key(opt_str
))
969 def remove_option(self
, opt_str
):
970 option
= self
._short
_opt
.get(opt_str
)
972 option
= self
._long
_opt
.get(opt_str
)
974 raise ValueError("no such option %r" % opt_str
)
976 for opt
in option
._short
_opts
:
977 del self
._short
_opt
[opt
]
978 for opt
in option
._long
_opts
:
979 del self
._long
_opt
[opt
]
980 option
.container
.option_list
.remove(option
)
983 # -- Help-formatting methods ---------------------------------------
985 def format_option_help(self
, formatter
):
986 if not self
.option_list
:
989 for option
in self
.option_list
:
990 if not option
.help is SUPPRESS_HELP
:
991 result
.append(formatter
.format_option(option
))
992 return "".join(result
)
994 def format_description(self
, formatter
):
995 return formatter
.format_description(self
.get_description())
997 def format_help(self
, formatter
):
1000 result
.append(self
.format_description(formatter
))
1001 if self
.option_list
:
1002 result
.append(self
.format_option_help(formatter
))
1003 return "\n".join(result
)
1006 class OptionGroup (OptionContainer
):
1008 def __init__(self
, parser
, title
, description
=None):
1009 self
.parser
= parser
1010 OptionContainer
.__init
__(
1011 self
, parser
.option_class
, parser
.conflict_handler
, description
)
1014 def _create_option_list(self
):
1015 self
.option_list
= []
1016 self
._share
_option
_mappings
(self
.parser
)
1018 def set_title(self
, title
):
1021 # -- Help-formatting methods ---------------------------------------
1023 def format_help(self
, formatter
):
1024 result
= formatter
.format_heading(self
.title
)
1026 result
+= OptionContainer
.format_help(self
, formatter
)
1031 class OptionParser (OptionContainer
):
1035 standard_option_list : [Option]
1036 list of standard options that will be accepted by all instances
1037 of this parser class (intended to be overridden by subclasses).
1039 Instance attributes:
1041 a usage string for your program. Before it is displayed
1042 to the user, "%prog" will be expanded to the name of
1043 your program (self.prog or os.path.basename(sys.argv[0])).
1045 the name of the current program (to override
1046 os.path.basename(sys.argv[0])).
1048 option_groups : [OptionGroup]
1049 list of option groups in this parser (option groups are
1050 irrelevant for parsing the command-line, but very useful
1051 for generating help)
1053 allow_interspersed_args : bool = true
1054 if true, positional arguments may be interspersed with options.
1055 Assuming -a and -b each take a single argument, the command-line
1056 -ablah foo bar -bboo baz
1057 will be interpreted the same as
1058 -ablah -bboo -- foo bar baz
1059 If this flag were false, that command line would be interpreted as
1060 -ablah -- foo bar -bboo baz
1061 -- ie. we stop processing options as soon as we see the first
1062 non-option argument. (This is the tradition followed by
1063 Python's getopt module, Perl's Getopt::Std, and other argument-
1064 parsing libraries, but it is generally annoying to users.)
1066 process_default_values : bool = true
1067 if true, option default values are processed similarly to option
1068 values from the command line: that is, they are passed to the
1069 type-checking function for the option's type (as long as the
1070 default value is a string). (This really only matters if you
1071 have defined custom types; see SF bug #955889.) Set it to false
1072 to restore the behaviour of Optik 1.4.1 and earlier.
1075 the argument list currently being parsed. Only set when
1076 parse_args() is active, and continually trimmed down as
1077 we consume arguments. Mainly there for the benefit of
1080 the list of leftover arguments that we have skipped while
1081 parsing options. If allow_interspersed_args is false, this
1082 list is always empty.
1084 the set of option values currently being accumulated. Only
1085 set when parse_args() is active. Also mainly for callbacks.
1087 Because of the 'rargs', 'largs', and 'values' attributes,
1088 OptionParser is not thread-safe. If, for some perverse reason, you
1089 need to parse command-line arguments simultaneously in different
1090 threads, use different OptionParser instances.
1094 standard_option_list
= []
1099 option_class
=Option
,
1101 conflict_handler
="error",
1104 add_help_option
=True,
1106 OptionContainer
.__init
__(
1107 self
, option_class
, conflict_handler
, description
)
1108 self
.set_usage(usage
)
1110 self
.version
= version
1111 self
.allow_interspersed_args
= True
1112 self
.process_default_values
= True
1113 if formatter
is None:
1114 formatter
= IndentedHelpFormatter()
1115 self
.formatter
= formatter
1116 self
.formatter
.set_parser(self
)
1118 # Populate the option list; initial sources are the
1119 # standard_option_list class attribute, the 'option_list'
1120 # argument, and (if applicable) the _add_version_option() and
1121 # _add_help_option() methods.
1122 self
._populate
_option
_list
(option_list
,
1123 add_help
=add_help_option
)
1125 self
._init
_parsing
_state
()
1127 # -- Private methods -----------------------------------------------
1128 # (used by our or OptionContainer's constructor)
1130 def _create_option_list(self
):
1131 self
.option_list
= []
1132 self
.option_groups
= []
1133 self
._create
_option
_mappings
()
1135 def _add_help_option(self
):
1136 self
.add_option("-h", "--help",
1138 help=_("show this help message and exit"))
1140 def _add_version_option(self
):
1141 self
.add_option("--version",
1143 help=_("show program's version number and exit"))
1145 def _populate_option_list(self
, option_list
, add_help
=True):
1146 if self
.standard_option_list
:
1147 self
.add_options(self
.standard_option_list
)
1149 self
.add_options(option_list
)
1151 self
._add
_version
_option
()
1153 self
._add
_help
_option
()
1155 def _init_parsing_state(self
):
1156 # These are set in parse_args() for the convenience of callbacks.
1162 # -- Simple modifier methods ---------------------------------------
1164 def set_usage(self
, usage
):
1166 self
.usage
= _("%prog [options]")
1167 elif usage
is SUPPRESS_USAGE
:
1169 # For backwards compatibility with Optik 1.3 and earlier.
1170 elif usage
.startswith("usage:" + " "):
1171 self
.usage
= usage
[7:]
1175 def enable_interspersed_args(self
):
1176 self
.allow_interspersed_args
= True
1178 def disable_interspersed_args(self
):
1179 self
.allow_interspersed_args
= False
1181 def set_process_default_values(self
, process
):
1182 self
.process_default_values
= process
1184 def set_default(self
, dest
, value
):
1185 self
.defaults
[dest
] = value
1187 def set_defaults(self
, **kwargs
):
1188 self
.defaults
.update(kwargs
)
1190 def _get_all_options(self
):
1191 options
= self
.option_list
[:]
1192 for group
in self
.option_groups
:
1193 options
.extend(group
.option_list
)
1196 def get_default_values(self
):
1197 if not self
.process_default_values
:
1198 # Old, pre-Optik 1.5 behaviour.
1199 return Values(self
.defaults
)
1201 defaults
= self
.defaults
.copy()
1202 for option
in self
._get
_all
_options
():
1203 default
= defaults
.get(option
.dest
)
1204 if isinstance(default
, basestring
):
1205 opt_str
= option
.get_opt_string()
1206 defaults
[option
.dest
] = option
.check_value(opt_str
, default
)
1208 return Values(defaults
)
1211 # -- OptionGroup methods -------------------------------------------
1213 def add_option_group(self
, *args
, **kwargs
):
1214 # XXX lots of overlap with OptionContainer.add_option()
1215 if type(args
[0]) is str:
1216 group
= OptionGroup(self
, *args
, **kwargs
)
1217 elif len(args
) == 1 and not kwargs
:
1219 if not isinstance(group
, OptionGroup
):
1220 raise TypeError, "not an OptionGroup instance: %r" % group
1221 if group
.parser
is not self
:
1222 raise ValueError, "invalid OptionGroup (wrong parser)"
1224 raise TypeError, "invalid arguments"
1226 self
.option_groups
.append(group
)
1229 def get_option_group(self
, opt_str
):
1230 option
= (self
._short
_opt
.get(opt_str
) or
1231 self
._long
_opt
.get(opt_str
))
1232 if option
and option
.container
is not self
:
1233 return option
.container
1237 # -- Option-parsing methods ----------------------------------------
1239 def _get_args(self
, args
):
1243 return args
[:] # don't modify caller's list
1245 def parse_args(self
, args
=None, values
=None):
1247 parse_args(args : [string] = sys.argv[1:],
1248 values : Values = None)
1249 -> (values : Values, args : [string])
1251 Parse the command-line options found in 'args' (default:
1252 sys.argv[1:]). Any errors result in a call to 'error()', which
1253 by default prints the usage message to stderr and calls
1254 sys.exit() with an error message. On success returns a pair
1255 (values, args) where 'values' is an Values instance (with all
1256 your option values) and 'args' is the list of arguments left
1257 over after parsing options.
1259 rargs
= self
._get
_args
(args
)
1261 values
= self
.get_default_values()
1263 # Store the halves of the argument list as attributes for the
1264 # convenience of callbacks:
1266 # the rest of the command-line (the "r" stands for
1267 # "remaining" or "right-hand")
1269 # the leftover arguments -- ie. what's left after removing
1270 # options and their arguments (the "l" stands for "leftover"
1273 self
.largs
= largs
= []
1274 self
.values
= values
1277 stop
= self
._process
_args
(largs
, rargs
, values
)
1278 except (BadOptionError
, OptionValueError
), err
:
1281 args
= largs
+ rargs
1282 return self
.check_values(values
, args
)
1284 def check_values(self
, values
, args
):
1286 check_values(values : Values, args : [string])
1287 -> (values : Values, args : [string])
1289 Check that the supplied option values and leftover arguments are
1290 valid. Returns the option values and leftover arguments
1291 (possibly adjusted, possibly completely new -- whatever you
1292 like). Default implementation just returns the passed-in
1293 values; subclasses may override as desired.
1295 return (values
, args
)
1297 def _process_args(self
, largs
, rargs
, values
):
1298 """_process_args(largs : [string],
1302 Process command-line arguments and populate 'values', consuming
1303 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1304 false, stop at the first non-option argument. If true, accumulate any
1305 interspersed non-option arguments in 'largs'.
1309 # We handle bare "--" explicitly, and bare "-" is handled by the
1310 # standard arg handler since the short arg case ensures that the
1311 # len of the opt string is greater than 1.
1315 elif arg
[0:2] == "--":
1316 # process a single long option (possibly with value(s))
1317 self
._process
_long
_opt
(rargs
, values
)
1318 elif arg
[:1] == "-" and len(arg
) > 1:
1319 # process a cluster of short options (possibly with
1320 # value(s) for the last one only)
1321 self
._process
_short
_opts
(rargs
, values
)
1322 elif self
.allow_interspersed_args
:
1326 return # stop now, leave this arg in rargs
1328 # Say this is the original argument list:
1329 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1331 # (we are about to process arg(i)).
1333 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1334 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1335 # been removed from largs).
1337 # The while loop will usually consume 1 or more arguments per pass.
1338 # If it consumes 1 (eg. arg is an option that takes no arguments),
1339 # then after _process_arg() is done the situation is:
1341 # largs = subset of [arg0, ..., arg(i)]
1342 # rargs = [arg(i+1), ..., arg(N-1)]
1344 # If allow_interspersed_args is false, largs will always be
1345 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1346 # not a very interesting subset!
1348 def _match_long_opt(self
, opt
):
1349 """_match_long_opt(opt : string) -> string
1351 Determine which long option string 'opt' matches, ie. which one
1352 it is an unambiguous abbrevation for. Raises BadOptionError if
1353 'opt' doesn't unambiguously match any long option string.
1355 return _match_abbrev(opt
, self
._long
_opt
)
1357 def _process_long_opt(self
, rargs
, values
):
1360 # Value explicitly attached to arg? Pretend it's the next
1363 (opt
, next_arg
) = arg
.split("=", 1)
1364 rargs
.insert(0, next_arg
)
1365 had_explicit_value
= True
1368 had_explicit_value
= False
1370 opt
= self
._match
_long
_opt
(opt
)
1371 option
= self
._long
_opt
[opt
]
1372 if option
.takes_value():
1373 nargs
= option
.nargs
1374 if len(rargs
) < nargs
:
1376 self
.error(_("%s option requires an argument") % opt
)
1378 self
.error(_("%s option requires %d arguments")
1381 value
= rargs
.pop(0)
1383 value
= tuple(rargs
[0:nargs
])
1386 elif had_explicit_value
:
1387 self
.error(_("%s option does not take a value") % opt
)
1392 option
.process(opt
, value
, values
, self
)
1394 def _process_short_opts(self
, rargs
, values
):
1400 option
= self
._short
_opt
.get(opt
)
1401 i
+= 1 # we have consumed a character
1404 self
.error(_("no such option: %s") % opt
)
1405 if option
.takes_value():
1406 # Any characters left in arg? Pretend they're the
1407 # next arg, and stop consuming characters of arg.
1409 rargs
.insert(0, arg
[i
:])
1412 nargs
= option
.nargs
1413 if len(rargs
) < nargs
:
1415 self
.error(_("%s option requires an argument") % opt
)
1417 self
.error(_("%s option requires %d arguments")
1420 value
= rargs
.pop(0)
1422 value
= tuple(rargs
[0:nargs
])
1425 else: # option doesn't take a value
1428 option
.process(opt
, value
, values
, self
)
1434 # -- Feedback methods ----------------------------------------------
1436 def get_prog_name(self
):
1437 if self
.prog
is None:
1438 return os
.path
.basename(sys
.argv
[0])
1442 def expand_prog_name(self
, s
):
1443 return s
.replace("%prog", self
.get_prog_name())
1445 def get_description(self
):
1446 return self
.expand_prog_name(self
.description
)
1448 def exit(self
, status
=0, msg
=None):
1450 sys
.stderr
.write(msg
)
1453 def error(self
, msg
):
1454 """error(msg : string)
1456 Print a usage message incorporating 'msg' to stderr and exit.
1457 If you override this in a subclass, it should not return -- it
1458 should either exit or raise an exception.
1460 self
.print_usage(sys
.stderr
)
1461 self
.exit(2, "%s: error: %s\n" % (self
.get_prog_name(), msg
))
1463 def get_usage(self
):
1465 return self
.formatter
.format_usage(
1466 self
.expand_prog_name(self
.usage
))
1470 def print_usage(self
, file=None):
1471 """print_usage(file : file = stdout)
1473 Print the usage message for the current program (self.usage) to
1474 'file' (default stdout). Any occurence of the string "%prog" in
1475 self.usage is replaced with the name of the current program
1476 (basename of sys.argv[0]). Does nothing if self.usage is empty
1480 print >>file, self
.get_usage()
1482 def get_version(self
):
1484 return self
.expand_prog_name(self
.version
)
1488 def print_version(self
, file=None):
1489 """print_version(file : file = stdout)
1491 Print the version message for this program (self.version) to
1492 'file' (default stdout). As with print_usage(), any occurence
1493 of "%prog" in self.version is replaced by the current program's
1494 name. Does nothing if self.version is empty or undefined.
1497 print >>file, self
.get_version()
1499 def format_option_help(self
, formatter
=None):
1500 if formatter
is None:
1501 formatter
= self
.formatter
1502 formatter
.store_option_strings(self
)
1504 result
.append(formatter
.format_heading(_("options")))
1506 if self
.option_list
:
1507 result
.append(OptionContainer
.format_option_help(self
, formatter
))
1509 for group
in self
.option_groups
:
1510 result
.append(group
.format_help(formatter
))
1513 # Drop the last "\n", or the header if no options or option groups:
1514 return "".join(result
[:-1])
1516 def format_help(self
, formatter
=None):
1517 if formatter
is None:
1518 formatter
= self
.formatter
1521 result
.append(self
.get_usage() + "\n")
1522 if self
.description
:
1523 result
.append(self
.format_description(formatter
) + "\n")
1524 result
.append(self
.format_option_help(formatter
))
1525 return "".join(result
)
1527 def print_help(self
, file=None):
1528 """print_help(file : file = stdout)
1530 Print an extended help message, listing all options and any
1531 help text provided with them, to 'file' (default stdout).
1535 file.write(self
.format_help())
1537 # class OptionParser
1540 def _match_abbrev(s
, wordmap
):
1541 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1543 Return the string key in 'wordmap' for which 's' is an unambiguous
1544 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1545 'words', raise BadOptionError.
1547 # Is there an exact match?
1548 if wordmap
.has_key(s
):
1551 # Isolate all words with s as a prefix.
1552 possibilities
= [word
for word
in wordmap
.keys()
1553 if word
.startswith(s
)]
1554 # No exact match, so there had better be just one possibility.
1555 if len(possibilities
) == 1:
1556 return possibilities
[0]
1557 elif not possibilities
:
1558 raise BadOptionError(_("no such option: %s") % s
)
1560 # More than one possible completion: ambiguous prefix.
1561 raise BadOptionError(_("ambiguous option: %s (%s?)")
1562 % (s
, ", ".join(possibilities
)))
1565 # Some day, there might be many Option classes. As of Optik 1.3, the
1566 # preferred way to instantiate Options is indirectly, via make_option(),
1567 # which will become a factory function when there are many Option
1569 make_option
= Option