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