1 # This is *not* the official distribution of Optik. See
2 # http://optik.sourceforge.net/ for the official distro.
4 # This combined module was converted from the "optik" package for Docutils use
5 # by David Goodger (2002-06-12). Optik is slated for inclusion in the Python
6 # standard library as OptionParser.py. Once Optik itself becomes a single
7 # module, Docutils will include the official module and kill off this
12 A powerful, extensible, and easy-to-use command-line parser for Python.
14 By Greg Ward <gward@python.net>
16 See http://optik.sourceforge.net/
19 # Copyright (c) 2001 Gregory P. Ward. All rights reserved.
21 # Redistribution and use in source and binary forms, with or without
22 # modification, are permitted provided that the following conditions are
25 # * Redistributions of source code must retain the above copyright
26 # notice, this list of conditions and the following disclaimer.
28 # * Redistributions in binary form must reproduce the above copyright
29 # notice, this list of conditions and the following disclaimer in the
30 # documentation and/or other materials provided with the distribution.
32 # * Neither the name of the author nor the names of its
33 # contributors may be used to endorse or promote products derived from
34 # this software without specific prior written permission.
36 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
37 # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
38 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
39 # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
40 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
41 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
42 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
43 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
44 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
45 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
46 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
56 from types
import TupleType
, ListType
, DictType
, StringType
57 from distutils
.fancy_getopt
import wrap_text
60 SUPPRESS_HELP
= "SUPPRESS"+"HELP"
61 SUPPRESS_USAGE
= "SUPPRESS"+"USAGE"
62 # Not supplying a default is different from a default of None,
63 # so we need an explicit "not supplied" value.
64 NO_DEFAULT
= "NO"+"DEFAULT"
67 class OptikError (Exception):
68 def __init__ (self
, msg
):
75 class OptionError (OptikError
):
77 Raised if an Option instance is created with invalid or
78 inconsistent arguments.
81 def __init__ (self
, msg
, option
):
83 self
.option_id
= str(option
)
87 return "option %s: %s" % (self
.option_id
, self
.msg
)
91 class OptionConflictError (OptionError
):
93 Raised if conflicting options are added to an OptionParser.
96 class OptionValueError (OptikError
):
98 Raised if an invalid option value is encountered on the command
102 class BadOptionError (OptikError
):
104 Raised if an invalid or ambiguous option is seen on the command-line.
108 _builtin_cvt
= { "int" : (int, "integer"),
109 "long" : (long, "long integer"),
110 "float" : (float, "floating-point"),
111 "complex" : (complex, "complex") }
113 def check_builtin (option
, opt
, value
):
114 (cvt
, what
) = _builtin_cvt
[option
.type]
118 raise OptionValueError(
119 #"%s: invalid %s argument %r" % (opt, what, value))
120 "option %s: invalid %s value: %r" % (opt
, what
, value
))
122 def check_choice(option
, opt
, value
):
123 if value
in option
.choices
:
126 raise OptionValueError(
127 "option %s: invalid choice: %r (choose one of %r)"
128 % (opt
, value
, option
.choices
))
134 _short_opts : [string]
135 _long_opts : [string]
137 option_string : string
138 Set when help output is formatted.
148 callback_args : (any*)
149 callback_kwargs : { string : any }
154 # The list of instance attributes that may be set through
155 # keyword args to the constructor.
169 # The set of actions allowed by option parsers. Explicitly listed
170 # here so the constructor can validate its arguments.
181 # The set of actions that involve storing a value somewhere;
182 # also listed just for constructor argument validation. (If
183 # the action is one of these, there must be a destination.)
184 STORE_ACTIONS
= ("store",
191 # The set of actions for which it makes sense to supply a value
192 # type, ie. where we expect an argument to this option.
193 TYPED_ACTIONS
= ("store",
197 # The set of known types for option parsers. Again, listed here for
198 # constructor argument validation.
199 TYPES
= ("string", "int", "long", "float", "complex", "choice")
201 # Dictionary of argument checking functions, which convert and
202 # validate option arguments according to the option type.
204 # Signature of checking functions is:
205 # check(option : Option, opt : string, value : string) -> any
207 # option is the Option instance calling the checker
208 # opt is the actual option seen on the command-line
209 # (eg. "-a", "--file")
210 # value is the option argument seen on the command-line
212 # The return value should be in the appropriate Python type
213 # for option.type -- eg. an integer if option.type == "int".
215 # If no checker is defined for a type, arguments will be
216 # unchecked and remain strings.
217 TYPE_CHECKER
= { "int" : check_builtin
,
218 "long" : check_builtin
,
219 "float" : check_builtin
,
220 "complex" : check_builtin
,
221 "choice" : check_choice
,
225 # CHECK_METHODS is a list of unbound method objects; they are called
226 # by the constructor, in order, after all attributes are
227 # initialized. The list is created and filled in later, after all
228 # the methods are actually defined. (I just put it here because I
229 # like to define and document all class attributes in the same
230 # place.) Subclasses that add another _check_*() method should
231 # define their own CHECK_METHODS list that adds their check method
232 # to those from this class.
236 # -- Constructor/initialization methods ----------------------------
238 def __init__ (self
, *opts
, **attrs
):
239 # Set _short_opts, _long_opts attrs from 'opts' tuple
240 opts
= self
._check
_opt
_strings
(opts
)
241 self
._set
_opt
_strings
(opts
)
243 # Set all other attrs (action, type, etc.) from 'attrs' dict
244 self
._set
_attrs
(attrs
)
246 # Check all the attributes we just set. There are lots of
247 # complicated interdependencies, but luckily they can be farmed
248 # out to the _check_*() methods listed in CHECK_METHODS -- which
249 # could be handy for subclasses! The one thing these all share
250 # is that they raise OptionError if they discover a problem.
251 for checker
in self
.CHECK_METHODS
:
254 def _check_opt_strings (self
, opts
):
255 # Filter out None because early versions of Optik had exactly
256 # one short option and one long option, either of which
258 opts
= filter(None, opts
)
260 raise OptionError("at least one option string must be supplied",
264 def _set_opt_strings (self
, opts
):
265 self
._short
_opts
= []
270 "invalid option string %r: "
271 "must be at least two characters long" % opt
, self
)
273 if not (opt
[0] == "-" and opt
[1] != "-"):
275 "invalid short option string %r: "
276 "must be of the form -x, (x any non-dash char)" % opt
,
278 self
._short
_opts
.append(opt
)
280 if not (opt
[0:2] == "--" and opt
[2] != "-"):
282 "invalid long option string %r: "
283 "must start with --, followed by non-dash" % opt
,
285 self
._long
_opts
.append(opt
)
287 def _set_attrs (self
, attrs
):
288 for attr
in self
.ATTRS
:
289 if attrs
.has_key(attr
):
290 setattr(self
, attr
, attrs
[attr
])
293 if attr
== 'default':
294 setattr(self
, attr
, NO_DEFAULT
)
296 setattr(self
, attr
, None)
299 "invalid keyword arguments: %s" % ", ".join(attrs
.keys()),
303 # -- Constructor validation methods --------------------------------
305 def _check_action (self
):
306 if self
.action
is None:
307 self
.action
= "store"
308 elif self
.action
not in self
.ACTIONS
:
309 raise OptionError("invalid action: %r" % self
.action
, self
)
311 def _check_type (self
):
312 if self
.type is None:
313 # XXX should factor out another class attr here: list of
314 # actions that *require* a type
315 if self
.action
in ("store", "append"):
316 if self
.choices
is not None:
317 # The "choices" attribute implies "choice" type.
320 # No type given? "string" is the most sensible default.
323 if self
.type not in self
.TYPES
:
324 raise OptionError("invalid option type: %r" % self
.type, self
)
325 if self
.action
not in self
.TYPED_ACTIONS
:
327 "must not supply a type for action %r" % self
.action
, self
)
329 def _check_choice(self
):
330 if self
.type == "choice":
331 if self
.choices
is None:
333 "must supply a list of choices for type 'choice'", self
)
334 elif type(self
.choices
) not in (TupleType
, ListType
):
336 "choices must be a list of strings ('%s' supplied)"
337 % str(type(self
.choices
)).split("'")[1], self
)
338 elif self
.choices
is not None:
340 "must not supply choices for type %r" % self
.type, self
)
342 def _check_dest (self
):
343 if self
.action
in self
.STORE_ACTIONS
and self
.dest
is None:
344 # No destination given, and we need one for this action.
345 # Glean a destination from the first long option string,
346 # or from the first short option string if no long options.
348 # eg. "--foo-bar" -> "foo_bar"
349 self
.dest
= self
._long
_opts
[0][2:].replace('-', '_')
351 self
.dest
= self
._short
_opts
[0][1]
353 def _check_const (self
):
354 if self
.action
!= "store_const" and self
.const
is not None:
356 "'const' must not be supplied for action %r" % self
.action
,
359 def _check_nargs (self
):
360 if self
.action
in self
.TYPED_ACTIONS
:
361 if self
.nargs
is None:
363 elif self
.nargs
is not None:
365 "'nargs' must not be supplied for action %r" % self
.action
,
368 def _check_callback (self
):
369 if self
.action
== "callback":
370 if not callable(self
.callback
):
372 "callback not callable: %r" % self
.callback
, self
)
373 if (self
.callback_args
is not None and
374 type(self
.callback_args
) is not TupleType
):
376 "callback_args, if supplied, must be a tuple: not %r"
377 % self
.callback_args
, self
)
378 if (self
.callback_kwargs
is not None and
379 type(self
.callback_kwargs
) is not DictType
):
381 "callback_kwargs, if supplied, must be a dict: not %r"
382 % self
.callback_kwargs
, self
)
384 if self
.callback
is not None:
386 "callback supplied (%r) for non-callback option"
387 % self
.callback
, self
)
388 if self
.callback_args
is not None:
390 "callback_args supplied for non-callback option", self
)
391 if self
.callback_kwargs
is not None:
393 "callback_kwargs supplied for non-callback option", self
)
396 CHECK_METHODS
= [_check_action
,
405 # -- Miscellaneous methods -----------------------------------------
408 if self
._short
_opts
or self
._long
_opts
:
409 return "/".join(self
._short
_opts
+ self
._long
_opts
)
411 raise RuntimeError, "short_opts and long_opts both empty!"
413 def takes_value (self
):
414 return self
.type is not None
417 # -- Processing methods --------------------------------------------
419 def check_value (self
, opt
, value
):
420 checker
= self
.TYPE_CHECKER
.get(self
.type)
424 return checker(self
, opt
, value
)
426 def process (self
, opt
, value
, values
, parser
):
428 # First, convert the value(s) to the right type. Howl if any
429 # value(s) are bogus.
430 if value
is not None:
432 value
= self
.check_value(opt
, value
)
434 value
= tuple([self
.check_value(opt
, v
) for v
in value
])
436 # And then take whatever action is expected of us.
437 # This is a separate method to make life easier for
438 # subclasses to add new actions.
439 return self
.take_action(
440 self
.action
, self
.dest
, opt
, value
, values
, parser
)
442 def take_action (self
, action
, dest
, opt
, value
, values
, parser
):
443 if action
== "store":
444 setattr(values
, dest
, value
)
445 elif action
== "store_const":
446 setattr(values
, dest
, self
.const
)
447 elif action
== "store_true":
448 setattr(values
, dest
, 1)
449 elif action
== "store_false":
450 setattr(values
, dest
, 0)
451 elif action
== "append":
452 values
.ensure_value(dest
, []).append(value
)
453 elif action
== "count":
454 setattr(values
, dest
, values
.ensure_value(dest
, 0) + 1)
455 elif action
== "callback":
456 args
= self
.callback_args
or ()
457 kwargs
= self
.callback_kwargs
or {}
458 self
.callback(self
, opt
, value
, parser
, *args
, **kwargs
)
459 elif action
== "help":
462 elif action
== "version":
463 parser
.print_version()
466 raise RuntimeError, "unknown action %r" % self
.action
473 # Some day, there might be many Option classes. As of Optik 1.3, the
474 # preferred way to instantiate Options is indirectly, via make_option(),
475 # which will become a factory function when there are many Option
480 STD_HELP_OPTION
= Option("-h", "--help",
482 help="show this help message and exit")
483 STD_VERSION_OPTION
= Option("--version",
485 help="show program's version number and exit")
488 class OptionContainer
:
494 standard_option_list : [Option]
495 List of standard options that will be accepted by all instances
496 of this parser class (intended to be overridden by subclasses).
499 option_list : [Option]
500 The list of Option objects contained by this OptionContainer.
501 _short_opt : { string : Option }
502 Dictionary mapping short option strings, eg. "-f" or "-X",
503 to the Option instances that implement them. If an Option
504 has multiple short option strings, it will appears in this
505 dictionary multiple times. [1]
506 _long_opt : { string : Option }
507 Dictionary mapping long option strings, eg. "--file" or
508 "--exclude", to the Option instances that implement them.
509 Again, a given Option can occur multiple times in this
511 defaults : { string : any }
512 Dictionary mapping option destination names to default
513 values for each destination. [1]
515 [1] These mappings are common to (shared by) all components of the
516 controlling OptionParser, where they are initially created.
520 standard_option_list
= []
522 def __init__(self
, parser
, description
=None, option_list
=None):
523 # List of Options is local to this OptionContainer.
524 self
.option_list
= []
525 # The shared mappings are stored in the parser.
526 self
._short
_opt
= parser
._short
_opt
527 self
._long
_opt
= parser
._long
_opt
528 self
.defaults
= parser
.defaults
530 self
.format
= parser
.format
531 self
.option_class
= parser
.option_class
532 self
.conflict_handler
= parser
.conflict_handler
533 self
.set_description(description
)
534 self
._populate
_option
_list
(option_list
)
536 def set_description(self
, description
):
537 self
.description
= description
539 def _populate_option_list(self
, option_list
, version
=None, help=None):
540 if self
.standard_option_list
:
541 self
.add_options(self
.standard_option_list
)
543 self
.add_options(option_list
)
545 self
.add_option(STD_VERSION_OPTION
)
547 self
.add_option(STD_HELP_OPTION
)
550 # -- Option-adding methods -----------------------------------------
552 def _check_conflict (self
, option
):
554 for opt
in option
._short
_opts
:
555 if self
._short
_opt
.has_key(opt
):
556 conflict_opts
.append((opt
, self
._short
_opt
[opt
]))
557 for opt
in option
._long
_opts
:
558 if self
._long
_opt
.has_key(opt
):
559 conflict_opts
.append((opt
, self
._long
_opt
[opt
]))
562 handler
= self
.conflict_handler
563 if handler
== "ignore": # behaviour for Optik 1.0, 1.1
565 elif handler
== "error": # new in 1.2
566 raise OptionConflictError(
567 "conflicting option string(s): %s"
568 % ", ".join([co
[0] for co
in conflict_opts
]),
570 elif handler
== "resolve": # new in 1.2
571 for (opt
, c_option
) in conflict_opts
:
572 if opt
.startswith("--"):
573 c_option
._long
_opts
.remove(opt
)
574 del self
._long
_opt
[opt
]
576 c_option
._short
_opts
.remove(opt
)
577 del self
._short
_opt
[opt
]
578 if not (c_option
._short
_opts
or c_option
._long
_opts
):
579 c_option
.container
.option_list
.remove(c_option
)
581 def add_option (self
, *args
, **kwargs
):
582 """add_option(Option)
583 add_option(opt_str, ..., kwarg=val, ...)
585 if type(args
[0]) is StringType
:
586 option
= self
.option_class(*args
, **kwargs
)
587 elif len(args
) == 1 and not kwargs
:
589 if not isinstance(option
, Option
):
590 raise TypeError, "not an Option instance: %r" % option
592 raise TypeError, "invalid arguments"
594 self
._check
_conflict
(option
)
596 self
.option_list
.append(option
)
597 option
.container
= self
598 for opt
in option
._short
_opts
:
599 self
._short
_opt
[opt
] = option
600 for opt
in option
._long
_opts
:
601 self
._long
_opt
[opt
] = option
603 if option
.dest
is not None: # option has a dest, we need a default
604 if option
.default
is not NO_DEFAULT
:
605 self
.defaults
[option
.dest
] = option
.default
606 elif not self
.defaults
.has_key(option
.dest
):
607 self
.defaults
[option
.dest
] = None
609 def add_options (self
, option_list
):
610 for option
in option_list
:
611 self
.add_option(option
)
613 # -- Option query/removal methods ----------------------------------
615 def get_option (self
, opt_str
):
616 return (self
._short
_opt
.get(opt_str
) or
617 self
._long
_opt
.get(opt_str
))
619 def has_option (self
, opt_str
):
620 return (self
._short
_opt
.has_key(opt_str
) or
621 self
._long
_opt
.has_key(opt_str
))
623 def remove_option (self
, opt_str
):
624 option
= self
._short
_opt
.get(opt_str
)
626 option
= self
._long
_opt
.get(opt_str
)
628 raise ValueError("no such option %r" % opt_str
)
630 for opt
in option
._short
_opts
:
631 del self
._short
_opt
[opt
]
632 for opt
in option
._long
_opts
:
633 del self
._long
_opt
[opt
]
634 option
.container
.option_list
.remove(option
)
637 # -- Feedback methods ----------------------------------------------
639 def get_option_help(self
):
640 if not self
.option_list
:
642 result
= [] # list of strings to "".join() later
643 for option
in self
.option_list
:
644 if not option
.help is SUPPRESS_HELP
:
645 result
.append(self
.format
.format_option(option
))
646 return "".join(result
)
648 def get_description_help(self
):
650 return self
.format
.format_description(self
.description
)
657 result
= self
.get_description_help() + "\n"
658 return result
+ self
.get_option_help()
661 class OptionGroup(OptionContainer
):
663 def __init__(self
, parser
, title
, description
=None):
664 OptionContainer
.__init
__(self
, parser
, description
)
667 self
.description
= description
669 def set_title(self
, title
):
673 result
= self
.format
.format_heading(self
.title
)
674 self
.format
.increase_nesting()
675 result
+= OptionContainer
.get_help(self
)
676 self
.format
.decrease_nesting()
682 def __init__ (self
, defaults
=None):
684 for (attr
, val
) in defaults
.items():
685 setattr(self
, attr
, val
)
688 return "%s(%r)" % (self
.__class
__, self
.__dict
__)
690 def _update_careful (self
, dict):
692 Update the option values from an arbitrary dictionary, but only
693 use keys from dict that already have a corresponding attribute
694 in self. Any keys in dict without a corresponding attribute
695 are silently ignored.
697 for attr
in dir(self
):
698 if dict.has_key(attr
):
701 setattr(self
, attr
, dval
)
703 def _update_loose (self
, dict):
705 Update the option values from an arbitrary dictionary,
706 using all keys from the dictionary regardless of whether
707 they have a corresponding attribute in self or not.
709 self
.__dict
__.update(dict)
711 def _update (self
, dict, mode
):
712 if mode
== "careful":
713 self
._update
_careful
(dict)
714 elif mode
== "loose":
715 self
._update
_loose
(dict)
717 raise ValueError, "invalid update mode: %r" % mode
719 def read_module (self
, modname
, mode
="careful"):
721 mod
= sys
.modules
[modname
]
722 self
._update
(vars(mod
), mode
)
724 def read_file (self
, filename
, mode
="careful"):
726 execfile(filename
, vars)
727 self
._update
(vars, mode
)
729 def ensure_value (self
, attr
, value
):
730 if not hasattr(self
, attr
) or getattr(self
, attr
) is None:
731 setattr(self
, attr
, value
)
732 return getattr(self
, attr
)
735 class OptionParser(OptionContainer
):
740 a usage string for your program. Before it is displayed
741 to the user, "%prog" will be expanded to the name of
742 your program (os.path.basename(sys.argv[0])).
744 allow_interspersed_args : boolean = true
745 If true, positional arguments may be interspersed with options.
746 Assuming -a and -b each take a single argument, the command-line
747 -ablah foo bar -bboo baz
748 will be interpreted the same as
749 -ablah -bboo -- foo bar baz
750 If this flag were false, that command line would be interpreted as
751 -ablah -- foo bar -bboo baz
752 -- ie. we stop processing options as soon as we see the first
753 non-option argument. (This is the tradition followed by
754 Python's getopt module, Perl's Getopt::Std, and other argument-
755 parsing libraries, but it is generally annoying to users.)
758 the argument list currently being parsed. Only set when
759 parse_args() is active, and continually trimmed down as
760 we consume arguments. Mainly there for the benefit of
763 the list of leftover arguments that we have skipped while
764 parsing options. If allow_interspersed_args is false, this
765 list is always empty.
767 the set of option values currently being accumulated. Only
768 set when parse_args() is active. Also mainly for callbacks.
770 Because of the 'rargs', 'largs', and 'values' attributes,
771 OptionParser is not thread-safe. If, for some perverse reason, you
772 need to parse command-line arguments simultaneously in different
773 threads, use different OptionParser instances.
784 conflict_handler
="error",
786 """Override OptionContainer.__init__."""
787 self
.set_usage(usage
)
788 self
.set_description(description
)
789 self
.option_class
= option_class
790 self
.version
= version
791 self
.set_conflict_handler(conflict_handler
)
792 self
.allow_interspersed_args
= 1
797 # Create the various lists and dicts that constitute the
798 # "option list". See class docstring for details about
800 self
._create
_option
_list
()
802 # Populate the option list; initial sources are the
803 # standard_option_list class attribute, the 'option_list' argument,
804 # and the STD_VERSION_OPTION and STD_HELP_OPTION globals (if 'version'
805 # and/or 'help' supplied).
806 self
._populate
_option
_list
(option_list
, version
=version
, help=help)
808 self
._init
_parsing
_state
()
810 # -- Private methods -----------------------------------------------
811 # (used by the constructor)
813 def _create_option_list (self
):
814 self
.option_list
= []
815 self
.option_groups
= []
816 self
._short
_opt
= {} # single letter -> Option instance
817 self
._long
_opt
= {} # long option -> Option instance
818 self
.defaults
= {} # maps option dest -> default value
820 def _init_parsing_state (self
):
821 # These are set in parse_args() for the convenience of callbacks.
827 # -- Simple modifier methods ---------------------------------------
829 def set_usage (self
, usage
):
831 self
.usage
= "%prog [options]"
832 elif usage
is SUPPRESS_USAGE
:
837 def enable_interspersed_args (self
):
838 self
.allow_interspersed_args
= 1
840 def disable_interspersed_args (self
):
841 self
.allow_interspersed_args
= 0
843 def set_conflict_handler (self
, handler
):
844 if handler
not in ("ignore", "error", "resolve"):
845 raise ValueError, "invalid conflict_resolution value %r" % handler
846 self
.conflict_handler
= handler
848 def set_default (self
, dest
, value
):
849 self
.defaults
[dest
] = value
851 def set_defaults (self
, **kwargs
):
852 self
.defaults
.update(kwargs
)
854 def get_default_values(self
):
855 return Values(self
.defaults
)
858 # -- OptionGroup methods -------------------------------------------
860 def add_option_group(self
, group
):
861 self
.option_groups
.append(group
)
863 def get_option_group(self
, opt_str
):
864 option
= (self
._short
_opt
.get(opt_str
) or
865 self
._long
_opt
.get(opt_str
))
866 if option
and option
.container
is not self
:
867 return option
.container
871 # -- Option-parsing methods ----------------------------------------
873 def _get_args (self
, args
):
877 return args
[:] # don't modify caller's list
879 def parse_args (self
, args
=None, values
=None):
881 parse_args(args : [string] = sys.argv[1:],
882 values : Values = None)
883 -> (values : Values, args : [string])
885 Parse the command-line options found in 'args' (default:
886 sys.argv[1:]). Any errors result in a call to 'error()', which
887 by default prints the usage message to stderr and calls
888 sys.exit() with an error message. On success returns a pair
889 (values, args) where 'values' is an Values instance (with all
890 your option values) and 'args' is the list of arguments left
891 over after parsing options.
893 rargs
= self
._get
_args
(args
)
895 values
= self
.get_default_values()
897 # Store the halves of the argument list as attributes for the
898 # convenience of callbacks:
900 # the rest of the command-line (the "r" stands for
901 # "remaining" or "right-hand")
903 # the leftover arguments -- ie. what's left after removing
904 # options and their arguments (the "l" stands for "leftover"
907 self
.largs
= largs
= []
911 stop
= self
._process
_args
(largs
, rargs
, values
)
912 except (BadOptionError
, OptionValueError
), err
:
916 return self
.check_values(values
, args
)
918 def check_values (self
, values
, args
):
920 check_values(values : Values, args : [string])
921 -> (values : Values, args : [string])
923 Check that the supplied option values and leftover arguments are
924 valid. Returns the option values and leftover arguments
925 (possibly adjusted, possibly completely new -- whatever you
926 like). Default implementation just returns the passed-in
927 values; subclasses may override as desired.
929 return (values
, args
)
931 def _process_args (self
, largs
, rargs
, values
):
932 """_process_args(largs : [string],
936 Process command-line arguments and populate 'values', consuming
937 options and arguments from 'rargs'. If 'allow_interspersed_args' is
938 false, stop at the first non-option argument. If true, accumulate any
939 interspersed non-option arguments in 'largs'.
943 # We handle bare "--" explicitly, and bare "-" is handled by the
944 # standard arg handler since the short arg case ensures that the
945 # len of the opt string is greater than 1.
949 elif arg
[0:2] == "--":
950 # process a single long option (possibly with value(s))
951 self
._process
_long
_opt
(rargs
, values
)
952 elif arg
[:1] == "-" and len(arg
) > 1:
953 # process a cluster of short options (possibly with
954 # value(s) for the last one only)
955 self
._process
_short
_opts
(rargs
, values
)
956 elif self
.allow_interspersed_args
:
960 return # stop now, leave this arg in rargs
962 # Say this is the original argument list:
963 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
965 # (we are about to process arg(i)).
967 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
968 # [arg0, ..., arg(i-1)] (any options and their arguments will have
969 # been removed from largs).
971 # The while loop will usually consume 1 or more arguments per pass.
972 # If it consumes 1 (eg. arg is an option that takes no arguments),
973 # then after _process_arg() is done the situation is:
975 # largs = subset of [arg0, ..., arg(i)]
976 # rargs = [arg(i+1), ..., arg(N-1)]
978 # If allow_interspersed_args is false, largs will always be
979 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
980 # not a very interesting subset!
982 def _match_long_opt (self
, opt
):
983 """_match_long_opt(opt : string) -> string
985 Determine which long option string 'opt' matches, ie. which one
986 it is an unambiguous abbrevation for. Raises BadOptionError if
987 'opt' doesn't unambiguously match any long option string.
989 return _match_abbrev(opt
, self
._long
_opt
)
991 def _process_long_opt (self
, rargs
, values
):
994 # Value explicitly attached to arg? Pretend it's the next
997 (opt
, next_arg
) = arg
.split("=", 1)
998 rargs
.insert(0, next_arg
)
999 had_explicit_value
= 1
1002 had_explicit_value
= 0
1004 opt
= self
._match
_long
_opt
(opt
)
1005 option
= self
._long
_opt
[opt
]
1006 if option
.takes_value():
1007 nargs
= option
.nargs
1008 if len(rargs
) < nargs
:
1010 self
.error("%s option requires a value" % opt
)
1012 self
.error("%s option requires %d values"
1015 value
= rargs
.pop(0)
1017 value
= tuple(rargs
[0:nargs
])
1020 elif had_explicit_value
:
1021 self
.error("%s option does not take a value" % opt
)
1026 option
.process(opt
, value
, values
, self
)
1028 def _process_short_opts (self
, rargs
, values
):
1034 option
= self
._short
_opt
.get(opt
)
1035 i
+= 1 # we have consumed a character
1038 self
.error("no such option: %s" % opt
)
1039 if option
.takes_value():
1040 # Any characters left in arg? Pretend they're the
1041 # next arg, and stop consuming characters of arg.
1043 rargs
.insert(0, arg
[i
:])
1046 nargs
= option
.nargs
1047 if len(rargs
) < nargs
:
1049 self
.error("%s option requires a value" % opt
)
1051 self
.error("%s option requires %s values"
1054 value
= rargs
.pop(0)
1056 value
= tuple(rargs
[0:nargs
])
1059 else: # option doesn't take a value
1062 option
.process(opt
, value
, values
, self
)
1068 # -- Feedback methods ----------------------------------------------
1070 def error (self
, msg
):
1071 """error(msg : string)
1073 Print a usage message incorporating 'msg' to stderr and exit.
1074 If you override this in a subclass, it should not return -- it
1075 should either exit or raise an exception.
1077 self
.print_usage(sys
.stderr
)
1078 sys
.exit("%s: error: %s" % (get_prog_name(), msg
))
1080 def get_usage_help(self
):
1082 return self
.format
.format_usage(
1083 self
.usage
.replace("%prog", get_prog_name()))
1087 def print_usage (self
, file=None):
1088 """print_usage(file : file = stdout)
1090 Print the usage message for the current program (self.usage) to
1091 'file' (default stdout). Any occurence of the string "%prog" in
1092 self.usage is replaced with the name of the current program
1093 (basename of sys.argv[0]). Does nothing if self.usage is empty
1097 print >>file, self
.get_usage_help()
1099 def get_version_help(self
):
1101 return self
.version
.replace("%prog", get_prog_name())
1105 def print_version (self
, file=None):
1106 """print_version(file : file = stdout)
1108 Print the version message for this program (self.version) to
1109 'file' (default stdout). As with print_usage(), any occurence
1110 of "%prog" in self.version is replaced by the current program's
1111 name. Does nothing if self.version is empty or undefined.
1114 print >>file, self
.get_version_help()
1116 def get_option_help(self
):
1117 self
.format
.store_option_strings(self
)
1119 result
.append(self
.format
.format_heading("Options"))
1120 self
.format
.increase_nesting()
1121 if self
.option_list
:
1122 result
.append(OptionContainer
.get_option_help(self
))
1124 for group
in self
.option_groups
:
1125 result
.append(group
.get_help())
1127 self
.format
.decrease_nesting()
1128 # Drop the last "\n", or the header if no options or option groups:
1129 return "".join(result
[:-1])
1134 result
.append(self
.get_usage_help() + "\n")
1135 if self
.description
:
1136 result
.append(self
.get_description_help() + "\n")
1137 result
.append(self
.get_option_help())
1138 return "".join(result
)
1140 def print_help (self
, file=None):
1141 """print_help(file : file = stdout)
1143 Print an extended help message, listing all options and any
1144 help text provided with them, to 'file' (default stdout).
1148 file.write(self
.get_help())
1150 # class OptionParser
1156 "--help" output format; abstract base class (Strategy design pattern).
1158 Instance attributes:
1159 indent_increment : int
1160 The number of columns to indent per nesting level.
1161 max_help_position : int
1162 The maximum starting column for option help text.
1164 The calculated starting column for option help text;
1165 initially the same as the maximum.
1167 The overall width (in columns) for output.
1168 current_indent : int
1169 In columns, calculated.
1171 Increased for each additional nesting level.
1173 Number of columns available for option help text, calculated.
1176 def __init__(self
, indent_increment
, max_help_position
, width
,
1178 self
.indent_increment
= indent_increment
1179 self
.help_position
= self
.max_help_position
= max_help_position
1181 self
.current_indent
= 0
1183 self
.help_width
= width
- max_help_position
1185 self
.format_option_strings
= self
.format_option_strings_short_first
1187 self
.format_option_strings
= self
.format_option_strings_long_first
1189 def increase_nesting(self
):
1190 self
.current_indent
+= self
.indent_increment
1193 def decrease_nesting(self
):
1194 self
.current_indent
-= self
.indent_increment
1195 assert self
.current_indent
>= 0, "Indent decreased below 0."
1198 def format_usage(self
, usage
):
1199 raise NotImplementedError
1201 def format_heading(self
, heading
):
1202 raise NotImplementedError
1204 def format_description(self
, description
):
1205 desc_width
= self
.width
- self
.current_indent
1206 desc_lines
= wrap_text(description
, desc_width
)
1207 result
= ["%*s%s\n" % (self
.current_indent
, "", line
)
1208 for line
in desc_lines
]
1209 return "".join(result
)
1211 def format_option(self
, option
):
1212 # The help for each option consists of two parts:
1213 # * the opt strings and metavars
1214 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
1215 # * the user-supplied help string
1216 # eg. ("turn on expert mode", "read data from FILENAME")
1218 # If possible, we write both of these on the same line:
1219 # -x turn on expert mode
1221 # But if the opt string list is too long, we put the help
1222 # string on a second line, indented to the same column it would
1223 # start in if it fit on the first line.
1224 # -fFILENAME, --file=FILENAME
1225 # read data from FILENAME
1227 opts
= option
.option_strings
1228 opt_width
= self
.help_position
- self
.current_indent
- 2
1229 if len(opts
) > opt_width
:
1230 opts
= "%*s%s\n" % (self
.current_indent
, "", opts
)
1231 indent_first
= self
.help_position
1232 else: # start help on same line as opts
1233 opts
= "%*s%-*s " % (self
.current_indent
, "", opt_width
, opts
)
1237 help_lines
= wrap_text(option
.help, self
.help_width
)
1238 result
.append("%*s%s\n" % (indent_first
, "", help_lines
[0]))
1239 result
.extend(["%*s%s\n" % (self
.help_position
, "", line
)
1240 for line
in help_lines
[1:]])
1241 elif opts
[-1] != "\n":
1243 return "".join(result
)
1245 def store_option_strings(self
, parser
):
1246 self
.increase_nesting()
1248 for opt
in parser
.option_list
:
1249 strings
= self
.format_option_strings(opt
)
1250 opt
.option_strings
= strings
1251 max_len
= max(max_len
, len(strings
) + self
.current_indent
)
1252 self
.increase_nesting()
1253 for group
in parser
.option_groups
:
1254 for opt
in group
.option_list
:
1255 strings
= self
.format_option_strings(opt
)
1256 opt
.option_strings
= strings
1257 max_len
= max(max_len
, len(strings
) + self
.current_indent
)
1258 self
.decrease_nesting()
1259 self
.decrease_nesting()
1260 self
.help_position
= min(max_len
+ 2, self
.max_help_position
)
1262 def format_option_strings(self
, option
):
1263 """Return a comma-separated list of option strigs & metavariables."""
1264 raise NotImplementedError(
1265 "Virtual method; use format_option_strings_short_first or "
1266 "format_option_strings_long_first instead.")
1268 def format_option_strings_short_first(self
, option
):
1269 opts
= [] # list of "-a" or "--foo=FILE" strings
1270 takes_value
= option
.takes_value()
1272 metavar
= option
.metavar
or option
.dest
.upper()
1273 for sopt
in option
._short
_opts
:
1274 opts
.append(sopt
+ metavar
)
1275 for lopt
in option
._long
_opts
:
1276 opts
.append(lopt
+ "=" + metavar
)
1278 for opt
in option
._short
_opts
+ option
._long
_opts
:
1280 return ", ".join(opts
)
1282 def format_option_strings_long_first(self
, option
):
1283 opts
= [] # list of "-a" or "--foo=FILE" strings
1284 takes_value
= option
.takes_value()
1286 metavar
= option
.metavar
or option
.dest
.upper()
1287 for lopt
in option
._long
_opts
:
1288 opts
.append(lopt
+ "=" + metavar
)
1289 for sopt
in option
._short
_opts
:
1290 opts
.append(sopt
+ metavar
)
1292 for opt
in option
._long
_opts
+ option
._short
_opts
:
1294 return ", ".join(opts
)
1297 class Indented(HelpFormat
):
1299 """Formats help with indented section bodies."""
1301 def __init__(self
, indent_increment
=2, max_help_position
=24, width
=78,
1303 HelpFormat
.__init
__(self
, indent_increment
, max_help_position
, width
,
1306 def format_usage(self
, usage
):
1307 return "Usage: %s\n" % usage
1309 def format_heading(self
, heading
):
1310 return "%*s%s:\n" % (self
.current_indent
, "", heading
)
1313 class Titled(HelpFormat
):
1315 """Formats help with underlined section headers."""
1317 def __init__(self
, indent_increment
=0, max_help_position
=24, width
=78,
1319 HelpFormat
.__init
__(self
, indent_increment
, max_help_position
, width
,
1322 def format_usage(self
, usage
):
1323 return "%s %s\n" % (self
.format_heading("Usage"), usage
)
1325 def format_heading(self
, heading
):
1326 return "%s\n%s\n" % (heading
, "=-"[self
.level
] * len(heading
))
1329 def _match_abbrev (s
, wordmap
):
1330 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1332 Return the string key in 'wordmap' for which 's' is an unambiguous
1333 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1334 'words', raise BadOptionError.
1336 # Is there an exact match?
1337 if wordmap
.has_key(s
):
1340 # Isolate all words with s as a prefix.
1341 possibilities
= [word
for word
in wordmap
.keys()
1342 if word
.startswith(s
)]
1343 # No exact match, so there had better be just one possibility.
1344 if len(possibilities
) == 1:
1345 return possibilities
[0]
1346 elif not possibilities
:
1347 raise BadOptionError("no such option: %s" % s
)
1349 # More than one possible completion: ambiguous prefix.
1350 raise BadOptionError("ambiguous option: %s (%s?)"
1351 % (s
, ", ".join(possibilities
)))
1353 def get_prog_name ():
1354 return os
.path
.basename(sys
.argv
[0])