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+"
31 'IndentedHelpFormatter',
32 'TitledHelpFormatter',
35 'OptionConflictError',
40 Copyright (c) 2001-2003 Gregory P. Ward. All rights reserved.
42 Redistribution and use in source and binary forms, with or without
43 modification, are permitted provided that the following conditions are
46 * Redistributions of source code must retain the above copyright
47 notice, this list of conditions and the following disclaimer.
49 * Redistributions in binary form must reproduce the above copyright
50 notice, this list of conditions and the following disclaimer in the
51 documentation and/or other materials provided with the distribution.
53 * Neither the name of the author nor the names of its
54 contributors may be used to endorse or promote products derived from
55 this software without specific prior written permission.
57 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
58 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
59 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
60 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
61 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
62 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
63 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
64 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
65 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
66 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
67 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
74 class OptParseError (Exception):
75 def __init__ (self
, msg
):
82 class OptionError (OptParseError
):
84 Raised if an Option instance is created with invalid or
85 inconsistent arguments.
88 def __init__ (self
, msg
, option
):
90 self
.option_id
= str(option
)
94 return "option %s: %s" % (self
.option_id
, self
.msg
)
98 class OptionConflictError (OptionError
):
100 Raised if conflicting options are added to an OptionParser.
103 class OptionValueError (OptParseError
):
105 Raised if an invalid option value is encountered on the command
109 class BadOptionError (OptParseError
):
111 Raised if an invalid or ambiguous option is seen on the command-line.
118 Abstract base class for formatting option help. OptionParser
119 instances should use one of the HelpFormatter subclasses for
120 formatting help; by default IndentedHelpFormatter is used.
123 indent_increment : int
124 the number of columns to indent per nesting level
125 max_help_position : int
126 the maximum starting column for option help text
128 the calculated starting column for option help text;
129 initially the same as the maximum
131 total number of columns for output
133 current indentation level
135 current indentation level (in columns)
137 number of columns available for option help text (calculated)
145 self
.indent_increment
= indent_increment
146 self
.help_position
= self
.max_help_position
= max_help_position
148 self
.current_indent
= 0
150 self
.help_width
= width
- max_help_position
151 self
.short_first
= short_first
154 self
.current_indent
+= self
.indent_increment
158 self
.current_indent
-= self
.indent_increment
159 assert self
.current_indent
>= 0, "Indent decreased below 0."
162 def format_usage (self
, usage
):
163 raise NotImplementedError, "subclasses must implement"
165 def format_heading (self
, heading
):
166 raise NotImplementedError, "subclasses must implement"
168 def format_description (self
, description
):
169 desc_width
= self
.width
- self
.current_indent
170 indent
= " "*self
.current_indent
171 return textwrap
.fill(description
, desc_width
,
172 initial_indent
=indent
,
173 subsequent_indent
=indent
)
175 def format_option (self
, option
):
176 # The help for each option consists of two parts:
177 # * the opt strings and metavars
178 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
179 # * the user-supplied help string
180 # eg. ("turn on expert mode", "read data from FILENAME")
182 # If possible, we write both of these on the same line:
183 # -x turn on expert mode
185 # But if the opt string list is too long, we put the help
186 # string on a second line, indented to the same column it would
187 # start in if it fit on the first line.
188 # -fFILENAME, --file=FILENAME
189 # read data from FILENAME
191 opts
= option
.option_strings
192 opt_width
= self
.help_position
- self
.current_indent
- 2
193 if len(opts
) > opt_width
:
194 opts
= "%*s%s\n" % (self
.current_indent
, "", opts
)
195 indent_first
= self
.help_position
196 else: # start help on same line as opts
197 opts
= "%*s%-*s " % (self
.current_indent
, "", opt_width
, opts
)
201 help_lines
= textwrap
.wrap(option
.help, self
.help_width
)
202 result
.append("%*s%s\n" % (indent_first
, "", help_lines
[0]))
203 result
.extend(["%*s%s\n" % (self
.help_position
, "", line
)
204 for line
in help_lines
[1:]])
205 elif opts
[-1] != "\n":
207 return "".join(result
)
209 def store_option_strings (self
, parser
):
212 for opt
in parser
.option_list
:
213 strings
= self
.format_option_strings(opt
)
214 opt
.option_strings
= strings
215 max_len
= max(max_len
, len(strings
) + self
.current_indent
)
217 for group
in parser
.option_groups
:
218 for opt
in group
.option_list
:
219 strings
= self
.format_option_strings(opt
)
220 opt
.option_strings
= strings
221 max_len
= max(max_len
, len(strings
) + self
.current_indent
)
224 self
.help_position
= min(max_len
+ 2, self
.max_help_position
)
226 def format_option_strings (self
, option
):
227 """Return a comma-separated list of option strings & metavariables."""
228 if option
.takes_value():
229 metavar
= option
.metavar
or option
.dest
.upper()
230 short_opts
= [sopt
+ metavar
for sopt
in option
._short
_opts
]
231 long_opts
= [lopt
+ "=" + metavar
for lopt
in option
._long
_opts
]
233 short_opts
= option
._short
_opts
234 long_opts
= option
._long
_opts
237 opts
= short_opts
+ long_opts
239 opts
= long_opts
+ short_opts
241 return ", ".join(opts
)
243 class IndentedHelpFormatter (HelpFormatter
):
244 """Format help with indented section bodies.
249 max_help_position
=24,
252 HelpFormatter
.__init
__(
253 self
, indent_increment
, max_help_position
, width
, short_first
)
255 def format_usage (self
, usage
):
256 return "usage: %s\n" % usage
258 def format_heading (self
, heading
):
259 return "%*s%s:\n" % (self
.current_indent
, "", heading
)
262 class TitledHelpFormatter (HelpFormatter
):
263 """Format help with underlined section headers.
268 max_help_position
=24,
271 HelpFormatter
.__init
__ (
272 self
, indent_increment
, max_help_position
, width
, short_first
)
274 def format_usage (self
, usage
):
275 return "%s %s\n" % (self
.format_heading("Usage"), usage
)
277 def format_heading (self
, heading
):
278 return "%s\n%s\n" % (heading
, "=-"[self
.level
] * len(heading
))
281 _builtin_cvt
= { "int" : (int, "integer"),
282 "long" : (long, "long integer"),
283 "float" : (float, "floating-point"),
284 "complex" : (complex, "complex") }
286 def check_builtin (option
, opt
, value
):
287 (cvt
, what
) = _builtin_cvt
[option
.type]
291 raise OptionValueError(
292 #"%s: invalid %s argument %r" % (opt, what, value))
293 "option %s: invalid %s value: %r" % (opt
, what
, value
))
295 def check_choice(option
, opt
, value
):
296 if value
in option
.choices
:
299 choices
= ", ".join(map(repr, option
.choices
))
300 raise OptionValueError(
301 "option %s: invalid choice: %r (choose from %s)"
302 % (opt
, value
, choices
))
304 # Not supplying a default is different from a default of None,
305 # so we need an explicit "not supplied" value.
306 NO_DEFAULT
= "NO"+"DEFAULT"
312 _short_opts : [string]
313 _long_opts : [string]
323 callback_args : (any*)
324 callback_kwargs : { string : any }
329 # The list of instance attributes that may be set through
330 # keyword args to the constructor.
344 # The set of actions allowed by option parsers. Explicitly listed
345 # here so the constructor can validate its arguments.
356 # The set of actions that involve storing a value somewhere;
357 # also listed just for constructor argument validation. (If
358 # the action is one of these, there must be a destination.)
359 STORE_ACTIONS
= ("store",
366 # The set of actions for which it makes sense to supply a value
367 # type, ie. where we expect an argument to this option.
368 TYPED_ACTIONS
= ("store",
372 # The set of known types for option parsers. Again, listed here for
373 # constructor argument validation.
374 TYPES
= ("string", "int", "long", "float", "complex", "choice")
376 # Dictionary of argument checking functions, which convert and
377 # validate option arguments according to the option type.
379 # Signature of checking functions is:
380 # check(option : Option, opt : string, value : string) -> any
382 # option is the Option instance calling the checker
383 # opt is the actual option seen on the command-line
384 # (eg. "-a", "--file")
385 # value is the option argument seen on the command-line
387 # The return value should be in the appropriate Python type
388 # for option.type -- eg. an integer if option.type == "int".
390 # If no checker is defined for a type, arguments will be
391 # unchecked and remain strings.
392 TYPE_CHECKER
= { "int" : check_builtin
,
393 "long" : check_builtin
,
394 "float" : check_builtin
,
395 "complex" : check_builtin
,
396 "choice" : check_choice
,
400 # CHECK_METHODS is a list of unbound method objects; they are called
401 # by the constructor, in order, after all attributes are
402 # initialized. The list is created and filled in later, after all
403 # the methods are actually defined. (I just put it here because I
404 # like to define and document all class attributes in the same
405 # place.) Subclasses that add another _check_*() method should
406 # define their own CHECK_METHODS list that adds their check method
407 # to those from this class.
411 # -- Constructor/initialization methods ----------------------------
413 def __init__ (self
, *opts
, **attrs
):
414 # Set _short_opts, _long_opts attrs from 'opts' tuple.
415 # Have to be set now, in case no option strings are supplied.
416 self
._short
_opts
= []
418 opts
= self
._check
_opt
_strings
(opts
)
419 self
._set
_opt
_strings
(opts
)
421 # Set all other attrs (action, type, etc.) from 'attrs' dict
422 self
._set
_attrs
(attrs
)
424 # Check all the attributes we just set. There are lots of
425 # complicated interdependencies, but luckily they can be farmed
426 # out to the _check_*() methods listed in CHECK_METHODS -- which
427 # could be handy for subclasses! The one thing these all share
428 # is that they raise OptionError if they discover a problem.
429 for checker
in self
.CHECK_METHODS
:
432 def _check_opt_strings (self
, opts
):
433 # Filter out None because early versions of Optik had exactly
434 # one short option and one long option, either of which
436 opts
= filter(None, opts
)
438 raise TypeError("at least one option string must be supplied")
441 def _set_opt_strings (self
, opts
):
445 "invalid option string %r: "
446 "must be at least two characters long" % opt
, self
)
448 if not (opt
[0] == "-" and opt
[1] != "-"):
450 "invalid short option string %r: "
451 "must be of the form -x, (x any non-dash char)" % opt
,
453 self
._short
_opts
.append(opt
)
455 if not (opt
[0:2] == "--" and opt
[2] != "-"):
457 "invalid long option string %r: "
458 "must start with --, followed by non-dash" % opt
,
460 self
._long
_opts
.append(opt
)
462 def _set_attrs (self
, attrs
):
463 for attr
in self
.ATTRS
:
464 if attrs
.has_key(attr
):
465 setattr(self
, attr
, attrs
[attr
])
468 if attr
== 'default':
469 setattr(self
, attr
, NO_DEFAULT
)
471 setattr(self
, attr
, None)
474 "invalid keyword arguments: %s" % ", ".join(attrs
.keys()),
478 # -- Constructor validation methods --------------------------------
480 def _check_action (self
):
481 if self
.action
is None:
482 self
.action
= "store"
483 elif self
.action
not in self
.ACTIONS
:
484 raise OptionError("invalid action: %r" % self
.action
, self
)
486 def _check_type (self
):
487 if self
.type is None:
488 # XXX should factor out another class attr here: list of
489 # actions that *require* a type
490 if self
.action
in ("store", "append"):
491 if self
.choices
is not None:
492 # The "choices" attribute implies "choice" type.
495 # No type given? "string" is the most sensible default.
498 if self
.type not in self
.TYPES
:
499 raise OptionError("invalid option type: %r" % self
.type, self
)
500 if self
.action
not in self
.TYPED_ACTIONS
:
502 "must not supply a type for action %r" % self
.action
, self
)
504 def _check_choice(self
):
505 if self
.type == "choice":
506 if self
.choices
is None:
508 "must supply a list of choices for type 'choice'", self
)
509 elif type(self
.choices
) not in (types
.TupleType
, types
.ListType
):
511 "choices must be a list of strings ('%s' supplied)"
512 % str(type(self
.choices
)).split("'")[1], self
)
513 elif self
.choices
is not None:
515 "must not supply choices for type %r" % self
.type, self
)
517 def _check_dest (self
):
518 if self
.action
in self
.STORE_ACTIONS
and self
.dest
is None:
519 # No destination given, and we need one for this action.
520 # Glean a destination from the first long option string,
521 # or from the first short option string if no long options.
523 # eg. "--foo-bar" -> "foo_bar"
524 self
.dest
= self
._long
_opts
[0][2:].replace('-', '_')
526 self
.dest
= self
._short
_opts
[0][1]
528 def _check_const (self
):
529 if self
.action
!= "store_const" and self
.const
is not None:
531 "'const' must not be supplied for action %r" % self
.action
,
534 def _check_nargs (self
):
535 if self
.action
in self
.TYPED_ACTIONS
:
536 if self
.nargs
is None:
538 elif self
.nargs
is not None:
540 "'nargs' must not be supplied for action %r" % self
.action
,
543 def _check_callback (self
):
544 if self
.action
== "callback":
545 if not callable(self
.callback
):
547 "callback not callable: %r" % self
.callback
, self
)
548 if (self
.callback_args
is not None and
549 type(self
.callback_args
) is not types
.TupleType
):
551 "callback_args, if supplied, must be a tuple: not %r"
552 % self
.callback_args
, self
)
553 if (self
.callback_kwargs
is not None and
554 type(self
.callback_kwargs
) is not types
.DictType
):
556 "callback_kwargs, if supplied, must be a dict: not %r"
557 % self
.callback_kwargs
, self
)
559 if self
.callback
is not None:
561 "callback supplied (%r) for non-callback option"
562 % self
.callback
, self
)
563 if self
.callback_args
is not None:
565 "callback_args supplied for non-callback option", self
)
566 if self
.callback_kwargs
is not None:
568 "callback_kwargs supplied for non-callback option", self
)
571 CHECK_METHODS
= [_check_action
,
580 # -- Miscellaneous methods -----------------------------------------
583 return "/".join(self
._short
_opts
+ self
._long
_opts
)
585 def takes_value (self
):
586 return self
.type is not None
589 # -- Processing methods --------------------------------------------
591 def check_value (self
, opt
, value
):
592 checker
= self
.TYPE_CHECKER
.get(self
.type)
596 return checker(self
, opt
, value
)
598 def process (self
, opt
, value
, values
, parser
):
600 # First, convert the value(s) to the right type. Howl if any
601 # value(s) are bogus.
602 if value
is not None:
604 value
= self
.check_value(opt
, value
)
606 value
= tuple([self
.check_value(opt
, v
) for v
in value
])
608 # And then take whatever action is expected of us.
609 # This is a separate method to make life easier for
610 # subclasses to add new actions.
611 return self
.take_action(
612 self
.action
, self
.dest
, opt
, value
, values
, parser
)
614 def take_action (self
, action
, dest
, opt
, value
, values
, parser
):
615 if action
== "store":
616 setattr(values
, dest
, value
)
617 elif action
== "store_const":
618 setattr(values
, dest
, self
.const
)
619 elif action
== "store_true":
620 setattr(values
, dest
, True)
621 elif action
== "store_false":
622 setattr(values
, dest
, False)
623 elif action
== "append":
624 values
.ensure_value(dest
, []).append(value
)
625 elif action
== "count":
626 setattr(values
, dest
, values
.ensure_value(dest
, 0) + 1)
627 elif action
== "callback":
628 args
= self
.callback_args
or ()
629 kwargs
= self
.callback_kwargs
or {}
630 self
.callback(self
, opt
, value
, parser
, *args
, **kwargs
)
631 elif action
== "help":
634 elif action
== "version":
635 parser
.print_version()
638 raise RuntimeError, "unknown action %r" % self
.action
645 def get_prog_name ():
646 return os
.path
.basename(sys
.argv
[0])
649 SUPPRESS_HELP
= "SUPPRESS"+"HELP"
650 SUPPRESS_USAGE
= "SUPPRESS"+"USAGE"
652 STD_HELP_OPTION
= Option("-h", "--help",
654 help="show this help message and exit")
655 STD_VERSION_OPTION
= Option("--version",
657 help="show program's version number and exit")
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
):
892 desc
= self
.format_description(formatter
) + "\n"
895 return desc
+ self
.format_option_help(formatter
)
898 class OptionGroup (OptionContainer
):
900 def __init__ (self
, parser
, title
, description
=None):
902 OptionContainer
.__init
__(
903 self
, parser
.option_class
, parser
.conflict_handler
, description
)
906 def _create_option_list (self
):
907 self
.option_list
= []
908 self
._share
_option
_mappings
(self
.parser
)
910 def set_title (self
, title
):
913 # -- Help-formatting methods ---------------------------------------
915 def format_help (self
, formatter
):
916 result
= formatter
.format_heading(self
.title
)
918 result
+= OptionContainer
.format_help(self
, formatter
)
923 class OptionParser (OptionContainer
):
927 standard_option_list : [Option]
928 list of standard options that will be accepted by all instances
929 of this parser class (intended to be overridden by subclasses).
933 a usage string for your program. Before it is displayed
934 to the user, "%prog" will be expanded to the name of
935 your program (self.prog or os.path.basename(sys.argv[0])).
937 the name of the current program (to override
938 os.path.basename(sys.argv[0])).
940 allow_interspersed_args : boolean = true
941 if true, positional arguments may be interspersed with options.
942 Assuming -a and -b each take a single argument, the command-line
943 -ablah foo bar -bboo baz
944 will be interpreted the same as
945 -ablah -bboo -- foo bar baz
946 If this flag were false, that command line would be interpreted as
947 -ablah -- foo bar -bboo baz
948 -- ie. we stop processing options as soon as we see the first
949 non-option argument. (This is the tradition followed by
950 Python's getopt module, Perl's Getopt::Std, and other argument-
951 parsing libraries, but it is generally annoying to users.)
954 the argument list currently being parsed. Only set when
955 parse_args() is active, and continually trimmed down as
956 we consume arguments. Mainly there for the benefit of
959 the list of leftover arguments that we have skipped while
960 parsing options. If allow_interspersed_args is false, this
961 list is always empty.
963 the set of option values currently being accumulated. Only
964 set when parse_args() is active. Also mainly for callbacks.
966 Because of the 'rargs', 'largs', and 'values' attributes,
967 OptionParser is not thread-safe. If, for some perverse reason, you
968 need to parse command-line arguments simultaneously in different
969 threads, use different OptionParser instances.
973 standard_option_list
= []
980 conflict_handler
="error",
985 OptionContainer
.__init
__(
986 self
, option_class
, conflict_handler
, description
)
987 self
.set_usage(usage
)
989 self
.version
= version
990 self
.allow_interspersed_args
= 1
991 if formatter
is None:
992 formatter
= IndentedHelpFormatter()
993 self
.formatter
= formatter
995 # Populate the option list; initial sources are the
996 # standard_option_list class attribute, the 'option_list'
997 # argument, and the STD_VERSION_OPTION (if 'version' supplied)
998 # and STD_HELP_OPTION globals.
999 self
._populate
_option
_list
(option_list
,
1000 add_help
=add_help_option
)
1002 self
._init
_parsing
_state
()
1004 # -- Private methods -----------------------------------------------
1005 # (used by our or OptionContainer's constructor)
1007 def _create_option_list (self
):
1008 self
.option_list
= []
1009 self
.option_groups
= []
1010 self
._create
_option
_mappings
()
1012 def _populate_option_list (self
, option_list
, add_help
=1):
1013 if self
.standard_option_list
:
1014 self
.add_options(self
.standard_option_list
)
1016 self
.add_options(option_list
)
1018 self
.add_option(STD_VERSION_OPTION
)
1020 self
.add_option(STD_HELP_OPTION
)
1022 def _init_parsing_state (self
):
1023 # These are set in parse_args() for the convenience of callbacks.
1029 # -- Simple modifier methods ---------------------------------------
1031 def set_usage (self
, usage
):
1033 self
.usage
= "%prog [options]"
1034 elif usage
is SUPPRESS_USAGE
:
1036 elif usage
.startswith("usage: "):
1037 # for backwards compatibility with Optik 1.3 and earlier
1038 self
.usage
= usage
[7:]
1042 def enable_interspersed_args (self
):
1043 self
.allow_interspersed_args
= 1
1045 def disable_interspersed_args (self
):
1046 self
.allow_interspersed_args
= 0
1048 def set_default (self
, dest
, value
):
1049 self
.defaults
[dest
] = value
1051 def set_defaults (self
, **kwargs
):
1052 self
.defaults
.update(kwargs
)
1054 def get_default_values (self
):
1055 return Values(self
.defaults
)
1058 # -- OptionGroup methods -------------------------------------------
1060 def add_option_group (self
, *args
, **kwargs
):
1061 # XXX lots of overlap with OptionContainer.add_option()
1062 if type(args
[0]) is types
.StringType
:
1063 group
= OptionGroup(self
, *args
, **kwargs
)
1064 elif len(args
) == 1 and not kwargs
:
1066 if not isinstance(group
, OptionGroup
):
1067 raise TypeError, "not an OptionGroup instance: %r" % group
1068 if group
.parser
is not self
:
1069 raise ValueError, "invalid OptionGroup (wrong parser)"
1071 raise TypeError, "invalid arguments"
1073 self
.option_groups
.append(group
)
1076 def get_option_group (self
, opt_str
):
1077 option
= (self
._short
_opt
.get(opt_str
) or
1078 self
._long
_opt
.get(opt_str
))
1079 if option
and option
.container
is not self
:
1080 return option
.container
1084 # -- Option-parsing methods ----------------------------------------
1086 def _get_args (self
, args
):
1090 return args
[:] # don't modify caller's list
1092 def parse_args (self
, args
=None, values
=None):
1094 parse_args(args : [string] = sys.argv[1:],
1095 values : Values = None)
1096 -> (values : Values, args : [string])
1098 Parse the command-line options found in 'args' (default:
1099 sys.argv[1:]). Any errors result in a call to 'error()', which
1100 by default prints the usage message to stderr and calls
1101 sys.exit() with an error message. On success returns a pair
1102 (values, args) where 'values' is an Values instance (with all
1103 your option values) and 'args' is the list of arguments left
1104 over after parsing options.
1106 rargs
= self
._get
_args
(args
)
1108 values
= self
.get_default_values()
1110 # Store the halves of the argument list as attributes for the
1111 # convenience of callbacks:
1113 # the rest of the command-line (the "r" stands for
1114 # "remaining" or "right-hand")
1116 # the leftover arguments -- ie. what's left after removing
1117 # options and their arguments (the "l" stands for "leftover"
1120 self
.largs
= largs
= []
1121 self
.values
= values
1124 stop
= self
._process
_args
(largs
, rargs
, values
)
1125 except (BadOptionError
, OptionValueError
), err
:
1128 args
= largs
+ rargs
1129 return self
.check_values(values
, args
)
1131 def check_values (self
, values
, args
):
1133 check_values(values : Values, args : [string])
1134 -> (values : Values, args : [string])
1136 Check that the supplied option values and leftover arguments are
1137 valid. Returns the option values and leftover arguments
1138 (possibly adjusted, possibly completely new -- whatever you
1139 like). Default implementation just returns the passed-in
1140 values; subclasses may override as desired.
1142 return (values
, args
)
1144 def _process_args (self
, largs
, rargs
, values
):
1145 """_process_args(largs : [string],
1149 Process command-line arguments and populate 'values', consuming
1150 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1151 false, stop at the first non-option argument. If true, accumulate any
1152 interspersed non-option arguments in 'largs'.
1156 # We handle bare "--" explicitly, and bare "-" is handled by the
1157 # standard arg handler since the short arg case ensures that the
1158 # len of the opt string is greater than 1.
1162 elif arg
[0:2] == "--":
1163 # process a single long option (possibly with value(s))
1164 self
._process
_long
_opt
(rargs
, values
)
1165 elif arg
[:1] == "-" and len(arg
) > 1:
1166 # process a cluster of short options (possibly with
1167 # value(s) for the last one only)
1168 self
._process
_short
_opts
(rargs
, values
)
1169 elif self
.allow_interspersed_args
:
1173 return # stop now, leave this arg in rargs
1175 # Say this is the original argument list:
1176 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1178 # (we are about to process arg(i)).
1180 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1181 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1182 # been removed from largs).
1184 # The while loop will usually consume 1 or more arguments per pass.
1185 # If it consumes 1 (eg. arg is an option that takes no arguments),
1186 # then after _process_arg() is done the situation is:
1188 # largs = subset of [arg0, ..., arg(i)]
1189 # rargs = [arg(i+1), ..., arg(N-1)]
1191 # If allow_interspersed_args is false, largs will always be
1192 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1193 # not a very interesting subset!
1195 def _match_long_opt (self
, opt
):
1196 """_match_long_opt(opt : string) -> string
1198 Determine which long option string 'opt' matches, ie. which one
1199 it is an unambiguous abbrevation for. Raises BadOptionError if
1200 'opt' doesn't unambiguously match any long option string.
1202 return _match_abbrev(opt
, self
._long
_opt
)
1204 def _process_long_opt (self
, rargs
, values
):
1207 # Value explicitly attached to arg? Pretend it's the next
1210 (opt
, next_arg
) = arg
.split("=", 1)
1211 rargs
.insert(0, next_arg
)
1212 had_explicit_value
= 1
1215 had_explicit_value
= 0
1217 opt
= self
._match
_long
_opt
(opt
)
1218 option
= self
._long
_opt
[opt
]
1219 if option
.takes_value():
1220 nargs
= option
.nargs
1221 if len(rargs
) < nargs
:
1223 self
.error("%s option requires a value" % opt
)
1225 self
.error("%s option requires %d values"
1228 value
= rargs
.pop(0)
1230 value
= tuple(rargs
[0:nargs
])
1233 elif had_explicit_value
:
1234 self
.error("%s option does not take a value" % opt
)
1239 option
.process(opt
, value
, values
, self
)
1241 def _process_short_opts (self
, rargs
, values
):
1247 option
= self
._short
_opt
.get(opt
)
1248 i
+= 1 # we have consumed a character
1251 self
.error("no such option: %s" % opt
)
1252 if option
.takes_value():
1253 # Any characters left in arg? Pretend they're the
1254 # next arg, and stop consuming characters of arg.
1256 rargs
.insert(0, arg
[i
:])
1259 nargs
= option
.nargs
1260 if len(rargs
) < nargs
:
1262 self
.error("%s option requires a value" % opt
)
1264 self
.error("%s option requires %s values"
1267 value
= rargs
.pop(0)
1269 value
= tuple(rargs
[0:nargs
])
1272 else: # option doesn't take a value
1275 option
.process(opt
, value
, values
, self
)
1281 # -- Feedback methods ----------------------------------------------
1283 def error (self
, msg
):
1284 """error(msg : string)
1286 Print a usage message incorporating 'msg' to stderr and exit.
1287 If you override this in a subclass, it should not return -- it
1288 should either exit or raise an exception.
1290 self
.print_usage(sys
.stderr
)
1291 sys
.exit("%s: error: %s" % (get_prog_name(), msg
))
1293 def get_usage (self
):
1295 return self
.formatter
.format_usage(
1296 self
.usage
.replace("%prog", get_prog_name()))
1300 def print_usage (self
, file=None):
1301 """print_usage(file : file = stdout)
1303 Print the usage message for the current program (self.usage) to
1304 'file' (default stdout). Any occurence of the string "%prog" in
1305 self.usage is replaced with the name of the current program
1306 (basename of sys.argv[0]). Does nothing if self.usage is empty
1310 print >>file, self
.get_usage()
1312 def get_version (self
):
1314 return self
.version
.replace("%prog", get_prog_name())
1318 def print_version (self
, file=None):
1319 """print_version(file : file = stdout)
1321 Print the version message for this program (self.version) to
1322 'file' (default stdout). As with print_usage(), any occurence
1323 of "%prog" in self.version is replaced by the current program's
1324 name. Does nothing if self.version is empty or undefined.
1327 print >>file, self
.get_version()
1329 def format_option_help (self
, formatter
=None):
1330 if formatter
is None:
1331 formatter
= self
.formatter
1332 formatter
.store_option_strings(self
)
1334 result
.append(formatter
.format_heading("options"))
1336 if self
.option_list
:
1337 result
.append(OptionContainer
.format_option_help(self
, formatter
))
1339 for group
in self
.option_groups
:
1340 result
.append(group
.format_help(formatter
))
1343 # Drop the last "\n", or the header if no options or option groups:
1344 return "".join(result
[:-1])
1346 def format_help (self
, formatter
=None):
1347 if formatter
is None:
1348 formatter
= self
.formatter
1351 result
.append(self
.get_usage() + "\n")
1352 if self
.description
:
1353 result
.append(self
.format_description(formatter
) + "\n")
1354 result
.append(self
.format_option_help(formatter
))
1355 return "".join(result
)
1357 def print_help (self
, file=None):
1358 """print_help(file : file = stdout)
1360 Print an extended help message, listing all options and any
1361 help text provided with them, to 'file' (default stdout).
1365 file.write(self
.format_help())
1367 # class OptionParser
1370 def _match_abbrev (s
, wordmap
):
1371 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1373 Return the string key in 'wordmap' for which 's' is an unambiguous
1374 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1375 'words', raise BadOptionError.
1377 # Is there an exact match?
1378 if wordmap
.has_key(s
):
1381 # Isolate all words with s as a prefix.
1382 possibilities
= [word
for word
in wordmap
.keys()
1383 if word
.startswith(s
)]
1384 # No exact match, so there had better be just one possibility.
1385 if len(possibilities
) == 1:
1386 return possibilities
[0]
1387 elif not possibilities
:
1388 raise BadOptionError("no such option: %s" % s
)
1390 # More than one possible completion: ambiguous prefix.
1391 raise BadOptionError("ambiguous option: %s (%s?)"
1392 % (s
, ", ".join(possibilities
)))
1395 # Some day, there might be many Option classes. As of Optik 1.3, the
1396 # preferred way to instantiate Options is indirectly, via make_option(),
1397 # which will become a factory function when there are many Option
1399 make_option
= Option