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