blob: e77e4212683e84e236613d34404de794a1e39033 [file] [log] [blame]
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001"""optparse - a powerful, extensible, and easy-to-use option parser.
2
3By Greg Ward <gward@python.net>
4
5Originally distributed as Optik.
6
7See http://optik.sourceforge.net/
8"""
9
10__copyright__ = """
11Copyright (c) 2001-2002 Gregory P. Ward. All rights reserved.
12
13Redistribution and use in source and binary forms, with or without
14modification, are permitted provided that the following conditions are
15met:
16
17 * Redistributions of source code must retain the above copyright
18 notice, this list of conditions and the following disclaimer.
19
20 * Redistributions in binary form must reproduce the above copyright
21 notice, this list of conditions and the following disclaimer in the
22 documentation and/or other materials provided with the distribution.
23
24 * Neither the name of the author nor the names of its
25 contributors may be used to endorse or promote products derived from
26 this software without specific prior written permission.
27
28THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
29IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
30TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
31PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
32CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
33EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
34PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
35PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
36LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
37NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
38SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39"""
40
41import sys, os
42import types
43import textwrap
44
45__version__ = "1.4"
46
47class OptParseError (Exception):
48 def __init__ (self, msg):
49 self.msg = msg
50
51 def __str__ (self):
52 return self.msg
53
54class OptionError (OptParseError):
55 """
56 Raised if an Option instance is created with invalid or
57 inconsistent arguments.
58 """
59
60 def __init__ (self, msg, option):
61 self.msg = msg
62 self.option_id = str(option)
63
64 def __str__ (self):
65 if self.option_id:
66 return "option %s: %s" % (self.option_id, self.msg)
67 else:
68 return self.msg
69
70class OptionConflictError (OptionError):
71 """
72 Raised if conflicting options are added to an OptionParser.
73 """
74
75class OptionValueError (OptParseError):
76 """
77 Raised if an invalid option value is encountered on the command
78 line.
79 """
80
81class BadOptionError (OptParseError):
82 """
83 Raised if an invalid or ambiguous option is seen on the command-line.
84 """
85class HelpFormatter:
86
87 """
88 Abstract base class for formatting option help. OptionParser
89 instances should use one of the HelpFormatter subclasses for
90 formatting help; by default IndentedHelpFormatter is used.
91
92 Instance attributes:
93 indent_increment : int
94 the number of columns to indent per nesting level
95 max_help_position : int
96 the maximum starting column for option help text
97 help_position : int
98 the calculated starting column for option help text;
99 initially the same as the maximum
100 width : int
101 total number of columns for output
102 level : int
103 current indentation level
104 current_indent : int
105 current indentation level (in columns)
106 help_width : int
107 number of columns available for option help text (calculated)
108 """
109
110 def __init__ (self,
111 indent_increment,
112 max_help_position,
113 width,
114 short_first):
115 self.indent_increment = indent_increment
116 self.help_position = self.max_help_position = max_help_position
117 self.width = width
118 self.current_indent = 0
119 self.level = 0
120 self.help_width = width - max_help_position
121 if short_first:
122 self.format_option_strings = self.format_option_strings_short_first
123 else:
124 self.format_option_strings = self.format_option_strings_long_first
125
126 def indent (self):
127 self.current_indent += self.indent_increment
128 self.level += 1
129
130 def dedent (self):
131 self.current_indent -= self.indent_increment
132 assert self.current_indent >= 0, "Indent decreased below 0."
133 self.level -= 1
134
135 def format_usage (self, usage):
136 raise NotImplementedError, "subclasses must implement"
137
138 def format_heading (self, heading):
139 raise NotImplementedError, "subclasses must implement"
140
141 def format_description (self, description):
142 desc_width = self.width - self.current_indent
143 indent = " "*self.current_indent
144 return textwrap.fill(description, desc_width,
145 initial_indent=indent,
146 subsequent_indent=indent)
147
148 def format_option (self, option):
149 # The help for each option consists of two parts:
150 # * the opt strings and metavars
151 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
152 # * the user-supplied help string
153 # eg. ("turn on expert mode", "read data from FILENAME")
154 #
155 # If possible, we write both of these on the same line:
156 # -x turn on expert mode
157 #
158 # But if the opt string list is too long, we put the help
159 # string on a second line, indented to the same column it would
160 # start in if it fit on the first line.
161 # -fFILENAME, --file=FILENAME
162 # read data from FILENAME
163 result = []
164 opts = option.option_strings
165 opt_width = self.help_position - self.current_indent - 2
166 if len(opts) > opt_width:
167 opts = "%*s%s\n" % (self.current_indent, "", opts)
168 indent_first = self.help_position
169 else: # start help on same line as opts
170 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
171 indent_first = 0
172 result.append(opts)
173 if option.help:
174 help_lines = textwrap.wrap(option.help, self.help_width)
175 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
176 result.extend(["%*s%s\n" % (self.help_position, "", line)
177 for line in help_lines[1:]])
178 elif opts[-1] != "\n":
179 result.append("\n")
180 return "".join(result)
181
182 def store_option_strings (self, parser):
183 self.indent()
184 max_len = 0
185 for opt in parser.option_list:
186 strings = self.format_option_strings(opt)
187 opt.option_strings = strings
188 max_len = max(max_len, len(strings) + self.current_indent)
189 self.indent()
190 for group in parser.option_groups:
191 for opt in group.option_list:
192 strings = self.format_option_strings(opt)
193 opt.option_strings = strings
194 max_len = max(max_len, len(strings) + self.current_indent)
195 self.dedent()
196 self.dedent()
197 self.help_position = min(max_len + 2, self.max_help_position)
198
199 def format_option_strings (self, option):
200 """Return a comma-separated list of option strings & metavariables."""
201 raise NotImplementedError(
202 "abstract method: use format_option_strings_short_first or "
203 "format_option_strings_long_first instead.")
204
205 def format_option_strings_short_first (self, option):
206 opts = [] # list of "-a" or "--foo=FILE" strings
207 takes_value = option.takes_value()
208 if takes_value:
209 metavar = option.metavar or option.dest.upper()
210 for sopt in option._short_opts:
211 opts.append(sopt + metavar)
212 for lopt in option._long_opts:
213 opts.append(lopt + "=" + metavar)
214 else:
215 for opt in option._short_opts + option._long_opts:
216 opts.append(opt)
217 return ", ".join(opts)
218
219 def format_option_strings_long_first (self, option):
220 opts = [] # list of "-a" or "--foo=FILE" strings
221 takes_value = option.takes_value()
222 if takes_value:
223 metavar = option.metavar or option.dest.upper()
224 for lopt in option._long_opts:
225 opts.append(lopt + "=" + metavar)
226 for sopt in option._short_opts:
227 opts.append(sopt + metavar)
228 else:
229 for opt in option._long_opts + option._short_opts:
230 opts.append(opt)
231 return ", ".join(opts)
232
233
234class IndentedHelpFormatter (HelpFormatter):
235 """Format help with indented section bodies.
236 """
237
238 def __init__ (self,
239 indent_increment=2,
240 max_help_position=24,
241 width=80,
242 short_first=1):
243 HelpFormatter.__init__(
244 self, indent_increment, max_help_position, width, short_first)
245
246 def format_usage (self, usage):
247 return "usage: %s\n" % usage
248
249 def format_heading (self, heading):
250 return "%*s%s:\n" % (self.current_indent, "", heading)
251
252
253class TitledHelpFormatter (HelpFormatter):
254 """Format help with underlined section headers.
255 """
256
257 def __init__ (self,
258 indent_increment=0,
259 max_help_position=24,
260 width=80,
261 short_first=0):
262 HelpFormatter.__init__ (
263 self, indent_increment, max_help_position, width, short_first)
264
265 def format_usage (self, usage):
266 return "%s %s\n" % (self.format_heading("Usage"), usage)
267
268 def format_heading (self, heading):
269 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
270_builtin_cvt = { "int" : (int, "integer"),
271 "long" : (long, "long integer"),
272 "float" : (float, "floating-point"),
273 "complex" : (complex, "complex") }
274
275def check_builtin (option, opt, value):
276 (cvt, what) = _builtin_cvt[option.type]
277 try:
278 return cvt(value)
279 except ValueError:
280 raise OptionValueError(
281 #"%s: invalid %s argument %r" % (opt, what, value))
282 "option %s: invalid %s value: %r" % (opt, what, value))
283
284def check_choice(option, opt, value):
285 if value in option.choices:
286 return value
287 else:
288 choices = ", ".join(map(repr, option.choices))
289 raise OptionValueError(
290 "option %s: invalid choice: %r (choose from %s)"
291 % (opt, value, choices))
292
293# Not supplying a default is different from a default of None,
294# so we need an explicit "not supplied" value.
295NO_DEFAULT = "NO"+"DEFAULT"
296
297
298class Option:
299 """
300 Instance attributes:
301 _short_opts : [string]
302 _long_opts : [string]
303
304 action : string
305 type : string
306 dest : string
307 default : any
308 nargs : int
309 const : any
310 choices : [string]
311 callback : function
312 callback_args : (any*)
313 callback_kwargs : { string : any }
314 help : string
315 metavar : string
316 """
317
318 # The list of instance attributes that may be set through
319 # keyword args to the constructor.
320 ATTRS = ['action',
321 'type',
322 'dest',
323 'default',
324 'nargs',
325 'const',
326 'choices',
327 'callback',
328 'callback_args',
329 'callback_kwargs',
330 'help',
331 'metavar']
332
333 # The set of actions allowed by option parsers. Explicitly listed
334 # here so the constructor can validate its arguments.
335 ACTIONS = ("store",
336 "store_const",
337 "store_true",
338 "store_false",
339 "append",
340 "count",
341 "callback",
342 "help",
343 "version")
344
345 # The set of actions that involve storing a value somewhere;
346 # also listed just for constructor argument validation. (If
347 # the action is one of these, there must be a destination.)
348 STORE_ACTIONS = ("store",
349 "store_const",
350 "store_true",
351 "store_false",
352 "append",
353 "count")
354
355 # The set of actions for which it makes sense to supply a value
356 # type, ie. where we expect an argument to this option.
357 TYPED_ACTIONS = ("store",
358 "append",
359 "callback")
360
361 # The set of known types for option parsers. Again, listed here for
362 # constructor argument validation.
363 TYPES = ("string", "int", "long", "float", "complex", "choice")
364
365 # Dictionary of argument checking functions, which convert and
366 # validate option arguments according to the option type.
367 #
368 # Signature of checking functions is:
369 # check(option : Option, opt : string, value : string) -> any
370 # where
371 # option is the Option instance calling the checker
372 # opt is the actual option seen on the command-line
373 # (eg. "-a", "--file")
374 # value is the option argument seen on the command-line
375 #
376 # The return value should be in the appropriate Python type
377 # for option.type -- eg. an integer if option.type == "int".
378 #
379 # If no checker is defined for a type, arguments will be
380 # unchecked and remain strings.
381 TYPE_CHECKER = { "int" : check_builtin,
382 "long" : check_builtin,
383 "float" : check_builtin,
384 "complex" : check_builtin,
385 "choice" : check_choice,
386 }
387
388
389 # CHECK_METHODS is a list of unbound method objects; they are called
390 # by the constructor, in order, after all attributes are
391 # initialized. The list is created and filled in later, after all
392 # the methods are actually defined. (I just put it here because I
393 # like to define and document all class attributes in the same
394 # place.) Subclasses that add another _check_*() method should
395 # define their own CHECK_METHODS list that adds their check method
396 # to those from this class.
397 CHECK_METHODS = None
398
399
400 # -- Constructor/initialization methods ----------------------------
401
402 def __init__ (self, *opts, **attrs):
403 # Set _short_opts, _long_opts attrs from 'opts' tuple
404 opts = self._check_opt_strings(opts)
405 self._set_opt_strings(opts)
406
407 # Set all other attrs (action, type, etc.) from 'attrs' dict
408 self._set_attrs(attrs)
409
410 # Check all the attributes we just set. There are lots of
411 # complicated interdependencies, but luckily they can be farmed
412 # out to the _check_*() methods listed in CHECK_METHODS -- which
413 # could be handy for subclasses! The one thing these all share
414 # is that they raise OptionError if they discover a problem.
415 for checker in self.CHECK_METHODS:
416 checker(self)
417
418 def _check_opt_strings (self, opts):
419 # Filter out None because early versions of Optik had exactly
420 # one short option and one long option, either of which
421 # could be None.
422 opts = filter(None, opts)
423 if not opts:
424 raise OptionError("at least one option string must be supplied",
425 self)
426 return opts
427
428 def _set_opt_strings (self, opts):
429 self._short_opts = []
430 self._long_opts = []
431 for opt in opts:
432 if len(opt) < 2:
433 raise OptionError(
434 "invalid option string %r: "
435 "must be at least two characters long" % opt, self)
436 elif len(opt) == 2:
437 if not (opt[0] == "-" and opt[1] != "-"):
438 raise OptionError(
439 "invalid short option string %r: "
440 "must be of the form -x, (x any non-dash char)" % opt,
441 self)
442 self._short_opts.append(opt)
443 else:
444 if not (opt[0:2] == "--" and opt[2] != "-"):
445 raise OptionError(
446 "invalid long option string %r: "
447 "must start with --, followed by non-dash" % opt,
448 self)
449 self._long_opts.append(opt)
450
451 def _set_attrs (self, attrs):
452 for attr in self.ATTRS:
453 if attrs.has_key(attr):
454 setattr(self, attr, attrs[attr])
455 del attrs[attr]
456 else:
457 if attr == 'default':
458 setattr(self, attr, NO_DEFAULT)
459 else:
460 setattr(self, attr, None)
461 if attrs:
462 raise OptionError(
463 "invalid keyword arguments: %s" % ", ".join(attrs.keys()),
464 self)
465
466
467 # -- Constructor validation methods --------------------------------
468
469 def _check_action (self):
470 if self.action is None:
471 self.action = "store"
472 elif self.action not in self.ACTIONS:
473 raise OptionError("invalid action: %r" % self.action, self)
474
475 def _check_type (self):
476 if self.type is None:
477 # XXX should factor out another class attr here: list of
478 # actions that *require* a type
479 if self.action in ("store", "append"):
480 if self.choices is not None:
481 # The "choices" attribute implies "choice" type.
482 self.type = "choice"
483 else:
484 # No type given? "string" is the most sensible default.
485 self.type = "string"
486 else:
487 if self.type not in self.TYPES:
488 raise OptionError("invalid option type: %r" % self.type, self)
489 if self.action not in self.TYPED_ACTIONS:
490 raise OptionError(
491 "must not supply a type for action %r" % self.action, self)
492
493 def _check_choice(self):
494 if self.type == "choice":
495 if self.choices is None:
496 raise OptionError(
497 "must supply a list of choices for type 'choice'", self)
498 elif type(self.choices) not in (types.TupleType, types.ListType):
499 raise OptionError(
500 "choices must be a list of strings ('%s' supplied)"
501 % str(type(self.choices)).split("'")[1], self)
502 elif self.choices is not None:
503 raise OptionError(
504 "must not supply choices for type %r" % self.type, self)
505
506 def _check_dest (self):
507 if self.action in self.STORE_ACTIONS and self.dest is None:
508 # No destination given, and we need one for this action.
509 # Glean a destination from the first long option string,
510 # or from the first short option string if no long options.
511 if self._long_opts:
512 # eg. "--foo-bar" -> "foo_bar"
513 self.dest = self._long_opts[0][2:].replace('-', '_')
514 else:
515 self.dest = self._short_opts[0][1]
516
517 def _check_const (self):
518 if self.action != "store_const" and self.const is not None:
519 raise OptionError(
520 "'const' must not be supplied for action %r" % self.action,
521 self)
522
523 def _check_nargs (self):
524 if self.action in self.TYPED_ACTIONS:
525 if self.nargs is None:
526 self.nargs = 1
527 elif self.nargs is not None:
528 raise OptionError(
529 "'nargs' must not be supplied for action %r" % self.action,
530 self)
531
532 def _check_callback (self):
533 if self.action == "callback":
534 if not callable(self.callback):
535 raise OptionError(
536 "callback not callable: %r" % self.callback, self)
537 if (self.callback_args is not None and
538 type(self.callback_args) is not types.TupleType):
539 raise OptionError(
540 "callback_args, if supplied, must be a tuple: not %r"
541 % self.callback_args, self)
542 if (self.callback_kwargs is not None and
543 type(self.callback_kwargs) is not types.DictType):
544 raise OptionError(
545 "callback_kwargs, if supplied, must be a dict: not %r"
546 % self.callback_kwargs, self)
547 else:
548 if self.callback is not None:
549 raise OptionError(
550 "callback supplied (%r) for non-callback option"
551 % self.callback, self)
552 if self.callback_args is not None:
553 raise OptionError(
554 "callback_args supplied for non-callback option", self)
555 if self.callback_kwargs is not None:
556 raise OptionError(
557 "callback_kwargs supplied for non-callback option", self)
558
559
560 CHECK_METHODS = [_check_action,
561 _check_type,
562 _check_choice,
563 _check_dest,
564 _check_const,
565 _check_nargs,
566 _check_callback]
567
568
569 # -- Miscellaneous methods -----------------------------------------
570
571 def __str__ (self):
572 if self._short_opts or self._long_opts:
573 return "/".join(self._short_opts + self._long_opts)
574 else:
575 raise RuntimeError, "short_opts and long_opts both empty!"
576
577 def takes_value (self):
578 return self.type is not None
579
580
581 # -- Processing methods --------------------------------------------
582
583 def check_value (self, opt, value):
584 checker = self.TYPE_CHECKER.get(self.type)
585 if checker is None:
586 return value
587 else:
588 return checker(self, opt, value)
589
590 def process (self, opt, value, values, parser):
591
592 # First, convert the value(s) to the right type. Howl if any
593 # value(s) are bogus.
594 if value is not None:
595 if self.nargs == 1:
596 value = self.check_value(opt, value)
597 else:
598 value = tuple([self.check_value(opt, v) for v in value])
599
600 # And then take whatever action is expected of us.
601 # This is a separate method to make life easier for
602 # subclasses to add new actions.
603 return self.take_action(
604 self.action, self.dest, opt, value, values, parser)
605
606 def take_action (self, action, dest, opt, value, values, parser):
607 if action == "store":
608 setattr(values, dest, value)
609 elif action == "store_const":
610 setattr(values, dest, self.const)
611 elif action == "store_true":
612 setattr(values, dest, 1)
613 elif action == "store_false":
614 setattr(values, dest, 0)
615 elif action == "append":
616 values.ensure_value(dest, []).append(value)
617 elif action == "count":
618 setattr(values, dest, values.ensure_value(dest, 0) + 1)
619 elif action == "callback":
620 args = self.callback_args or ()
621 kwargs = self.callback_kwargs or {}
622 self.callback(self, opt, value, parser, *args, **kwargs)
623 elif action == "help":
624 parser.print_help()
625 sys.exit(0)
626 elif action == "version":
627 parser.print_version()
628 sys.exit(0)
629 else:
630 raise RuntimeError, "unknown action %r" % self.action
631
632 return 1
633
634# class Option
635def get_prog_name ():
636 return os.path.basename(sys.argv[0])
637
638
639SUPPRESS_HELP = "SUPPRESS"+"HELP"
640SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
641
642STD_HELP_OPTION = Option("-h", "--help",
643 action="help",
644 help="show this help message and exit")
645STD_VERSION_OPTION = Option("--version",
646 action="version",
647 help="show program's version number and exit")
648
649
650class Values:
651
652 def __init__ (self, defaults=None):
653 if defaults:
654 for (attr, val) in defaults.items():
655 setattr(self, attr, val)
656
657 def __repr__ (self):
658 return ("<%s at 0x%x: %r>"
659 % (self.__class__.__name__, id(self), self.__dict__))
660
661 def _update_careful (self, dict):
662 """
663 Update the option values from an arbitrary dictionary, but only
664 use keys from dict that already have a corresponding attribute
665 in self. Any keys in dict without a corresponding attribute
666 are silently ignored.
667 """
668 for attr in dir(self):
669 if dict.has_key(attr):
670 dval = dict[attr]
671 if dval is not None:
672 setattr(self, attr, dval)
673
674 def _update_loose (self, dict):
675 """
676 Update the option values from an arbitrary dictionary,
677 using all keys from the dictionary regardless of whether
678 they have a corresponding attribute in self or not.
679 """
680 self.__dict__.update(dict)
681
682 def _update (self, dict, mode):
683 if mode == "careful":
684 self._update_careful(dict)
685 elif mode == "loose":
686 self._update_loose(dict)
687 else:
688 raise ValueError, "invalid update mode: %r" % mode
689
690 def read_module (self, modname, mode="careful"):
691 __import__(modname)
692 mod = sys.modules[modname]
693 self._update(vars(mod), mode)
694
695 def read_file (self, filename, mode="careful"):
696 vars = {}
697 execfile(filename, vars)
698 self._update(vars, mode)
699
700 def ensure_value (self, attr, value):
701 if not hasattr(self, attr) or getattr(self, attr) is None:
702 setattr(self, attr, value)
703 return getattr(self, attr)
704
705
706class OptionContainer:
707
708 """
709 Abstract base class.
710
711 Class attributes:
712 standard_option_list : [Option]
713 list of standard options that will be accepted by all instances
714 of this parser class (intended to be overridden by subclasses).
715
716 Instance attributes:
717 option_list : [Option]
718 the list of Option objects contained by this OptionContainer
719 _short_opt : { string : Option }
720 dictionary mapping short option strings, eg. "-f" or "-X",
721 to the Option instances that implement them. If an Option
722 has multiple short option strings, it will appears in this
723 dictionary multiple times. [1]
724 _long_opt : { string : Option }
725 dictionary mapping long option strings, eg. "--file" or
726 "--exclude", to the Option instances that implement them.
727 Again, a given Option can occur multiple times in this
728 dictionary. [1]
729 defaults : { string : any }
730 dictionary mapping option destination names to default
731 values for each destination [1]
732
733 [1] These mappings are common to (shared by) all components of the
734 controlling OptionParser, where they are initially created.
735
736 """
737
738 def __init__ (self, option_class, conflict_handler, description):
739 # Initialize the option list and related data structures.
740 # This method must be provided by subclasses, and it must
741 # initialize at least the following instance attributes:
742 # option_list, _short_opt, _long_opt, defaults.
743 self._create_option_list()
744
745 self.option_class = option_class
746 self.set_conflict_handler(conflict_handler)
747 self.set_description(description)
748
749 def _create_option_mappings (self):
750 # For use by OptionParser constructor -- create the master
751 # option mappings used by this OptionParser and all
752 # OptionGroups that it owns.
753 self._short_opt = {} # single letter -> Option instance
754 self._long_opt = {} # long option -> Option instance
755 self.defaults = {} # maps option dest -> default value
756
757
758 def _share_option_mappings (self, parser):
759 # For use by OptionGroup constructor -- use shared option
760 # mappings from the OptionParser that owns this OptionGroup.
761 self._short_opt = parser._short_opt
762 self._long_opt = parser._long_opt
763 self.defaults = parser.defaults
764
765 def set_conflict_handler (self, handler):
766 if handler not in ("ignore", "error", "resolve"):
767 raise ValueError, "invalid conflict_resolution value %r" % handler
768 self.conflict_handler = handler
769
770 def set_description (self, description):
771 self.description = description
772
773
774 # -- Option-adding methods -----------------------------------------
775
776 def _check_conflict (self, option):
777 conflict_opts = []
778 for opt in option._short_opts:
779 if self._short_opt.has_key(opt):
780 conflict_opts.append((opt, self._short_opt[opt]))
781 for opt in option._long_opts:
782 if self._long_opt.has_key(opt):
783 conflict_opts.append((opt, self._long_opt[opt]))
784
785 if conflict_opts:
786 handler = self.conflict_handler
787 if handler == "ignore": # behaviour for Optik 1.0, 1.1
788 pass
789 elif handler == "error": # new in 1.2
790 raise OptionConflictError(
791 "conflicting option string(s): %s"
792 % ", ".join([co[0] for co in conflict_opts]),
793 option)
794 elif handler == "resolve": # new in 1.2
795 for (opt, c_option) in conflict_opts:
796 if opt.startswith("--"):
797 c_option._long_opts.remove(opt)
798 del self._long_opt[opt]
799 else:
800 c_option._short_opts.remove(opt)
801 del self._short_opt[opt]
802 if not (c_option._short_opts or c_option._long_opts):
803 c_option.container.option_list.remove(c_option)
804
805 def add_option (self, *args, **kwargs):
806 """add_option(Option)
807 add_option(opt_str, ..., kwarg=val, ...)
808 """
809 if type(args[0]) is types.StringType:
810 option = self.option_class(*args, **kwargs)
811 elif len(args) == 1 and not kwargs:
812 option = args[0]
813 if not isinstance(option, Option):
814 raise TypeError, "not an Option instance: %r" % option
815 else:
816 raise TypeError, "invalid arguments"
817
818 self._check_conflict(option)
819
820 self.option_list.append(option)
821 option.container = self
822 for opt in option._short_opts:
823 self._short_opt[opt] = option
824 for opt in option._long_opts:
825 self._long_opt[opt] = option
826
827 if option.dest is not None: # option has a dest, we need a default
828 if option.default is not NO_DEFAULT:
829 self.defaults[option.dest] = option.default
830 elif not self.defaults.has_key(option.dest):
831 self.defaults[option.dest] = None
832
833 return option
834
835 def add_options (self, option_list):
836 for option in option_list:
837 self.add_option(option)
838
839 # -- Option query/removal methods ----------------------------------
840
841 def get_option (self, opt_str):
842 return (self._short_opt.get(opt_str) or
843 self._long_opt.get(opt_str))
844
845 def has_option (self, opt_str):
846 return (self._short_opt.has_key(opt_str) or
847 self._long_opt.has_key(opt_str))
848
849 def remove_option (self, opt_str):
850 option = self._short_opt.get(opt_str)
851 if option is None:
852 option = self._long_opt.get(opt_str)
853 if option is None:
854 raise ValueError("no such option %r" % opt_str)
855
856 for opt in option._short_opts:
857 del self._short_opt[opt]
858 for opt in option._long_opts:
859 del self._long_opt[opt]
860 option.container.option_list.remove(option)
861
862
863 # -- Help-formatting methods ---------------------------------------
864
865 def format_option_help (self, formatter):
866 if not self.option_list:
867 return ""
868 result = []
869 for option in self.option_list:
870 if not option.help is SUPPRESS_HELP:
871 result.append(formatter.format_option(option))
872 return "".join(result)
873
874 def format_description (self, formatter):
875 if self.description:
876 return formatter.format_description(self.description)
877 else:
878 return ""
879
880 def format_help (self, formatter):
881 if self.description:
882 desc = self.format_description(formatter) + "\n"
883 else:
884 desc = ""
885 return desc + self.format_option_help(formatter)
886
887
888class OptionGroup (OptionContainer):
889
890 def __init__ (self, parser, title, description=None):
891 self.parser = parser
892 OptionContainer.__init__(
893 self, parser.option_class, parser.conflict_handler, description)
894 self.title = title
895
896 def _create_option_list (self):
897 self.option_list = []
898 self._share_option_mappings(self.parser)
899
900 def set_title (self, title):
901 self.title = title
902
903 # -- Help-formatting methods ---------------------------------------
904
905 def format_help (self, formatter):
906 result = formatter.format_heading(self.title)
907 formatter.indent()
908 result += OptionContainer.format_help(self, formatter)
909 formatter.dedent()
910 return result
911
912
913class OptionParser (OptionContainer):
914
915 """
916 Class attributes:
917 standard_option_list : [Option]
918 list of standard options that will be accepted by all instances
919 of this parser class (intended to be overridden by subclasses).
920
921 Instance attributes:
922 usage : string
923 a usage string for your program. Before it is displayed
924 to the user, "%prog" will be expanded to the name of
925 your program (os.path.basename(sys.argv[0])).
926
927 allow_interspersed_args : boolean = true
928 if true, positional arguments may be interspersed with options.
929 Assuming -a and -b each take a single argument, the command-line
930 -ablah foo bar -bboo baz
931 will be interpreted the same as
932 -ablah -bboo -- foo bar baz
933 If this flag were false, that command line would be interpreted as
934 -ablah -- foo bar -bboo baz
935 -- ie. we stop processing options as soon as we see the first
936 non-option argument. (This is the tradition followed by
937 Python's getopt module, Perl's Getopt::Std, and other argument-
938 parsing libraries, but it is generally annoying to users.)
939
940 rargs : [string]
941 the argument list currently being parsed. Only set when
942 parse_args() is active, and continually trimmed down as
943 we consume arguments. Mainly there for the benefit of
944 callback options.
945 largs : [string]
946 the list of leftover arguments that we have skipped while
947 parsing options. If allow_interspersed_args is false, this
948 list is always empty.
949 values : Values
950 the set of option values currently being accumulated. Only
951 set when parse_args() is active. Also mainly for callbacks.
952
953 Because of the 'rargs', 'largs', and 'values' attributes,
954 OptionParser is not thread-safe. If, for some perverse reason, you
955 need to parse command-line arguments simultaneously in different
956 threads, use different OptionParser instances.
957
958 """
959
960 standard_option_list = []
961
962 def __init__ (self,
963 usage=None,
964 option_list=None,
965 option_class=Option,
966 version=None,
967 conflict_handler="error",
968 description=None,
969 formatter=None,
970 add_help_option=1):
971 OptionContainer.__init__(
972 self, option_class, conflict_handler, description)
973 self.set_usage(usage)
974 self.version = version
975 self.allow_interspersed_args = 1
976 if formatter is None:
977 formatter = IndentedHelpFormatter()
978 self.formatter = formatter
979
980 # Populate the option list; initial sources are the
981 # standard_option_list class attribute, the 'option_list'
982 # argument, and the STD_VERSION_OPTION (if 'version' supplied)
983 # and STD_HELP_OPTION globals.
984 self._populate_option_list(option_list,
985 add_help=add_help_option)
986
987 self._init_parsing_state()
988
989 # -- Private methods -----------------------------------------------
990 # (used by our or OptionContainer's constructor)
991
992 def _create_option_list (self):
993 self.option_list = []
994 self.option_groups = []
995 self._create_option_mappings()
996
997 def _populate_option_list (self, option_list, add_help=1):
998 if self.standard_option_list:
999 self.add_options(self.standard_option_list)
1000 if option_list:
1001 self.add_options(option_list)
1002 if self.version:
1003 self.add_option(STD_VERSION_OPTION)
1004 if add_help:
1005 self.add_option(STD_HELP_OPTION)
1006
1007 def _init_parsing_state (self):
1008 # These are set in parse_args() for the convenience of callbacks.
1009 self.rargs = None
1010 self.largs = None
1011 self.values = None
1012
1013
1014 # -- Simple modifier methods ---------------------------------------
1015
1016 def set_usage (self, usage):
1017 if usage is None:
1018 self.usage = "%prog [options]"
1019 elif usage is SUPPRESS_USAGE:
1020 self.usage = None
1021 elif usage.startswith("usage: "):
1022 # for backwards compatibility with Optik 1.3 and earlier
1023 self.usage = usage[7:]
1024 else:
1025 self.usage = usage
1026
1027 def enable_interspersed_args (self):
1028 self.allow_interspersed_args = 1
1029
1030 def disable_interspersed_args (self):
1031 self.allow_interspersed_args = 0
1032
1033 def set_default (self, dest, value):
1034 self.defaults[dest] = value
1035
1036 def set_defaults (self, **kwargs):
1037 self.defaults.update(kwargs)
1038
1039 def get_default_values (self):
1040 return Values(self.defaults)
1041
1042
1043 # -- OptionGroup methods -------------------------------------------
1044
1045 def add_option_group (self, *args, **kwargs):
1046 # XXX lots of overlap with OptionContainer.add_option()
1047 if type(args[0]) is types.StringType:
1048 group = OptionGroup(self, *args, **kwargs)
1049 elif len(args) == 1 and not kwargs:
1050 group = args[0]
1051 if not isinstance(group, OptionGroup):
1052 raise TypeError, "not an OptionGroup instance: %r" % group
1053 if group.parser is not self:
1054 raise ValueError, "invalid OptionGroup (wrong parser)"
1055 else:
1056 raise TypeError, "invalid arguments"
1057
1058 self.option_groups.append(group)
1059 return group
1060
1061 def get_option_group (self, opt_str):
1062 option = (self._short_opt.get(opt_str) or
1063 self._long_opt.get(opt_str))
1064 if option and option.container is not self:
1065 return option.container
1066 return None
1067
1068
1069 # -- Option-parsing methods ----------------------------------------
1070
1071 def _get_args (self, args):
1072 if args is None:
1073 return sys.argv[1:]
1074 else:
1075 return args[:] # don't modify caller's list
1076
1077 def parse_args (self, args=None, values=None):
1078 """
1079 parse_args(args : [string] = sys.argv[1:],
1080 values : Values = None)
1081 -> (values : Values, args : [string])
1082
1083 Parse the command-line options found in 'args' (default:
1084 sys.argv[1:]). Any errors result in a call to 'error()', which
1085 by default prints the usage message to stderr and calls
1086 sys.exit() with an error message. On success returns a pair
1087 (values, args) where 'values' is an Values instance (with all
1088 your option values) and 'args' is the list of arguments left
1089 over after parsing options.
1090 """
1091 rargs = self._get_args(args)
1092 if values is None:
1093 values = self.get_default_values()
1094
1095 # Store the halves of the argument list as attributes for the
1096 # convenience of callbacks:
1097 # rargs
1098 # the rest of the command-line (the "r" stands for
1099 # "remaining" or "right-hand")
1100 # largs
1101 # the leftover arguments -- ie. what's left after removing
1102 # options and their arguments (the "l" stands for "leftover"
1103 # or "left-hand")
1104 self.rargs = rargs
1105 self.largs = largs = []
1106 self.values = values
1107
1108 try:
1109 stop = self._process_args(largs, rargs, values)
1110 except (BadOptionError, OptionValueError), err:
1111 self.error(err.msg)
1112
1113 args = largs + rargs
1114 return self.check_values(values, args)
1115
1116 def check_values (self, values, args):
1117 """
1118 check_values(values : Values, args : [string])
1119 -> (values : Values, args : [string])
1120
1121 Check that the supplied option values and leftover arguments are
1122 valid. Returns the option values and leftover arguments
1123 (possibly adjusted, possibly completely new -- whatever you
1124 like). Default implementation just returns the passed-in
1125 values; subclasses may override as desired.
1126 """
1127 return (values, args)
1128
1129 def _process_args (self, largs, rargs, values):
1130 """_process_args(largs : [string],
1131 rargs : [string],
1132 values : Values)
1133
1134 Process command-line arguments and populate 'values', consuming
1135 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1136 false, stop at the first non-option argument. If true, accumulate any
1137 interspersed non-option arguments in 'largs'.
1138 """
1139 while rargs:
1140 arg = rargs[0]
1141 # We handle bare "--" explicitly, and bare "-" is handled by the
1142 # standard arg handler since the short arg case ensures that the
1143 # len of the opt string is greater than 1.
1144 if arg == "--":
1145 del rargs[0]
1146 return
1147 elif arg[0:2] == "--":
1148 # process a single long option (possibly with value(s))
1149 self._process_long_opt(rargs, values)
1150 elif arg[:1] == "-" and len(arg) > 1:
1151 # process a cluster of short options (possibly with
1152 # value(s) for the last one only)
1153 self._process_short_opts(rargs, values)
1154 elif self.allow_interspersed_args:
1155 largs.append(arg)
1156 del rargs[0]
1157 else:
1158 return # stop now, leave this arg in rargs
1159
1160 # Say this is the original argument list:
1161 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1162 # ^
1163 # (we are about to process arg(i)).
1164 #
1165 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1166 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1167 # been removed from largs).
1168 #
1169 # The while loop will usually consume 1 or more arguments per pass.
1170 # If it consumes 1 (eg. arg is an option that takes no arguments),
1171 # then after _process_arg() is done the situation is:
1172 #
1173 # largs = subset of [arg0, ..., arg(i)]
1174 # rargs = [arg(i+1), ..., arg(N-1)]
1175 #
1176 # If allow_interspersed_args is false, largs will always be
1177 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1178 # not a very interesting subset!
1179
1180 def _match_long_opt (self, opt):
1181 """_match_long_opt(opt : string) -> string
1182
1183 Determine which long option string 'opt' matches, ie. which one
1184 it is an unambiguous abbrevation for. Raises BadOptionError if
1185 'opt' doesn't unambiguously match any long option string.
1186 """
1187 return _match_abbrev(opt, self._long_opt)
1188
1189 def _process_long_opt (self, rargs, values):
1190 arg = rargs.pop(0)
1191
1192 # Value explicitly attached to arg? Pretend it's the next
1193 # argument.
1194 if "=" in arg:
1195 (opt, next_arg) = arg.split("=", 1)
1196 rargs.insert(0, next_arg)
1197 had_explicit_value = 1
1198 else:
1199 opt = arg
1200 had_explicit_value = 0
1201
1202 opt = self._match_long_opt(opt)
1203 option = self._long_opt[opt]
1204 if option.takes_value():
1205 nargs = option.nargs
1206 if len(rargs) < nargs:
1207 if nargs == 1:
1208 self.error("%s option requires a value" % opt)
1209 else:
1210 self.error("%s option requires %d values"
1211 % (opt, nargs))
1212 elif nargs == 1:
1213 value = rargs.pop(0)
1214 else:
1215 value = tuple(rargs[0:nargs])
1216 del rargs[0:nargs]
1217
1218 elif had_explicit_value:
1219 self.error("%s option does not take a value" % opt)
1220
1221 else:
1222 value = None
1223
1224 option.process(opt, value, values, self)
1225
1226 def _process_short_opts (self, rargs, values):
1227 arg = rargs.pop(0)
1228 stop = 0
1229 i = 1
1230 for ch in arg[1:]:
1231 opt = "-" + ch
1232 option = self._short_opt.get(opt)
1233 i += 1 # we have consumed a character
1234
1235 if not option:
1236 self.error("no such option: %s" % opt)
1237 if option.takes_value():
1238 # Any characters left in arg? Pretend they're the
1239 # next arg, and stop consuming characters of arg.
1240 if i < len(arg):
1241 rargs.insert(0, arg[i:])
1242 stop = 1
1243
1244 nargs = option.nargs
1245 if len(rargs) < nargs:
1246 if nargs == 1:
1247 self.error("%s option requires a value" % opt)
1248 else:
1249 self.error("%s option requires %s values"
1250 % (opt, nargs))
1251 elif nargs == 1:
1252 value = rargs.pop(0)
1253 else:
1254 value = tuple(rargs[0:nargs])
1255 del rargs[0:nargs]
1256
1257 else: # option doesn't take a value
1258 value = None
1259
1260 option.process(opt, value, values, self)
1261
1262 if stop:
1263 break
1264
1265
1266 # -- Feedback methods ----------------------------------------------
1267
1268 def error (self, msg):
1269 """error(msg : string)
1270
1271 Print a usage message incorporating 'msg' to stderr and exit.
1272 If you override this in a subclass, it should not return -- it
1273 should either exit or raise an exception.
1274 """
1275 self.print_usage(sys.stderr)
1276 sys.exit("%s: error: %s" % (get_prog_name(), msg))
1277
1278 def get_usage (self):
1279 if self.usage:
1280 return self.formatter.format_usage(
1281 self.usage.replace("%prog", get_prog_name()))
1282 else:
1283 return ""
1284
1285 def print_usage (self, file=None):
1286 """print_usage(file : file = stdout)
1287
1288 Print the usage message for the current program (self.usage) to
1289 'file' (default stdout). Any occurence of the string "%prog" in
1290 self.usage is replaced with the name of the current program
1291 (basename of sys.argv[0]). Does nothing if self.usage is empty
1292 or not defined.
1293 """
1294 if self.usage:
1295 print >>file, self.get_usage()
1296
1297 def get_version (self):
1298 if self.version:
1299 return self.version.replace("%prog", get_prog_name())
1300 else:
1301 return ""
1302
1303 def print_version (self, file=None):
1304 """print_version(file : file = stdout)
1305
1306 Print the version message for this program (self.version) to
1307 'file' (default stdout). As with print_usage(), any occurence
1308 of "%prog" in self.version is replaced by the current program's
1309 name. Does nothing if self.version is empty or undefined.
1310 """
1311 if self.version:
1312 print >>file, self.get_version()
1313
1314 def format_option_help (self, formatter=None):
1315 if formatter is None:
1316 formatter = self.formatter
1317 formatter.store_option_strings(self)
1318 result = []
1319 result.append(formatter.format_heading("options"))
1320 formatter.indent()
1321 if self.option_list:
1322 result.append(OptionContainer.format_option_help(self, formatter))
1323 result.append("\n")
1324 for group in self.option_groups:
1325 result.append(group.format_help(formatter))
1326 result.append("\n")
1327 formatter.dedent()
1328 # Drop the last "\n", or the header if no options or option groups:
1329 return "".join(result[:-1])
1330
1331 def format_help (self, formatter=None):
1332 if formatter is None:
1333 formatter = self.formatter
1334 result = []
1335 if self.usage:
1336 result.append(self.get_usage() + "\n")
1337 if self.description:
1338 result.append(self.format_description(formatter) + "\n")
1339 result.append(self.format_option_help(formatter))
1340 return "".join(result)
1341
1342 def print_help (self, file=None):
1343 """print_help(file : file = stdout)
1344
1345 Print an extended help message, listing all options and any
1346 help text provided with them, to 'file' (default stdout).
1347 """
1348 if file is None:
1349 file = sys.stdout
1350 file.write(self.format_help())
1351
1352# class OptionParser
1353
1354
1355def _match_abbrev (s, wordmap):
1356 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1357
1358 Return the string key in 'wordmap' for which 's' is an unambiguous
1359 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1360 'words', raise BadOptionError.
1361 """
1362 # Is there an exact match?
1363 if wordmap.has_key(s):
1364 return s
1365 else:
1366 # Isolate all words with s as a prefix.
1367 possibilities = [word for word in wordmap.keys()
1368 if word.startswith(s)]
1369 # No exact match, so there had better be just one possibility.
1370 if len(possibilities) == 1:
1371 return possibilities[0]
1372 elif not possibilities:
1373 raise BadOptionError("no such option: %s" % s)
1374 else:
1375 # More than one possible completion: ambiguous prefix.
1376 raise BadOptionError("ambiguous option: %s (%s?)"
1377 % (s, ", ".join(possibilities)))
1378
1379
1380# Some day, there might be many Option classes. As of Optik 1.3, the
1381# preferred way to instantiate Options is indirectly, via make_option(),
1382# which will become a factory function when there are many Option
1383# classes.
1384make_option = Option