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