blob: f30fc458b22a5df7b58853f28efef865e79b0239 [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 Wardeba20e62004-07-31 16:15:44 +000019__version__ = "1.5a1"
Greg Ward2492fcf2003-04-21 02:40:34 +000020
Greg Ward4656ed42003-05-08 01:38:52 +000021__all__ = ['Option',
22 'SUPPRESS_HELP',
23 'SUPPRESS_USAGE',
Greg Ward4656ed42003-05-08 01:38:52 +000024 'Values',
25 'OptionContainer',
26 'OptionGroup',
27 'OptionParser',
28 'HelpFormatter',
29 'IndentedHelpFormatter',
30 'TitledHelpFormatter',
31 'OptParseError',
32 'OptionError',
33 'OptionConflictError',
34 'OptionValueError',
35 'BadOptionError']
Greg Ward2492fcf2003-04-21 02:40:34 +000036
Guido van Rossumb9ba4582002-11-14 22:00:19 +000037__copyright__ = """
Greg Wardeba20e62004-07-31 16:15:44 +000038Copyright (c) 2001-2004 Gregory P. Ward. All rights reserved.
39Copyright (c) 2002-2004 Python Software Foundation. All rights reserved.
Guido van Rossumb9ba4582002-11-14 22:00:19 +000040
41Redistribution and use in source and binary forms, with or without
42modification, are permitted provided that the following conditions are
43met:
44
45 * Redistributions of source code must retain the above copyright
46 notice, this list of conditions and the following disclaimer.
47
48 * Redistributions in binary form must reproduce the above copyright
49 notice, this list of conditions and the following disclaimer in the
50 documentation and/or other materials provided with the distribution.
51
52 * Neither the name of the author nor the names of its
53 contributors may be used to endorse or promote products derived from
54 this software without specific prior written permission.
55
56THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
57IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
59PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
60CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
61EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
62PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
63PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
64LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
65NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
66SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
67"""
68
69import sys, os
70import types
71import textwrap
Greg Wardeba20e62004-07-31 16:15:44 +000072from gettext import gettext as _
73
74def _repr(self):
75 return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
76
77
78# This file was generated from:
79# Id: option_parser.py,v 1.67 2004/07/24 23:21:21 gward Exp
80# Id: option.py,v 1.33 2004/07/24 23:21:21 gward Exp
81# Id: help.py,v 1.15 2004/07/24 23:21:21 gward Exp
82# Id: errors.py,v 1.9 2004/07/24 23:21:21 gward Exp
Guido van Rossumb9ba4582002-11-14 22:00:19 +000083
Guido van Rossumb9ba4582002-11-14 22:00:19 +000084class OptParseError (Exception):
Greg Wardeba20e62004-07-31 16:15:44 +000085 def __init__(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000086 self.msg = msg
87
Greg Wardeba20e62004-07-31 16:15:44 +000088 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000089 return self.msg
90
Greg Ward2492fcf2003-04-21 02:40:34 +000091
Guido van Rossumb9ba4582002-11-14 22:00:19 +000092class OptionError (OptParseError):
93 """
94 Raised if an Option instance is created with invalid or
95 inconsistent arguments.
96 """
97
Greg Wardeba20e62004-07-31 16:15:44 +000098 def __init__(self, msg, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000099 self.msg = msg
100 self.option_id = str(option)
101
Greg Wardeba20e62004-07-31 16:15:44 +0000102 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000103 if self.option_id:
104 return "option %s: %s" % (self.option_id, self.msg)
105 else:
106 return self.msg
107
108class OptionConflictError (OptionError):
109 """
110 Raised if conflicting options are added to an OptionParser.
111 """
112
113class OptionValueError (OptParseError):
114 """
115 Raised if an invalid option value is encountered on the command
116 line.
117 """
118
119class BadOptionError (OptParseError):
120 """
121 Raised if an invalid or ambiguous option is seen on the command-line.
122 """
Greg Ward2492fcf2003-04-21 02:40:34 +0000123
124
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000125class HelpFormatter:
126
127 """
128 Abstract base class for formatting option help. OptionParser
129 instances should use one of the HelpFormatter subclasses for
130 formatting help; by default IndentedHelpFormatter is used.
131
132 Instance attributes:
Greg Wardeba20e62004-07-31 16:15:44 +0000133 parser : OptionParser
134 the controlling OptionParser instance
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000135 indent_increment : int
136 the number of columns to indent per nesting level
137 max_help_position : int
138 the maximum starting column for option help text
139 help_position : int
140 the calculated starting column for option help text;
141 initially the same as the maximum
142 width : int
Greg Wardeba20e62004-07-31 16:15:44 +0000143 total number of columns for output (pass None to constructor for
144 this value to be taken from the $COLUMNS environment variable)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000145 level : int
146 current indentation level
147 current_indent : int
148 current indentation level (in columns)
149 help_width : int
150 number of columns available for option help text (calculated)
Greg Wardeba20e62004-07-31 16:15:44 +0000151 default_tag : str
152 text to replace with each option's default value, "%default"
153 by default. Set to false value to disable default value expansion.
154 option_strings : { Option : str }
155 maps Option instances to the snippet of help text explaining
156 the syntax of that option, e.g. "-h, --help" or
157 "-fFILE, --file=FILE"
158 _short_opt_fmt : str
159 format string controlling how short options with values are
160 printed in help text. Must be either "%s%s" ("-fFILE") or
161 "%s %s" ("-f FILE"), because those are the two syntaxes that
162 Optik supports.
163 _long_opt_fmt : str
164 similar but for long options; must be either "%s %s" ("--file FILE")
165 or "%s=%s" ("--file=FILE").
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000166 """
167
Greg Wardeba20e62004-07-31 16:15:44 +0000168 NO_DEFAULT_VALUE = "none"
169
170 def __init__(self,
171 indent_increment,
172 max_help_position,
173 width,
174 short_first):
175 self.parser = None
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000176 self.indent_increment = indent_increment
177 self.help_position = self.max_help_position = max_help_position
Greg Wardeba20e62004-07-31 16:15:44 +0000178 if width is None:
179 try:
180 width = int(os.environ['COLUMNS'])
181 except (KeyError, ValueError):
182 width = 80
183 width -= 2
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000184 self.width = width
185 self.current_indent = 0
186 self.level = 0
Greg Wardeba20e62004-07-31 16:15:44 +0000187 self.help_width = None # computed later
Greg Ward2492fcf2003-04-21 02:40:34 +0000188 self.short_first = short_first
Greg Wardeba20e62004-07-31 16:15:44 +0000189 self.default_tag = "%default"
190 self.option_strings = {}
191 self._short_opt_fmt = "%s %s"
192 self._long_opt_fmt = "%s=%s"
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000193
Greg Wardeba20e62004-07-31 16:15:44 +0000194 def set_parser(self, parser):
195 self.parser = parser
196
197 def set_short_opt_delimiter(self, delim):
198 if delim not in ("", " "):
199 raise ValueError(
200 "invalid metavar delimiter for short options: %r" % delim)
201 self._short_opt_fmt = "%s" + delim + "%s"
202
203 def set_long_opt_delimiter(self, delim):
204 if delim not in ("=", " "):
205 raise ValueError(
206 "invalid metavar delimiter for long options: %r" % delim)
207 self._long_opt_fmt = "%s" + delim + "%s"
208
209 def indent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000210 self.current_indent += self.indent_increment
211 self.level += 1
212
Greg Wardeba20e62004-07-31 16:15:44 +0000213 def dedent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000214 self.current_indent -= self.indent_increment
215 assert self.current_indent >= 0, "Indent decreased below 0."
216 self.level -= 1
217
Greg Wardeba20e62004-07-31 16:15:44 +0000218 def format_usage(self, usage):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000219 raise NotImplementedError, "subclasses must implement"
220
Greg Wardeba20e62004-07-31 16:15:44 +0000221 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000222 raise NotImplementedError, "subclasses must implement"
223
Greg Wardeba20e62004-07-31 16:15:44 +0000224 def format_description(self, description):
225 if not description:
226 return ""
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000227 desc_width = self.width - self.current_indent
228 indent = " "*self.current_indent
Greg Wardeba20e62004-07-31 16:15:44 +0000229 return textwrap.fill(description,
230 desc_width,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000231 initial_indent=indent,
Greg Wardeba20e62004-07-31 16:15:44 +0000232 subsequent_indent=indent) + "\n"
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000233
Greg Wardeba20e62004-07-31 16:15:44 +0000234 def expand_default(self, option):
235 if self.parser is None or not self.default_tag:
236 return option.help
237
238 default_value = self.parser.defaults.get(option.dest)
239 if default_value is NO_DEFAULT or default_value is None:
240 default_value = self.NO_DEFAULT_VALUE
241
242 return option.help.replace(self.default_tag, str(default_value))
243
244 def format_option(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000245 # The help for each option consists of two parts:
246 # * the opt strings and metavars
247 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
248 # * the user-supplied help string
249 # eg. ("turn on expert mode", "read data from FILENAME")
250 #
251 # If possible, we write both of these on the same line:
252 # -x turn on expert mode
253 #
254 # But if the opt string list is too long, we put the help
255 # string on a second line, indented to the same column it would
256 # start in if it fit on the first line.
257 # -fFILENAME, --file=FILENAME
258 # read data from FILENAME
259 result = []
Greg Wardeba20e62004-07-31 16:15:44 +0000260 opts = self.option_strings[option]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000261 opt_width = self.help_position - self.current_indent - 2
262 if len(opts) > opt_width:
263 opts = "%*s%s\n" % (self.current_indent, "", opts)
264 indent_first = self.help_position
265 else: # start help on same line as opts
266 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
267 indent_first = 0
268 result.append(opts)
269 if option.help:
Greg Wardeba20e62004-07-31 16:15:44 +0000270 help_text = self.expand_default(option)
271 help_lines = textwrap.wrap(help_text, self.help_width)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000272 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
273 result.extend(["%*s%s\n" % (self.help_position, "", line)
274 for line in help_lines[1:]])
275 elif opts[-1] != "\n":
276 result.append("\n")
277 return "".join(result)
278
Greg Wardeba20e62004-07-31 16:15:44 +0000279 def store_option_strings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000280 self.indent()
281 max_len = 0
282 for opt in parser.option_list:
283 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000284 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000285 max_len = max(max_len, len(strings) + self.current_indent)
286 self.indent()
287 for group in parser.option_groups:
288 for opt in group.option_list:
289 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000290 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000291 max_len = max(max_len, len(strings) + self.current_indent)
292 self.dedent()
293 self.dedent()
294 self.help_position = min(max_len + 2, self.max_help_position)
Greg Wardeba20e62004-07-31 16:15:44 +0000295 self.help_width = self.width - self.help_position
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000296
Greg Wardeba20e62004-07-31 16:15:44 +0000297 def format_option_strings(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000298 """Return a comma-separated list of option strings & metavariables."""
Greg Ward2492fcf2003-04-21 02:40:34 +0000299 if option.takes_value():
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000300 metavar = option.metavar or option.dest.upper()
Greg Wardeba20e62004-07-31 16:15:44 +0000301 short_opts = [self._short_opt_fmt % (sopt, metavar)
302 for sopt in option._short_opts]
303 long_opts = [self._long_opt_fmt % (lopt, metavar)
304 for lopt in option._long_opts]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000305 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000306 short_opts = option._short_opts
307 long_opts = option._long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000308
Greg Ward2492fcf2003-04-21 02:40:34 +0000309 if self.short_first:
310 opts = short_opts + long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000311 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000312 opts = long_opts + short_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000313
Greg Ward2492fcf2003-04-21 02:40:34 +0000314 return ", ".join(opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000315
316class IndentedHelpFormatter (HelpFormatter):
317 """Format help with indented section bodies.
318 """
319
Greg Wardeba20e62004-07-31 16:15:44 +0000320 def __init__(self,
321 indent_increment=2,
322 max_help_position=24,
323 width=None,
324 short_first=1):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000325 HelpFormatter.__init__(
326 self, indent_increment, max_help_position, width, short_first)
327
Greg Wardeba20e62004-07-31 16:15:44 +0000328 def format_usage(self, usage):
329 return _("usage: %s\n") % usage
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000330
Greg Wardeba20e62004-07-31 16:15:44 +0000331 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000332 return "%*s%s:\n" % (self.current_indent, "", heading)
333
334
335class TitledHelpFormatter (HelpFormatter):
336 """Format help with underlined section headers.
337 """
338
Greg Wardeba20e62004-07-31 16:15:44 +0000339 def __init__(self,
340 indent_increment=0,
341 max_help_position=24,
342 width=None,
343 short_first=0):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000344 HelpFormatter.__init__ (
345 self, indent_increment, max_help_position, width, short_first)
346
Greg Wardeba20e62004-07-31 16:15:44 +0000347 def format_usage(self, usage):
348 return "%s %s\n" % (self.format_heading(_("Usage")), usage)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000349
Greg Wardeba20e62004-07-31 16:15:44 +0000350 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000351 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
Greg Ward2492fcf2003-04-21 02:40:34 +0000352
353
Greg Wardeba20e62004-07-31 16:15:44 +0000354_builtin_cvt = { "int" : (int, _("integer")),
355 "long" : (long, _("long integer")),
356 "float" : (float, _("floating-point")),
357 "complex" : (complex, _("complex")) }
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000358
Greg Wardeba20e62004-07-31 16:15:44 +0000359def check_builtin(option, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000360 (cvt, what) = _builtin_cvt[option.type]
361 try:
362 return cvt(value)
363 except ValueError:
364 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000365 _("option %s: invalid %s value: %r") % (opt, what, value))
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000366
367def check_choice(option, opt, value):
368 if value in option.choices:
369 return value
370 else:
371 choices = ", ".join(map(repr, option.choices))
372 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000373 _("option %s: invalid choice: %r (choose from %s)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000374 % (opt, value, choices))
375
376# Not supplying a default is different from a default of None,
377# so we need an explicit "not supplied" value.
Greg Wardeba20e62004-07-31 16:15:44 +0000378NO_DEFAULT = ("NO", "DEFAULT")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000379
380
381class Option:
382 """
383 Instance attributes:
384 _short_opts : [string]
385 _long_opts : [string]
386
387 action : string
388 type : string
389 dest : string
390 default : any
391 nargs : int
392 const : any
393 choices : [string]
394 callback : function
395 callback_args : (any*)
396 callback_kwargs : { string : any }
397 help : string
398 metavar : string
399 """
400
401 # The list of instance attributes that may be set through
402 # keyword args to the constructor.
403 ATTRS = ['action',
404 'type',
405 'dest',
406 'default',
407 'nargs',
408 'const',
409 'choices',
410 'callback',
411 'callback_args',
412 'callback_kwargs',
413 'help',
414 'metavar']
415
416 # The set of actions allowed by option parsers. Explicitly listed
417 # here so the constructor can validate its arguments.
418 ACTIONS = ("store",
419 "store_const",
420 "store_true",
421 "store_false",
422 "append",
423 "count",
424 "callback",
425 "help",
426 "version")
427
428 # The set of actions that involve storing a value somewhere;
429 # also listed just for constructor argument validation. (If
430 # the action is one of these, there must be a destination.)
431 STORE_ACTIONS = ("store",
432 "store_const",
433 "store_true",
434 "store_false",
435 "append",
436 "count")
437
438 # The set of actions for which it makes sense to supply a value
439 # type, ie. where we expect an argument to this option.
440 TYPED_ACTIONS = ("store",
441 "append",
442 "callback")
443
444 # The set of known types for option parsers. Again, listed here for
445 # constructor argument validation.
446 TYPES = ("string", "int", "long", "float", "complex", "choice")
447
448 # Dictionary of argument checking functions, which convert and
449 # validate option arguments according to the option type.
450 #
451 # Signature of checking functions is:
452 # check(option : Option, opt : string, value : string) -> any
453 # where
454 # option is the Option instance calling the checker
455 # opt is the actual option seen on the command-line
456 # (eg. "-a", "--file")
457 # value is the option argument seen on the command-line
458 #
459 # The return value should be in the appropriate Python type
460 # for option.type -- eg. an integer if option.type == "int".
461 #
462 # If no checker is defined for a type, arguments will be
463 # unchecked and remain strings.
464 TYPE_CHECKER = { "int" : check_builtin,
465 "long" : check_builtin,
466 "float" : check_builtin,
Greg Wardeba20e62004-07-31 16:15:44 +0000467 "complex": check_builtin,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000468 "choice" : check_choice,
469 }
470
471
472 # CHECK_METHODS is a list of unbound method objects; they are called
473 # by the constructor, in order, after all attributes are
474 # initialized. The list is created and filled in later, after all
475 # the methods are actually defined. (I just put it here because I
476 # like to define and document all class attributes in the same
477 # place.) Subclasses that add another _check_*() method should
478 # define their own CHECK_METHODS list that adds their check method
479 # to those from this class.
480 CHECK_METHODS = None
481
482
483 # -- Constructor/initialization methods ----------------------------
484
Greg Wardeba20e62004-07-31 16:15:44 +0000485 def __init__(self, *opts, **attrs):
Greg Ward2492fcf2003-04-21 02:40:34 +0000486 # Set _short_opts, _long_opts attrs from 'opts' tuple.
487 # Have to be set now, in case no option strings are supplied.
488 self._short_opts = []
489 self._long_opts = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000490 opts = self._check_opt_strings(opts)
491 self._set_opt_strings(opts)
492
493 # Set all other attrs (action, type, etc.) from 'attrs' dict
494 self._set_attrs(attrs)
495
496 # Check all the attributes we just set. There are lots of
497 # complicated interdependencies, but luckily they can be farmed
498 # out to the _check_*() methods listed in CHECK_METHODS -- which
499 # could be handy for subclasses! The one thing these all share
500 # is that they raise OptionError if they discover a problem.
501 for checker in self.CHECK_METHODS:
502 checker(self)
503
Greg Wardeba20e62004-07-31 16:15:44 +0000504 def _check_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000505 # Filter out None because early versions of Optik had exactly
506 # one short option and one long option, either of which
507 # could be None.
508 opts = filter(None, opts)
509 if not opts:
Greg Ward2492fcf2003-04-21 02:40:34 +0000510 raise TypeError("at least one option string must be supplied")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000511 return opts
512
Greg Wardeba20e62004-07-31 16:15:44 +0000513 def _set_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000514 for opt in opts:
515 if len(opt) < 2:
516 raise OptionError(
517 "invalid option string %r: "
518 "must be at least two characters long" % opt, self)
519 elif len(opt) == 2:
520 if not (opt[0] == "-" and opt[1] != "-"):
521 raise OptionError(
522 "invalid short option string %r: "
523 "must be of the form -x, (x any non-dash char)" % opt,
524 self)
525 self._short_opts.append(opt)
526 else:
527 if not (opt[0:2] == "--" and opt[2] != "-"):
528 raise OptionError(
529 "invalid long option string %r: "
530 "must start with --, followed by non-dash" % opt,
531 self)
532 self._long_opts.append(opt)
533
Greg Wardeba20e62004-07-31 16:15:44 +0000534 def _set_attrs(self, attrs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000535 for attr in self.ATTRS:
536 if attrs.has_key(attr):
537 setattr(self, attr, attrs[attr])
538 del attrs[attr]
539 else:
540 if attr == 'default':
541 setattr(self, attr, NO_DEFAULT)
542 else:
543 setattr(self, attr, None)
544 if attrs:
545 raise OptionError(
546 "invalid keyword arguments: %s" % ", ".join(attrs.keys()),
547 self)
548
549
550 # -- Constructor validation methods --------------------------------
551
Greg Wardeba20e62004-07-31 16:15:44 +0000552 def _check_action(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000553 if self.action is None:
554 self.action = "store"
555 elif self.action not in self.ACTIONS:
556 raise OptionError("invalid action: %r" % self.action, self)
557
Greg Wardeba20e62004-07-31 16:15:44 +0000558 def _check_type(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000559 if self.type is None:
560 # XXX should factor out another class attr here: list of
561 # actions that *require* a type
562 if self.action in ("store", "append"):
563 if self.choices is not None:
564 # The "choices" attribute implies "choice" type.
565 self.type = "choice"
566 else:
567 # No type given? "string" is the most sensible default.
568 self.type = "string"
569 else:
Greg Wardeba20e62004-07-31 16:15:44 +0000570 # Allow type objects as an alternative to their names.
571 if type(self.type) is type:
572 self.type = self.type.__name__
573 if self.type == "str":
574 self.type = "string"
575
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000576 if self.type not in self.TYPES:
577 raise OptionError("invalid option type: %r" % self.type, self)
578 if self.action not in self.TYPED_ACTIONS:
579 raise OptionError(
580 "must not supply a type for action %r" % self.action, self)
581
582 def _check_choice(self):
583 if self.type == "choice":
584 if self.choices is None:
585 raise OptionError(
586 "must supply a list of choices for type 'choice'", self)
587 elif type(self.choices) not in (types.TupleType, types.ListType):
588 raise OptionError(
589 "choices must be a list of strings ('%s' supplied)"
590 % str(type(self.choices)).split("'")[1], self)
591 elif self.choices is not None:
592 raise OptionError(
593 "must not supply choices for type %r" % self.type, self)
594
Greg Wardeba20e62004-07-31 16:15:44 +0000595 def _check_dest(self):
596 # No destination given, and we need one for this action. The
597 # self.type check is for callbacks that take a value.
598 takes_value = (self.action in self.STORE_ACTIONS or
599 self.type is not None)
600 if self.dest is None and takes_value:
601
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000602 # Glean a destination from the first long option string,
603 # or from the first short option string if no long options.
604 if self._long_opts:
605 # eg. "--foo-bar" -> "foo_bar"
606 self.dest = self._long_opts[0][2:].replace('-', '_')
607 else:
608 self.dest = self._short_opts[0][1]
609
Greg Wardeba20e62004-07-31 16:15:44 +0000610 def _check_const(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000611 if self.action != "store_const" and self.const is not None:
612 raise OptionError(
613 "'const' must not be supplied for action %r" % self.action,
614 self)
615
Greg Wardeba20e62004-07-31 16:15:44 +0000616 def _check_nargs(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000617 if self.action in self.TYPED_ACTIONS:
618 if self.nargs is None:
619 self.nargs = 1
620 elif self.nargs is not None:
621 raise OptionError(
622 "'nargs' must not be supplied for action %r" % self.action,
623 self)
624
Greg Wardeba20e62004-07-31 16:15:44 +0000625 def _check_callback(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000626 if self.action == "callback":
627 if not callable(self.callback):
628 raise OptionError(
629 "callback not callable: %r" % self.callback, self)
630 if (self.callback_args is not None and
631 type(self.callback_args) is not types.TupleType):
632 raise OptionError(
633 "callback_args, if supplied, must be a tuple: not %r"
634 % self.callback_args, self)
635 if (self.callback_kwargs is not None and
636 type(self.callback_kwargs) is not types.DictType):
637 raise OptionError(
638 "callback_kwargs, if supplied, must be a dict: not %r"
639 % self.callback_kwargs, self)
640 else:
641 if self.callback is not None:
642 raise OptionError(
643 "callback supplied (%r) for non-callback option"
644 % self.callback, self)
645 if self.callback_args is not None:
646 raise OptionError(
647 "callback_args supplied for non-callback option", self)
648 if self.callback_kwargs is not None:
649 raise OptionError(
650 "callback_kwargs supplied for non-callback option", self)
651
652
653 CHECK_METHODS = [_check_action,
654 _check_type,
655 _check_choice,
656 _check_dest,
657 _check_const,
658 _check_nargs,
659 _check_callback]
660
661
662 # -- Miscellaneous methods -----------------------------------------
663
Greg Wardeba20e62004-07-31 16:15:44 +0000664 def __str__(self):
Greg Ward2492fcf2003-04-21 02:40:34 +0000665 return "/".join(self._short_opts + self._long_opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000666
Greg Wardeba20e62004-07-31 16:15:44 +0000667 __repr__ = _repr
668
669 def takes_value(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000670 return self.type is not None
671
Greg Wardeba20e62004-07-31 16:15:44 +0000672 def get_opt_string(self):
673 if self._long_opts:
674 return self._long_opts[0]
675 else:
676 return self._short_opts[0]
677
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000678
679 # -- Processing methods --------------------------------------------
680
Greg Wardeba20e62004-07-31 16:15:44 +0000681 def check_value(self, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000682 checker = self.TYPE_CHECKER.get(self.type)
683 if checker is None:
684 return value
685 else:
686 return checker(self, opt, value)
687
Greg Wardeba20e62004-07-31 16:15:44 +0000688 def convert_value(self, opt, value):
689 if value is not None:
690 if self.nargs == 1:
691 return self.check_value(opt, value)
692 else:
693 return tuple([self.check_value(opt, v) for v in value])
694
695 def process(self, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000696
697 # First, convert the value(s) to the right type. Howl if any
698 # value(s) are bogus.
Greg Wardeba20e62004-07-31 16:15:44 +0000699 value = self.convert_value(opt, value)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000700
701 # And then take whatever action is expected of us.
702 # This is a separate method to make life easier for
703 # subclasses to add new actions.
704 return self.take_action(
705 self.action, self.dest, opt, value, values, parser)
706
Greg Wardeba20e62004-07-31 16:15:44 +0000707 def take_action(self, action, dest, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000708 if action == "store":
709 setattr(values, dest, value)
710 elif action == "store_const":
711 setattr(values, dest, self.const)
712 elif action == "store_true":
Greg Ward2492fcf2003-04-21 02:40:34 +0000713 setattr(values, dest, True)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000714 elif action == "store_false":
Greg Ward2492fcf2003-04-21 02:40:34 +0000715 setattr(values, dest, False)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000716 elif action == "append":
717 values.ensure_value(dest, []).append(value)
718 elif action == "count":
719 setattr(values, dest, values.ensure_value(dest, 0) + 1)
720 elif action == "callback":
721 args = self.callback_args or ()
722 kwargs = self.callback_kwargs or {}
723 self.callback(self, opt, value, parser, *args, **kwargs)
724 elif action == "help":
725 parser.print_help()
726 sys.exit(0)
727 elif action == "version":
728 parser.print_version()
729 sys.exit(0)
730 else:
731 raise RuntimeError, "unknown action %r" % self.action
732
733 return 1
734
735# class Option
Greg Ward2492fcf2003-04-21 02:40:34 +0000736
737
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000738SUPPRESS_HELP = "SUPPRESS"+"HELP"
739SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
740
Greg Wardeba20e62004-07-31 16:15:44 +0000741# For compatibility with Python 2.2
742try:
743 True, False
744except NameError:
745 (True, False) = (1, 0)
746try:
747 basestring
748except NameError:
749 basestring = (str, unicode)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000750
751
752class Values:
753
Greg Wardeba20e62004-07-31 16:15:44 +0000754 def __init__(self, defaults=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000755 if defaults:
756 for (attr, val) in defaults.items():
757 setattr(self, attr, val)
758
Greg Wardeba20e62004-07-31 16:15:44 +0000759 def __str__(self):
760 return str(self.__dict__)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000761
Greg Wardeba20e62004-07-31 16:15:44 +0000762 __repr__ = _repr
763
764 def __eq__(self, other):
765 if isinstance(other, Values):
766 return self.__dict__ == other.__dict__
767 elif isinstance(other, dict):
768 return self.__dict__ == other
769 else:
770 return false
771
772 def __ne__(self, other):
773 return not (self == other)
774
775 def _update_careful(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000776 """
777 Update the option values from an arbitrary dictionary, but only
778 use keys from dict that already have a corresponding attribute
779 in self. Any keys in dict without a corresponding attribute
780 are silently ignored.
781 """
782 for attr in dir(self):
783 if dict.has_key(attr):
784 dval = dict[attr]
785 if dval is not None:
786 setattr(self, attr, dval)
787
Greg Wardeba20e62004-07-31 16:15:44 +0000788 def _update_loose(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000789 """
790 Update the option values from an arbitrary dictionary,
791 using all keys from the dictionary regardless of whether
792 they have a corresponding attribute in self or not.
793 """
794 self.__dict__.update(dict)
795
Greg Wardeba20e62004-07-31 16:15:44 +0000796 def _update(self, dict, mode):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000797 if mode == "careful":
798 self._update_careful(dict)
799 elif mode == "loose":
800 self._update_loose(dict)
801 else:
802 raise ValueError, "invalid update mode: %r" % mode
803
Greg Wardeba20e62004-07-31 16:15:44 +0000804 def read_module(self, modname, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000805 __import__(modname)
806 mod = sys.modules[modname]
807 self._update(vars(mod), mode)
808
Greg Wardeba20e62004-07-31 16:15:44 +0000809 def read_file(self, filename, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000810 vars = {}
811 execfile(filename, vars)
812 self._update(vars, mode)
813
Greg Wardeba20e62004-07-31 16:15:44 +0000814 def ensure_value(self, attr, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000815 if not hasattr(self, attr) or getattr(self, attr) is None:
816 setattr(self, attr, value)
817 return getattr(self, attr)
818
819
820class OptionContainer:
821
822 """
823 Abstract base class.
824
825 Class attributes:
826 standard_option_list : [Option]
827 list of standard options that will be accepted by all instances
828 of this parser class (intended to be overridden by subclasses).
829
830 Instance attributes:
831 option_list : [Option]
832 the list of Option objects contained by this OptionContainer
833 _short_opt : { string : Option }
834 dictionary mapping short option strings, eg. "-f" or "-X",
835 to the Option instances that implement them. If an Option
836 has multiple short option strings, it will appears in this
837 dictionary multiple times. [1]
838 _long_opt : { string : Option }
839 dictionary mapping long option strings, eg. "--file" or
840 "--exclude", to the Option instances that implement them.
841 Again, a given Option can occur multiple times in this
842 dictionary. [1]
843 defaults : { string : any }
844 dictionary mapping option destination names to default
845 values for each destination [1]
846
847 [1] These mappings are common to (shared by) all components of the
848 controlling OptionParser, where they are initially created.
849
850 """
851
Greg Wardeba20e62004-07-31 16:15:44 +0000852 def __init__(self, option_class, conflict_handler, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000853 # Initialize the option list and related data structures.
854 # This method must be provided by subclasses, and it must
855 # initialize at least the following instance attributes:
856 # option_list, _short_opt, _long_opt, defaults.
857 self._create_option_list()
858
859 self.option_class = option_class
860 self.set_conflict_handler(conflict_handler)
861 self.set_description(description)
862
Greg Wardeba20e62004-07-31 16:15:44 +0000863 def _create_option_mappings(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000864 # For use by OptionParser constructor -- create the master
865 # option mappings used by this OptionParser and all
866 # OptionGroups that it owns.
867 self._short_opt = {} # single letter -> Option instance
868 self._long_opt = {} # long option -> Option instance
869 self.defaults = {} # maps option dest -> default value
870
871
Greg Wardeba20e62004-07-31 16:15:44 +0000872 def _share_option_mappings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000873 # For use by OptionGroup constructor -- use shared option
874 # mappings from the OptionParser that owns this OptionGroup.
875 self._short_opt = parser._short_opt
876 self._long_opt = parser._long_opt
877 self.defaults = parser.defaults
878
Greg Wardeba20e62004-07-31 16:15:44 +0000879 def set_conflict_handler(self, handler):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000880 if handler not in ("ignore", "error", "resolve"):
881 raise ValueError, "invalid conflict_resolution value %r" % handler
882 self.conflict_handler = handler
883
Greg Wardeba20e62004-07-31 16:15:44 +0000884 def set_description(self, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000885 self.description = description
886
Greg Wardeba20e62004-07-31 16:15:44 +0000887 def get_description(self):
888 return self.description
889
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000890
891 # -- Option-adding methods -----------------------------------------
892
Greg Wardeba20e62004-07-31 16:15:44 +0000893 def _check_conflict(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000894 conflict_opts = []
895 for opt in option._short_opts:
896 if self._short_opt.has_key(opt):
897 conflict_opts.append((opt, self._short_opt[opt]))
898 for opt in option._long_opts:
899 if self._long_opt.has_key(opt):
900 conflict_opts.append((opt, self._long_opt[opt]))
901
902 if conflict_opts:
903 handler = self.conflict_handler
904 if handler == "ignore": # behaviour for Optik 1.0, 1.1
905 pass
906 elif handler == "error": # new in 1.2
907 raise OptionConflictError(
908 "conflicting option string(s): %s"
909 % ", ".join([co[0] for co in conflict_opts]),
910 option)
911 elif handler == "resolve": # new in 1.2
912 for (opt, c_option) in conflict_opts:
913 if opt.startswith("--"):
914 c_option._long_opts.remove(opt)
915 del self._long_opt[opt]
916 else:
917 c_option._short_opts.remove(opt)
918 del self._short_opt[opt]
919 if not (c_option._short_opts or c_option._long_opts):
920 c_option.container.option_list.remove(c_option)
921
Greg Wardeba20e62004-07-31 16:15:44 +0000922 def add_option(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000923 """add_option(Option)
924 add_option(opt_str, ..., kwarg=val, ...)
925 """
926 if type(args[0]) is types.StringType:
927 option = self.option_class(*args, **kwargs)
928 elif len(args) == 1 and not kwargs:
929 option = args[0]
930 if not isinstance(option, Option):
931 raise TypeError, "not an Option instance: %r" % option
932 else:
933 raise TypeError, "invalid arguments"
934
935 self._check_conflict(option)
936
937 self.option_list.append(option)
938 option.container = self
939 for opt in option._short_opts:
940 self._short_opt[opt] = option
941 for opt in option._long_opts:
942 self._long_opt[opt] = option
943
944 if option.dest is not None: # option has a dest, we need a default
945 if option.default is not NO_DEFAULT:
946 self.defaults[option.dest] = option.default
947 elif not self.defaults.has_key(option.dest):
948 self.defaults[option.dest] = None
949
950 return option
951
Greg Wardeba20e62004-07-31 16:15:44 +0000952 def add_options(self, option_list):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000953 for option in option_list:
954 self.add_option(option)
955
956 # -- Option query/removal methods ----------------------------------
957
Greg Wardeba20e62004-07-31 16:15:44 +0000958 def get_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000959 return (self._short_opt.get(opt_str) or
960 self._long_opt.get(opt_str))
961
Greg Wardeba20e62004-07-31 16:15:44 +0000962 def has_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000963 return (self._short_opt.has_key(opt_str) or
964 self._long_opt.has_key(opt_str))
965
Greg Wardeba20e62004-07-31 16:15:44 +0000966 def remove_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000967 option = self._short_opt.get(opt_str)
968 if option is None:
969 option = self._long_opt.get(opt_str)
970 if option is None:
971 raise ValueError("no such option %r" % opt_str)
972
973 for opt in option._short_opts:
974 del self._short_opt[opt]
975 for opt in option._long_opts:
976 del self._long_opt[opt]
977 option.container.option_list.remove(option)
978
979
980 # -- Help-formatting methods ---------------------------------------
981
Greg Wardeba20e62004-07-31 16:15:44 +0000982 def format_option_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000983 if not self.option_list:
984 return ""
985 result = []
986 for option in self.option_list:
987 if not option.help is SUPPRESS_HELP:
988 result.append(formatter.format_option(option))
989 return "".join(result)
990
Greg Wardeba20e62004-07-31 16:15:44 +0000991 def format_description(self, formatter):
992 return formatter.format_description(self.get_description())
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000993
Greg Wardeba20e62004-07-31 16:15:44 +0000994 def format_help(self, formatter):
995 result = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000996 if self.description:
Greg Wardeba20e62004-07-31 16:15:44 +0000997 result.append(self.format_description(formatter))
998 if self.option_list:
999 result.append(self.format_option_help(formatter))
1000 return "\n".join(result)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001001
1002
1003class OptionGroup (OptionContainer):
1004
Greg Wardeba20e62004-07-31 16:15:44 +00001005 def __init__(self, parser, title, description=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001006 self.parser = parser
1007 OptionContainer.__init__(
1008 self, parser.option_class, parser.conflict_handler, description)
1009 self.title = title
1010
Greg Wardeba20e62004-07-31 16:15:44 +00001011 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001012 self.option_list = []
1013 self._share_option_mappings(self.parser)
1014
Greg Wardeba20e62004-07-31 16:15:44 +00001015 def set_title(self, title):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001016 self.title = title
1017
1018 # -- Help-formatting methods ---------------------------------------
1019
Greg Wardeba20e62004-07-31 16:15:44 +00001020 def format_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001021 result = formatter.format_heading(self.title)
1022 formatter.indent()
1023 result += OptionContainer.format_help(self, formatter)
1024 formatter.dedent()
1025 return result
1026
1027
1028class OptionParser (OptionContainer):
1029
1030 """
1031 Class attributes:
1032 standard_option_list : [Option]
1033 list of standard options that will be accepted by all instances
1034 of this parser class (intended to be overridden by subclasses).
1035
1036 Instance attributes:
1037 usage : string
1038 a usage string for your program. Before it is displayed
1039 to the user, "%prog" will be expanded to the name of
Greg Ward2492fcf2003-04-21 02:40:34 +00001040 your program (self.prog or os.path.basename(sys.argv[0])).
1041 prog : string
1042 the name of the current program (to override
1043 os.path.basename(sys.argv[0])).
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001044
Greg Wardeba20e62004-07-31 16:15:44 +00001045 option_groups : [OptionGroup]
1046 list of option groups in this parser (option groups are
1047 irrelevant for parsing the command-line, but very useful
1048 for generating help)
1049
1050 allow_interspersed_args : bool = true
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001051 if true, positional arguments may be interspersed with options.
1052 Assuming -a and -b each take a single argument, the command-line
1053 -ablah foo bar -bboo baz
1054 will be interpreted the same as
1055 -ablah -bboo -- foo bar baz
1056 If this flag were false, that command line would be interpreted as
1057 -ablah -- foo bar -bboo baz
1058 -- ie. we stop processing options as soon as we see the first
1059 non-option argument. (This is the tradition followed by
1060 Python's getopt module, Perl's Getopt::Std, and other argument-
1061 parsing libraries, but it is generally annoying to users.)
1062
Greg Wardeba20e62004-07-31 16:15:44 +00001063 process_default_values : bool = true
1064 if true, option default values are processed similarly to option
1065 values from the command line: that is, they are passed to the
1066 type-checking function for the option's type (as long as the
1067 default value is a string). (This really only matters if you
1068 have defined custom types; see SF bug #955889.) Set it to false
1069 to restore the behaviour of Optik 1.4.1 and earlier.
1070
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001071 rargs : [string]
1072 the argument list currently being parsed. Only set when
1073 parse_args() is active, and continually trimmed down as
1074 we consume arguments. Mainly there for the benefit of
1075 callback options.
1076 largs : [string]
1077 the list of leftover arguments that we have skipped while
1078 parsing options. If allow_interspersed_args is false, this
1079 list is always empty.
1080 values : Values
1081 the set of option values currently being accumulated. Only
1082 set when parse_args() is active. Also mainly for callbacks.
1083
1084 Because of the 'rargs', 'largs', and 'values' attributes,
1085 OptionParser is not thread-safe. If, for some perverse reason, you
1086 need to parse command-line arguments simultaneously in different
1087 threads, use different OptionParser instances.
1088
1089 """
1090
1091 standard_option_list = []
1092
Greg Wardeba20e62004-07-31 16:15:44 +00001093 def __init__(self,
1094 usage=None,
1095 option_list=None,
1096 option_class=Option,
1097 version=None,
1098 conflict_handler="error",
1099 description=None,
1100 formatter=None,
1101 add_help_option=True,
1102 prog=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001103 OptionContainer.__init__(
1104 self, option_class, conflict_handler, description)
1105 self.set_usage(usage)
Greg Ward2492fcf2003-04-21 02:40:34 +00001106 self.prog = prog
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001107 self.version = version
Greg Wardeba20e62004-07-31 16:15:44 +00001108 self.allow_interspersed_args = True
1109 self.process_default_values = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001110 if formatter is None:
1111 formatter = IndentedHelpFormatter()
1112 self.formatter = formatter
Greg Wardeba20e62004-07-31 16:15:44 +00001113 self.formatter.set_parser(self)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001114
1115 # Populate the option list; initial sources are the
1116 # standard_option_list class attribute, the 'option_list'
Greg Wardeba20e62004-07-31 16:15:44 +00001117 # argument, and (if applicable) the _add_version_option() and
1118 # _add_help_option() methods.
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001119 self._populate_option_list(option_list,
1120 add_help=add_help_option)
1121
1122 self._init_parsing_state()
1123
1124 # -- Private methods -----------------------------------------------
1125 # (used by our or OptionContainer's constructor)
1126
Greg Wardeba20e62004-07-31 16:15:44 +00001127 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001128 self.option_list = []
1129 self.option_groups = []
1130 self._create_option_mappings()
1131
Greg Wardeba20e62004-07-31 16:15:44 +00001132 def _add_help_option(self):
1133 self.add_option("-h", "--help",
1134 action="help",
1135 help=_("show this help message and exit"))
1136
1137 def _add_version_option(self):
1138 self.add_option("--version",
1139 action="version",
1140 help=_("show program's version number and exit"))
1141
1142 def _populate_option_list(self, option_list, add_help=True):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001143 if self.standard_option_list:
1144 self.add_options(self.standard_option_list)
1145 if option_list:
1146 self.add_options(option_list)
1147 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001148 self._add_version_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001149 if add_help:
Greg Wardeba20e62004-07-31 16:15:44 +00001150 self._add_help_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001151
Greg Wardeba20e62004-07-31 16:15:44 +00001152 def _init_parsing_state(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001153 # These are set in parse_args() for the convenience of callbacks.
1154 self.rargs = None
1155 self.largs = None
1156 self.values = None
1157
1158
1159 # -- Simple modifier methods ---------------------------------------
1160
Greg Wardeba20e62004-07-31 16:15:44 +00001161 def set_usage(self, usage):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001162 if usage is None:
Greg Wardeba20e62004-07-31 16:15:44 +00001163 self.usage = _("%prog [options]")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001164 elif usage is SUPPRESS_USAGE:
1165 self.usage = None
Greg Wardeba20e62004-07-31 16:15:44 +00001166 # For backwards compatibility with Optik 1.3 and earlier.
1167 elif usage.startswith("usage:" + " "):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001168 self.usage = usage[7:]
1169 else:
1170 self.usage = usage
1171
Greg Wardeba20e62004-07-31 16:15:44 +00001172 def enable_interspersed_args(self):
1173 self.allow_interspersed_args = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001174
Greg Wardeba20e62004-07-31 16:15:44 +00001175 def disable_interspersed_args(self):
1176 self.allow_interspersed_args = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001177
Greg Wardeba20e62004-07-31 16:15:44 +00001178 def set_process_default_values(self, process):
1179 self.process_default_values = process
1180
1181 def set_default(self, dest, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001182 self.defaults[dest] = value
1183
Greg Wardeba20e62004-07-31 16:15:44 +00001184 def set_defaults(self, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001185 self.defaults.update(kwargs)
1186
Greg Wardeba20e62004-07-31 16:15:44 +00001187 def _get_all_options(self):
1188 options = self.option_list[:]
1189 for group in self.option_groups:
1190 options.extend(group.option_list)
1191 return options
1192
1193 def get_default_values(self):
1194 if not self.process_default_values:
1195 # Old, pre-Optik 1.5 behaviour.
1196 return Values(self.defaults)
1197
1198 defaults = self.defaults.copy()
1199 for option in self._get_all_options():
1200 default = defaults.get(option.dest)
1201 if isinstance(default, basestring):
1202 opt_str = option.get_opt_string()
1203 defaults[option.dest] = option.check_value(opt_str, default)
1204
1205 return Values(defaults)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001206
1207
1208 # -- OptionGroup methods -------------------------------------------
1209
Greg Wardeba20e62004-07-31 16:15:44 +00001210 def add_option_group(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001211 # XXX lots of overlap with OptionContainer.add_option()
1212 if type(args[0]) is types.StringType:
1213 group = OptionGroup(self, *args, **kwargs)
1214 elif len(args) == 1 and not kwargs:
1215 group = args[0]
1216 if not isinstance(group, OptionGroup):
1217 raise TypeError, "not an OptionGroup instance: %r" % group
1218 if group.parser is not self:
1219 raise ValueError, "invalid OptionGroup (wrong parser)"
1220 else:
1221 raise TypeError, "invalid arguments"
1222
1223 self.option_groups.append(group)
1224 return group
1225
Greg Wardeba20e62004-07-31 16:15:44 +00001226 def get_option_group(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001227 option = (self._short_opt.get(opt_str) or
1228 self._long_opt.get(opt_str))
1229 if option and option.container is not self:
1230 return option.container
1231 return None
1232
1233
1234 # -- Option-parsing methods ----------------------------------------
1235
Greg Wardeba20e62004-07-31 16:15:44 +00001236 def _get_args(self, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001237 if args is None:
1238 return sys.argv[1:]
1239 else:
1240 return args[:] # don't modify caller's list
1241
Greg Wardeba20e62004-07-31 16:15:44 +00001242 def parse_args(self, args=None, values=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001243 """
1244 parse_args(args : [string] = sys.argv[1:],
1245 values : Values = None)
1246 -> (values : Values, args : [string])
1247
1248 Parse the command-line options found in 'args' (default:
1249 sys.argv[1:]). Any errors result in a call to 'error()', which
1250 by default prints the usage message to stderr and calls
1251 sys.exit() with an error message. On success returns a pair
1252 (values, args) where 'values' is an Values instance (with all
1253 your option values) and 'args' is the list of arguments left
1254 over after parsing options.
1255 """
1256 rargs = self._get_args(args)
1257 if values is None:
1258 values = self.get_default_values()
1259
1260 # Store the halves of the argument list as attributes for the
1261 # convenience of callbacks:
1262 # rargs
1263 # the rest of the command-line (the "r" stands for
1264 # "remaining" or "right-hand")
1265 # largs
1266 # the leftover arguments -- ie. what's left after removing
1267 # options and their arguments (the "l" stands for "leftover"
1268 # or "left-hand")
1269 self.rargs = rargs
1270 self.largs = largs = []
1271 self.values = values
1272
1273 try:
1274 stop = self._process_args(largs, rargs, values)
1275 except (BadOptionError, OptionValueError), err:
1276 self.error(err.msg)
1277
1278 args = largs + rargs
1279 return self.check_values(values, args)
1280
Greg Wardeba20e62004-07-31 16:15:44 +00001281 def check_values(self, values, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001282 """
1283 check_values(values : Values, args : [string])
1284 -> (values : Values, args : [string])
1285
1286 Check that the supplied option values and leftover arguments are
1287 valid. Returns the option values and leftover arguments
1288 (possibly adjusted, possibly completely new -- whatever you
1289 like). Default implementation just returns the passed-in
1290 values; subclasses may override as desired.
1291 """
1292 return (values, args)
1293
Greg Wardeba20e62004-07-31 16:15:44 +00001294 def _process_args(self, largs, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001295 """_process_args(largs : [string],
1296 rargs : [string],
1297 values : Values)
1298
1299 Process command-line arguments and populate 'values', consuming
1300 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1301 false, stop at the first non-option argument. If true, accumulate any
1302 interspersed non-option arguments in 'largs'.
1303 """
1304 while rargs:
1305 arg = rargs[0]
1306 # We handle bare "--" explicitly, and bare "-" is handled by the
1307 # standard arg handler since the short arg case ensures that the
1308 # len of the opt string is greater than 1.
1309 if arg == "--":
1310 del rargs[0]
1311 return
1312 elif arg[0:2] == "--":
1313 # process a single long option (possibly with value(s))
1314 self._process_long_opt(rargs, values)
1315 elif arg[:1] == "-" and len(arg) > 1:
1316 # process a cluster of short options (possibly with
1317 # value(s) for the last one only)
1318 self._process_short_opts(rargs, values)
1319 elif self.allow_interspersed_args:
1320 largs.append(arg)
1321 del rargs[0]
1322 else:
1323 return # stop now, leave this arg in rargs
1324
1325 # Say this is the original argument list:
1326 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1327 # ^
1328 # (we are about to process arg(i)).
1329 #
1330 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1331 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1332 # been removed from largs).
1333 #
1334 # The while loop will usually consume 1 or more arguments per pass.
1335 # If it consumes 1 (eg. arg is an option that takes no arguments),
1336 # then after _process_arg() is done the situation is:
1337 #
1338 # largs = subset of [arg0, ..., arg(i)]
1339 # rargs = [arg(i+1), ..., arg(N-1)]
1340 #
1341 # If allow_interspersed_args is false, largs will always be
1342 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1343 # not a very interesting subset!
1344
Greg Wardeba20e62004-07-31 16:15:44 +00001345 def _match_long_opt(self, opt):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001346 """_match_long_opt(opt : string) -> string
1347
1348 Determine which long option string 'opt' matches, ie. which one
1349 it is an unambiguous abbrevation for. Raises BadOptionError if
1350 'opt' doesn't unambiguously match any long option string.
1351 """
1352 return _match_abbrev(opt, self._long_opt)
1353
Greg Wardeba20e62004-07-31 16:15:44 +00001354 def _process_long_opt(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001355 arg = rargs.pop(0)
1356
1357 # Value explicitly attached to arg? Pretend it's the next
1358 # argument.
1359 if "=" in arg:
1360 (opt, next_arg) = arg.split("=", 1)
1361 rargs.insert(0, next_arg)
Greg Wardeba20e62004-07-31 16:15:44 +00001362 had_explicit_value = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001363 else:
1364 opt = arg
Greg Wardeba20e62004-07-31 16:15:44 +00001365 had_explicit_value = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001366
1367 opt = self._match_long_opt(opt)
1368 option = self._long_opt[opt]
1369 if option.takes_value():
1370 nargs = option.nargs
1371 if len(rargs) < nargs:
1372 if nargs == 1:
Greg Wardeba20e62004-07-31 16:15:44 +00001373 self.error(_("%s option requires an argument") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001374 else:
Greg Wardeba20e62004-07-31 16:15:44 +00001375 self.error(_("%s option requires %d arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001376 % (opt, nargs))
1377 elif nargs == 1:
1378 value = rargs.pop(0)
1379 else:
1380 value = tuple(rargs[0:nargs])
1381 del rargs[0:nargs]
1382
1383 elif had_explicit_value:
Greg Wardeba20e62004-07-31 16:15:44 +00001384 self.error(_("%s option does not take a value") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001385
1386 else:
1387 value = None
1388
1389 option.process(opt, value, values, self)
1390
Greg Wardeba20e62004-07-31 16:15:44 +00001391 def _process_short_opts(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001392 arg = rargs.pop(0)
Greg Wardeba20e62004-07-31 16:15:44 +00001393 stop = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001394 i = 1
1395 for ch in arg[1:]:
1396 opt = "-" + ch
1397 option = self._short_opt.get(opt)
1398 i += 1 # we have consumed a character
1399
1400 if not option:
Greg Wardeba20e62004-07-31 16:15:44 +00001401 self.error(_("no such option: %s") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001402 if option.takes_value():
1403 # Any characters left in arg? Pretend they're the
1404 # next arg, and stop consuming characters of arg.
1405 if i < len(arg):
1406 rargs.insert(0, arg[i:])
Greg Wardeba20e62004-07-31 16:15:44 +00001407 stop = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001408
1409 nargs = option.nargs
1410 if len(rargs) < nargs:
1411 if nargs == 1:
Greg Wardeba20e62004-07-31 16:15:44 +00001412 self.error(_("%s option requires an argument") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001413 else:
Greg Wardeba20e62004-07-31 16:15:44 +00001414 self.error(_("%s option requires %d arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001415 % (opt, nargs))
1416 elif nargs == 1:
1417 value = rargs.pop(0)
1418 else:
1419 value = tuple(rargs[0:nargs])
1420 del rargs[0:nargs]
1421
1422 else: # option doesn't take a value
1423 value = None
1424
1425 option.process(opt, value, values, self)
1426
1427 if stop:
1428 break
1429
1430
1431 # -- Feedback methods ----------------------------------------------
1432
Greg Wardeba20e62004-07-31 16:15:44 +00001433 def get_prog_name(self):
1434 if self.prog is None:
1435 return os.path.basename(sys.argv[0])
1436 else:
1437 return self.prog
1438
1439 def expand_prog_name(self, s):
1440 return s.replace("%prog", self.get_prog_name())
1441
1442 def get_description(self):
1443 return self.expand_prog_name(self.description)
1444
1445 def error(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001446 """error(msg : string)
1447
1448 Print a usage message incorporating 'msg' to stderr and exit.
1449 If you override this in a subclass, it should not return -- it
1450 should either exit or raise an exception.
1451 """
1452 self.print_usage(sys.stderr)
Greg Wardeba20e62004-07-31 16:15:44 +00001453 sys.stderr.write("%s: error: %s\n" % (self.get_prog_name(), msg))
1454 sys.exit(2) # command-line usage error
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001455
Greg Wardeba20e62004-07-31 16:15:44 +00001456 def get_usage(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001457 if self.usage:
1458 return self.formatter.format_usage(
Greg Wardeba20e62004-07-31 16:15:44 +00001459 self.expand_prog_name(self.usage))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001460 else:
1461 return ""
1462
Greg Wardeba20e62004-07-31 16:15:44 +00001463 def print_usage(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001464 """print_usage(file : file = stdout)
1465
1466 Print the usage message for the current program (self.usage) to
1467 'file' (default stdout). Any occurence of the string "%prog" in
1468 self.usage is replaced with the name of the current program
1469 (basename of sys.argv[0]). Does nothing if self.usage is empty
1470 or not defined.
1471 """
1472 if self.usage:
1473 print >>file, self.get_usage()
1474
Greg Wardeba20e62004-07-31 16:15:44 +00001475 def get_version(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001476 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001477 return self.expand_prog_name(self.version)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001478 else:
1479 return ""
1480
Greg Wardeba20e62004-07-31 16:15:44 +00001481 def print_version(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001482 """print_version(file : file = stdout)
1483
1484 Print the version message for this program (self.version) to
1485 'file' (default stdout). As with print_usage(), any occurence
1486 of "%prog" in self.version is replaced by the current program's
1487 name. Does nothing if self.version is empty or undefined.
1488 """
1489 if self.version:
1490 print >>file, self.get_version()
1491
Greg Wardeba20e62004-07-31 16:15:44 +00001492 def format_option_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001493 if formatter is None:
1494 formatter = self.formatter
1495 formatter.store_option_strings(self)
1496 result = []
Greg Wardeba20e62004-07-31 16:15:44 +00001497 result.append(formatter.format_heading(_("options")))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001498 formatter.indent()
1499 if self.option_list:
1500 result.append(OptionContainer.format_option_help(self, formatter))
1501 result.append("\n")
1502 for group in self.option_groups:
1503 result.append(group.format_help(formatter))
1504 result.append("\n")
1505 formatter.dedent()
1506 # Drop the last "\n", or the header if no options or option groups:
1507 return "".join(result[:-1])
1508
Greg Wardeba20e62004-07-31 16:15:44 +00001509 def format_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001510 if formatter is None:
1511 formatter = self.formatter
1512 result = []
1513 if self.usage:
1514 result.append(self.get_usage() + "\n")
1515 if self.description:
1516 result.append(self.format_description(formatter) + "\n")
1517 result.append(self.format_option_help(formatter))
1518 return "".join(result)
1519
Greg Wardeba20e62004-07-31 16:15:44 +00001520 def print_help(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001521 """print_help(file : file = stdout)
1522
1523 Print an extended help message, listing all options and any
1524 help text provided with them, to 'file' (default stdout).
1525 """
1526 if file is None:
1527 file = sys.stdout
1528 file.write(self.format_help())
1529
1530# class OptionParser
1531
1532
Greg Wardeba20e62004-07-31 16:15:44 +00001533def _match_abbrev(s, wordmap):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001534 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1535
1536 Return the string key in 'wordmap' for which 's' is an unambiguous
1537 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1538 'words', raise BadOptionError.
1539 """
1540 # Is there an exact match?
1541 if wordmap.has_key(s):
1542 return s
1543 else:
1544 # Isolate all words with s as a prefix.
1545 possibilities = [word for word in wordmap.keys()
1546 if word.startswith(s)]
1547 # No exact match, so there had better be just one possibility.
1548 if len(possibilities) == 1:
1549 return possibilities[0]
1550 elif not possibilities:
Greg Wardeba20e62004-07-31 16:15:44 +00001551 raise BadOptionError(_("no such option: %s") % s)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001552 else:
1553 # More than one possible completion: ambiguous prefix.
Greg Wardeba20e62004-07-31 16:15:44 +00001554 raise BadOptionError(_("ambiguous option: %s (%s?)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001555 % (s, ", ".join(possibilities)))
1556
1557
1558# Some day, there might be many Option classes. As of Optik 1.3, the
1559# preferred way to instantiate Options is indirectly, via make_option(),
1560# which will become a factory function when there are many Option
1561# classes.
1562make_option = Option