blob: 6d3c94bff37b6247bb7b7a2673505ddc2f0b5b60 [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 Ward48aa84b2004-10-27 02:20:04 +000019__version__ = "1.5a2"
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
Brett Cannon84667c02004-12-07 03:25:18 +000072try:
73 from gettext import gettext as _
74except ImportError:
75 _ = lambda arg: arg
Greg Wardeba20e62004-07-31 16:15:44 +000076
77def _repr(self):
78 return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
79
80
81# This file was generated from:
Greg Ward48aa84b2004-10-27 02:20:04 +000082# Id: option_parser.py 421 2004-10-26 00:45:16Z greg
83# Id: option.py 422 2004-10-26 00:53:47Z greg
84# Id: help.py 367 2004-07-24 23:21:21Z gward
85# Id: errors.py 367 2004-07-24 23:21:21Z gward
Guido van Rossumb9ba4582002-11-14 22:00:19 +000086
Guido van Rossumb9ba4582002-11-14 22:00:19 +000087class OptParseError (Exception):
Greg Wardeba20e62004-07-31 16:15:44 +000088 def __init__(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000089 self.msg = msg
90
Greg Wardeba20e62004-07-31 16:15:44 +000091 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000092 return self.msg
93
Greg Ward2492fcf2003-04-21 02:40:34 +000094
Guido van Rossumb9ba4582002-11-14 22:00:19 +000095class OptionError (OptParseError):
96 """
97 Raised if an Option instance is created with invalid or
98 inconsistent arguments.
99 """
100
Greg Wardeba20e62004-07-31 16:15:44 +0000101 def __init__(self, msg, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000102 self.msg = msg
103 self.option_id = str(option)
104
Greg Wardeba20e62004-07-31 16:15:44 +0000105 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000106 if self.option_id:
107 return "option %s: %s" % (self.option_id, self.msg)
108 else:
109 return self.msg
110
111class OptionConflictError (OptionError):
112 """
113 Raised if conflicting options are added to an OptionParser.
114 """
115
116class OptionValueError (OptParseError):
117 """
118 Raised if an invalid option value is encountered on the command
119 line.
120 """
121
122class BadOptionError (OptParseError):
123 """
124 Raised if an invalid or ambiguous option is seen on the command-line.
125 """
Greg Ward2492fcf2003-04-21 02:40:34 +0000126
127
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000128class HelpFormatter:
129
130 """
131 Abstract base class for formatting option help. OptionParser
132 instances should use one of the HelpFormatter subclasses for
133 formatting help; by default IndentedHelpFormatter is used.
134
135 Instance attributes:
Greg Wardeba20e62004-07-31 16:15:44 +0000136 parser : OptionParser
137 the controlling OptionParser instance
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000138 indent_increment : int
139 the number of columns to indent per nesting level
140 max_help_position : int
141 the maximum starting column for option help text
142 help_position : int
143 the calculated starting column for option help text;
144 initially the same as the maximum
145 width : int
Greg Wardeba20e62004-07-31 16:15:44 +0000146 total number of columns for output (pass None to constructor for
147 this value to be taken from the $COLUMNS environment variable)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000148 level : int
149 current indentation level
150 current_indent : int
151 current indentation level (in columns)
152 help_width : int
153 number of columns available for option help text (calculated)
Greg Wardeba20e62004-07-31 16:15:44 +0000154 default_tag : str
155 text to replace with each option's default value, "%default"
156 by default. Set to false value to disable default value expansion.
157 option_strings : { Option : str }
158 maps Option instances to the snippet of help text explaining
159 the syntax of that option, e.g. "-h, --help" or
160 "-fFILE, --file=FILE"
161 _short_opt_fmt : str
162 format string controlling how short options with values are
163 printed in help text. Must be either "%s%s" ("-fFILE") or
164 "%s %s" ("-f FILE"), because those are the two syntaxes that
165 Optik supports.
166 _long_opt_fmt : str
167 similar but for long options; must be either "%s %s" ("--file FILE")
168 or "%s=%s" ("--file=FILE").
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000169 """
170
Greg Wardeba20e62004-07-31 16:15:44 +0000171 NO_DEFAULT_VALUE = "none"
172
173 def __init__(self,
174 indent_increment,
175 max_help_position,
176 width,
177 short_first):
178 self.parser = None
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000179 self.indent_increment = indent_increment
180 self.help_position = self.max_help_position = max_help_position
Greg Wardeba20e62004-07-31 16:15:44 +0000181 if width is None:
182 try:
183 width = int(os.environ['COLUMNS'])
184 except (KeyError, ValueError):
185 width = 80
186 width -= 2
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000187 self.width = width
188 self.current_indent = 0
189 self.level = 0
Greg Wardeba20e62004-07-31 16:15:44 +0000190 self.help_width = None # computed later
Greg Ward2492fcf2003-04-21 02:40:34 +0000191 self.short_first = short_first
Greg Wardeba20e62004-07-31 16:15:44 +0000192 self.default_tag = "%default"
193 self.option_strings = {}
194 self._short_opt_fmt = "%s %s"
195 self._long_opt_fmt = "%s=%s"
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000196
Greg Wardeba20e62004-07-31 16:15:44 +0000197 def set_parser(self, parser):
198 self.parser = parser
199
200 def set_short_opt_delimiter(self, delim):
201 if delim not in ("", " "):
202 raise ValueError(
203 "invalid metavar delimiter for short options: %r" % delim)
204 self._short_opt_fmt = "%s" + delim + "%s"
205
206 def set_long_opt_delimiter(self, delim):
207 if delim not in ("=", " "):
208 raise ValueError(
209 "invalid metavar delimiter for long options: %r" % delim)
210 self._long_opt_fmt = "%s" + delim + "%s"
211
212 def indent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000213 self.current_indent += self.indent_increment
214 self.level += 1
215
Greg Wardeba20e62004-07-31 16:15:44 +0000216 def dedent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000217 self.current_indent -= self.indent_increment
218 assert self.current_indent >= 0, "Indent decreased below 0."
219 self.level -= 1
220
Greg Wardeba20e62004-07-31 16:15:44 +0000221 def format_usage(self, usage):
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_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000225 raise NotImplementedError, "subclasses must implement"
226
Greg Wardeba20e62004-07-31 16:15:44 +0000227 def format_description(self, description):
228 if not description:
229 return ""
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000230 desc_width = self.width - self.current_indent
231 indent = " "*self.current_indent
Greg Wardeba20e62004-07-31 16:15:44 +0000232 return textwrap.fill(description,
233 desc_width,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000234 initial_indent=indent,
Greg Wardeba20e62004-07-31 16:15:44 +0000235 subsequent_indent=indent) + "\n"
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000236
Greg Wardeba20e62004-07-31 16:15:44 +0000237 def expand_default(self, option):
238 if self.parser is None or not self.default_tag:
239 return option.help
240
241 default_value = self.parser.defaults.get(option.dest)
242 if default_value is NO_DEFAULT or default_value is None:
243 default_value = self.NO_DEFAULT_VALUE
244
245 return option.help.replace(self.default_tag, str(default_value))
246
247 def format_option(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000248 # The help for each option consists of two parts:
249 # * the opt strings and metavars
250 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
251 # * the user-supplied help string
252 # eg. ("turn on expert mode", "read data from FILENAME")
253 #
254 # If possible, we write both of these on the same line:
255 # -x turn on expert mode
256 #
257 # But if the opt string list is too long, we put the help
258 # string on a second line, indented to the same column it would
259 # start in if it fit on the first line.
260 # -fFILENAME, --file=FILENAME
261 # read data from FILENAME
262 result = []
Greg Wardeba20e62004-07-31 16:15:44 +0000263 opts = self.option_strings[option]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000264 opt_width = self.help_position - self.current_indent - 2
265 if len(opts) > opt_width:
266 opts = "%*s%s\n" % (self.current_indent, "", opts)
267 indent_first = self.help_position
268 else: # start help on same line as opts
269 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
270 indent_first = 0
271 result.append(opts)
272 if option.help:
Greg Wardeba20e62004-07-31 16:15:44 +0000273 help_text = self.expand_default(option)
274 help_lines = textwrap.wrap(help_text, self.help_width)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000275 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
276 result.extend(["%*s%s\n" % (self.help_position, "", line)
277 for line in help_lines[1:]])
278 elif opts[-1] != "\n":
279 result.append("\n")
280 return "".join(result)
281
Greg Wardeba20e62004-07-31 16:15:44 +0000282 def store_option_strings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000283 self.indent()
284 max_len = 0
285 for opt in parser.option_list:
286 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000287 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000288 max_len = max(max_len, len(strings) + self.current_indent)
289 self.indent()
290 for group in parser.option_groups:
291 for opt in group.option_list:
292 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000293 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000294 max_len = max(max_len, len(strings) + self.current_indent)
295 self.dedent()
296 self.dedent()
297 self.help_position = min(max_len + 2, self.max_help_position)
Greg Wardeba20e62004-07-31 16:15:44 +0000298 self.help_width = self.width - self.help_position
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000299
Greg Wardeba20e62004-07-31 16:15:44 +0000300 def format_option_strings(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000301 """Return a comma-separated list of option strings & metavariables."""
Greg Ward2492fcf2003-04-21 02:40:34 +0000302 if option.takes_value():
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000303 metavar = option.metavar or option.dest.upper()
Greg Wardeba20e62004-07-31 16:15:44 +0000304 short_opts = [self._short_opt_fmt % (sopt, metavar)
305 for sopt in option._short_opts]
306 long_opts = [self._long_opt_fmt % (lopt, metavar)
307 for lopt in option._long_opts]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000308 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000309 short_opts = option._short_opts
310 long_opts = option._long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000311
Greg Ward2492fcf2003-04-21 02:40:34 +0000312 if self.short_first:
313 opts = short_opts + long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000314 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000315 opts = long_opts + short_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000316
Greg Ward2492fcf2003-04-21 02:40:34 +0000317 return ", ".join(opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000318
319class IndentedHelpFormatter (HelpFormatter):
320 """Format help with indented section bodies.
321 """
322
Greg Wardeba20e62004-07-31 16:15:44 +0000323 def __init__(self,
324 indent_increment=2,
325 max_help_position=24,
326 width=None,
327 short_first=1):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000328 HelpFormatter.__init__(
329 self, indent_increment, max_help_position, width, short_first)
330
Greg Wardeba20e62004-07-31 16:15:44 +0000331 def format_usage(self, usage):
332 return _("usage: %s\n") % usage
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000333
Greg Wardeba20e62004-07-31 16:15:44 +0000334 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000335 return "%*s%s:\n" % (self.current_indent, "", heading)
336
337
338class TitledHelpFormatter (HelpFormatter):
339 """Format help with underlined section headers.
340 """
341
Greg Wardeba20e62004-07-31 16:15:44 +0000342 def __init__(self,
343 indent_increment=0,
344 max_help_position=24,
345 width=None,
346 short_first=0):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000347 HelpFormatter.__init__ (
348 self, indent_increment, max_help_position, width, short_first)
349
Greg Wardeba20e62004-07-31 16:15:44 +0000350 def format_usage(self, usage):
351 return "%s %s\n" % (self.format_heading(_("Usage")), usage)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000352
Greg Wardeba20e62004-07-31 16:15:44 +0000353 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000354 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
Greg Ward2492fcf2003-04-21 02:40:34 +0000355
356
Greg Wardeba20e62004-07-31 16:15:44 +0000357_builtin_cvt = { "int" : (int, _("integer")),
358 "long" : (long, _("long integer")),
359 "float" : (float, _("floating-point")),
360 "complex" : (complex, _("complex")) }
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000361
Greg Wardeba20e62004-07-31 16:15:44 +0000362def check_builtin(option, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000363 (cvt, what) = _builtin_cvt[option.type]
364 try:
365 return cvt(value)
366 except ValueError:
367 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000368 _("option %s: invalid %s value: %r") % (opt, what, value))
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000369
370def check_choice(option, opt, value):
371 if value in option.choices:
372 return value
373 else:
374 choices = ", ".join(map(repr, option.choices))
375 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000376 _("option %s: invalid choice: %r (choose from %s)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000377 % (opt, value, choices))
378
379# Not supplying a default is different from a default of None,
380# so we need an explicit "not supplied" value.
Greg Wardeba20e62004-07-31 16:15:44 +0000381NO_DEFAULT = ("NO", "DEFAULT")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000382
383
384class Option:
385 """
386 Instance attributes:
387 _short_opts : [string]
388 _long_opts : [string]
389
390 action : string
391 type : string
392 dest : string
393 default : any
394 nargs : int
395 const : any
396 choices : [string]
397 callback : function
398 callback_args : (any*)
399 callback_kwargs : { string : any }
400 help : string
401 metavar : string
402 """
403
404 # The list of instance attributes that may be set through
405 # keyword args to the constructor.
406 ATTRS = ['action',
407 'type',
408 'dest',
409 'default',
410 'nargs',
411 'const',
412 'choices',
413 'callback',
414 'callback_args',
415 'callback_kwargs',
416 'help',
417 'metavar']
418
419 # The set of actions allowed by option parsers. Explicitly listed
420 # here so the constructor can validate its arguments.
421 ACTIONS = ("store",
422 "store_const",
423 "store_true",
424 "store_false",
425 "append",
426 "count",
427 "callback",
428 "help",
429 "version")
430
431 # The set of actions that involve storing a value somewhere;
432 # also listed just for constructor argument validation. (If
433 # the action is one of these, there must be a destination.)
434 STORE_ACTIONS = ("store",
435 "store_const",
436 "store_true",
437 "store_false",
438 "append",
439 "count")
440
441 # The set of actions for which it makes sense to supply a value
Greg Ward48aa84b2004-10-27 02:20:04 +0000442 # type, ie. which may consume an argument from the command line.
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000443 TYPED_ACTIONS = ("store",
444 "append",
445 "callback")
446
Greg Ward48aa84b2004-10-27 02:20:04 +0000447 # The set of actions which *require* a value type, ie. that
448 # always consume an argument from the command line.
449 ALWAYS_TYPED_ACTIONS = ("store",
450 "append")
451
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000452 # The set of known types for option parsers. Again, listed here for
453 # constructor argument validation.
454 TYPES = ("string", "int", "long", "float", "complex", "choice")
455
456 # Dictionary of argument checking functions, which convert and
457 # validate option arguments according to the option type.
458 #
459 # Signature of checking functions is:
460 # check(option : Option, opt : string, value : string) -> any
461 # where
462 # option is the Option instance calling the checker
463 # opt is the actual option seen on the command-line
464 # (eg. "-a", "--file")
465 # value is the option argument seen on the command-line
466 #
467 # The return value should be in the appropriate Python type
468 # for option.type -- eg. an integer if option.type == "int".
469 #
470 # If no checker is defined for a type, arguments will be
471 # unchecked and remain strings.
472 TYPE_CHECKER = { "int" : check_builtin,
473 "long" : check_builtin,
474 "float" : check_builtin,
Greg Wardeba20e62004-07-31 16:15:44 +0000475 "complex": check_builtin,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000476 "choice" : check_choice,
477 }
478
479
480 # CHECK_METHODS is a list of unbound method objects; they are called
481 # by the constructor, in order, after all attributes are
482 # initialized. The list is created and filled in later, after all
483 # the methods are actually defined. (I just put it here because I
484 # like to define and document all class attributes in the same
485 # place.) Subclasses that add another _check_*() method should
486 # define their own CHECK_METHODS list that adds their check method
487 # to those from this class.
488 CHECK_METHODS = None
489
490
491 # -- Constructor/initialization methods ----------------------------
492
Greg Wardeba20e62004-07-31 16:15:44 +0000493 def __init__(self, *opts, **attrs):
Greg Ward2492fcf2003-04-21 02:40:34 +0000494 # Set _short_opts, _long_opts attrs from 'opts' tuple.
495 # Have to be set now, in case no option strings are supplied.
496 self._short_opts = []
497 self._long_opts = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000498 opts = self._check_opt_strings(opts)
499 self._set_opt_strings(opts)
500
501 # Set all other attrs (action, type, etc.) from 'attrs' dict
502 self._set_attrs(attrs)
503
504 # Check all the attributes we just set. There are lots of
505 # complicated interdependencies, but luckily they can be farmed
506 # out to the _check_*() methods listed in CHECK_METHODS -- which
507 # could be handy for subclasses! The one thing these all share
508 # is that they raise OptionError if they discover a problem.
509 for checker in self.CHECK_METHODS:
510 checker(self)
511
Greg Wardeba20e62004-07-31 16:15:44 +0000512 def _check_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000513 # Filter out None because early versions of Optik had exactly
514 # one short option and one long option, either of which
515 # could be None.
516 opts = filter(None, opts)
517 if not opts:
Greg Ward2492fcf2003-04-21 02:40:34 +0000518 raise TypeError("at least one option string must be supplied")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000519 return opts
520
Greg Wardeba20e62004-07-31 16:15:44 +0000521 def _set_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000522 for opt in opts:
523 if len(opt) < 2:
524 raise OptionError(
525 "invalid option string %r: "
526 "must be at least two characters long" % opt, self)
527 elif len(opt) == 2:
528 if not (opt[0] == "-" and opt[1] != "-"):
529 raise OptionError(
530 "invalid short option string %r: "
531 "must be of the form -x, (x any non-dash char)" % opt,
532 self)
533 self._short_opts.append(opt)
534 else:
535 if not (opt[0:2] == "--" and opt[2] != "-"):
536 raise OptionError(
537 "invalid long option string %r: "
538 "must start with --, followed by non-dash" % opt,
539 self)
540 self._long_opts.append(opt)
541
Greg Wardeba20e62004-07-31 16:15:44 +0000542 def _set_attrs(self, attrs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000543 for attr in self.ATTRS:
544 if attrs.has_key(attr):
545 setattr(self, attr, attrs[attr])
546 del attrs[attr]
547 else:
548 if attr == 'default':
549 setattr(self, attr, NO_DEFAULT)
550 else:
551 setattr(self, attr, None)
552 if attrs:
553 raise OptionError(
554 "invalid keyword arguments: %s" % ", ".join(attrs.keys()),
555 self)
556
557
558 # -- Constructor validation methods --------------------------------
559
Greg Wardeba20e62004-07-31 16:15:44 +0000560 def _check_action(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000561 if self.action is None:
562 self.action = "store"
563 elif self.action not in self.ACTIONS:
564 raise OptionError("invalid action: %r" % self.action, self)
565
Greg Wardeba20e62004-07-31 16:15:44 +0000566 def _check_type(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000567 if self.type is None:
Greg Ward48aa84b2004-10-27 02:20:04 +0000568 if self.action in self.ALWAYS_TYPED_ACTIONS:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000569 if self.choices is not None:
570 # The "choices" attribute implies "choice" type.
571 self.type = "choice"
572 else:
573 # No type given? "string" is the most sensible default.
574 self.type = "string"
575 else:
Greg Wardeba20e62004-07-31 16:15:44 +0000576 # Allow type objects as an alternative to their names.
577 if type(self.type) is type:
578 self.type = self.type.__name__
579 if self.type == "str":
580 self.type = "string"
581
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000582 if self.type not in self.TYPES:
583 raise OptionError("invalid option type: %r" % self.type, self)
584 if self.action not in self.TYPED_ACTIONS:
585 raise OptionError(
586 "must not supply a type for action %r" % self.action, self)
587
588 def _check_choice(self):
589 if self.type == "choice":
590 if self.choices is None:
591 raise OptionError(
592 "must supply a list of choices for type 'choice'", self)
593 elif type(self.choices) not in (types.TupleType, types.ListType):
594 raise OptionError(
595 "choices must be a list of strings ('%s' supplied)"
596 % str(type(self.choices)).split("'")[1], self)
597 elif self.choices is not None:
598 raise OptionError(
599 "must not supply choices for type %r" % self.type, self)
600
Greg Wardeba20e62004-07-31 16:15:44 +0000601 def _check_dest(self):
602 # No destination given, and we need one for this action. The
603 # self.type check is for callbacks that take a value.
604 takes_value = (self.action in self.STORE_ACTIONS or
605 self.type is not None)
606 if self.dest is None and takes_value:
607
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000608 # Glean a destination from the first long option string,
609 # or from the first short option string if no long options.
610 if self._long_opts:
611 # eg. "--foo-bar" -> "foo_bar"
612 self.dest = self._long_opts[0][2:].replace('-', '_')
613 else:
614 self.dest = self._short_opts[0][1]
615
Greg Wardeba20e62004-07-31 16:15:44 +0000616 def _check_const(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000617 if self.action != "store_const" and self.const is not None:
618 raise OptionError(
619 "'const' must not be supplied for action %r" % self.action,
620 self)
621
Greg Wardeba20e62004-07-31 16:15:44 +0000622 def _check_nargs(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000623 if self.action in self.TYPED_ACTIONS:
624 if self.nargs is None:
625 self.nargs = 1
626 elif self.nargs is not None:
627 raise OptionError(
628 "'nargs' must not be supplied for action %r" % self.action,
629 self)
630
Greg Wardeba20e62004-07-31 16:15:44 +0000631 def _check_callback(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000632 if self.action == "callback":
633 if not callable(self.callback):
634 raise OptionError(
635 "callback not callable: %r" % self.callback, self)
636 if (self.callback_args is not None and
637 type(self.callback_args) is not types.TupleType):
638 raise OptionError(
639 "callback_args, if supplied, must be a tuple: not %r"
640 % self.callback_args, self)
641 if (self.callback_kwargs is not None and
642 type(self.callback_kwargs) is not types.DictType):
643 raise OptionError(
644 "callback_kwargs, if supplied, must be a dict: not %r"
645 % self.callback_kwargs, self)
646 else:
647 if self.callback is not None:
648 raise OptionError(
649 "callback supplied (%r) for non-callback option"
650 % self.callback, self)
651 if self.callback_args is not None:
652 raise OptionError(
653 "callback_args supplied for non-callback option", self)
654 if self.callback_kwargs is not None:
655 raise OptionError(
656 "callback_kwargs supplied for non-callback option", self)
657
658
659 CHECK_METHODS = [_check_action,
660 _check_type,
661 _check_choice,
662 _check_dest,
663 _check_const,
664 _check_nargs,
665 _check_callback]
666
667
668 # -- Miscellaneous methods -----------------------------------------
669
Greg Wardeba20e62004-07-31 16:15:44 +0000670 def __str__(self):
Greg Ward2492fcf2003-04-21 02:40:34 +0000671 return "/".join(self._short_opts + self._long_opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000672
Greg Wardeba20e62004-07-31 16:15:44 +0000673 __repr__ = _repr
674
675 def takes_value(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000676 return self.type is not None
677
Greg Wardeba20e62004-07-31 16:15:44 +0000678 def get_opt_string(self):
679 if self._long_opts:
680 return self._long_opts[0]
681 else:
682 return self._short_opts[0]
683
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000684
685 # -- Processing methods --------------------------------------------
686
Greg Wardeba20e62004-07-31 16:15:44 +0000687 def check_value(self, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000688 checker = self.TYPE_CHECKER.get(self.type)
689 if checker is None:
690 return value
691 else:
692 return checker(self, opt, value)
693
Greg Wardeba20e62004-07-31 16:15:44 +0000694 def convert_value(self, opt, value):
695 if value is not None:
696 if self.nargs == 1:
697 return self.check_value(opt, value)
698 else:
699 return tuple([self.check_value(opt, v) for v in value])
700
701 def process(self, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000702
703 # First, convert the value(s) to the right type. Howl if any
704 # value(s) are bogus.
Greg Wardeba20e62004-07-31 16:15:44 +0000705 value = self.convert_value(opt, value)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000706
707 # And then take whatever action is expected of us.
708 # This is a separate method to make life easier for
709 # subclasses to add new actions.
710 return self.take_action(
711 self.action, self.dest, opt, value, values, parser)
712
Greg Wardeba20e62004-07-31 16:15:44 +0000713 def take_action(self, action, dest, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000714 if action == "store":
715 setattr(values, dest, value)
716 elif action == "store_const":
717 setattr(values, dest, self.const)
718 elif action == "store_true":
Greg Ward2492fcf2003-04-21 02:40:34 +0000719 setattr(values, dest, True)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000720 elif action == "store_false":
Greg Ward2492fcf2003-04-21 02:40:34 +0000721 setattr(values, dest, False)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000722 elif action == "append":
723 values.ensure_value(dest, []).append(value)
724 elif action == "count":
725 setattr(values, dest, values.ensure_value(dest, 0) + 1)
726 elif action == "callback":
727 args = self.callback_args or ()
728 kwargs = self.callback_kwargs or {}
729 self.callback(self, opt, value, parser, *args, **kwargs)
730 elif action == "help":
731 parser.print_help()
Greg Ward48aa84b2004-10-27 02:20:04 +0000732 parser.exit()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000733 elif action == "version":
734 parser.print_version()
Greg Ward48aa84b2004-10-27 02:20:04 +0000735 parser.exit()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000736 else:
737 raise RuntimeError, "unknown action %r" % self.action
738
739 return 1
740
741# class Option
Greg Ward2492fcf2003-04-21 02:40:34 +0000742
743
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000744SUPPRESS_HELP = "SUPPRESS"+"HELP"
745SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
746
Greg Wardeba20e62004-07-31 16:15:44 +0000747# For compatibility with Python 2.2
748try:
749 True, False
750except NameError:
751 (True, False) = (1, 0)
752try:
753 basestring
754except NameError:
755 basestring = (str, unicode)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000756
757
758class Values:
759
Greg Wardeba20e62004-07-31 16:15:44 +0000760 def __init__(self, defaults=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000761 if defaults:
762 for (attr, val) in defaults.items():
763 setattr(self, attr, val)
764
Greg Wardeba20e62004-07-31 16:15:44 +0000765 def __str__(self):
766 return str(self.__dict__)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000767
Greg Wardeba20e62004-07-31 16:15:44 +0000768 __repr__ = _repr
769
770 def __eq__(self, other):
771 if isinstance(other, Values):
772 return self.__dict__ == other.__dict__
773 elif isinstance(other, dict):
774 return self.__dict__ == other
775 else:
Neal Norwitz13389462004-10-17 16:24:25 +0000776 return False
Greg Wardeba20e62004-07-31 16:15:44 +0000777
778 def __ne__(self, other):
779 return not (self == other)
780
781 def _update_careful(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000782 """
783 Update the option values from an arbitrary dictionary, but only
784 use keys from dict that already have a corresponding attribute
785 in self. Any keys in dict without a corresponding attribute
786 are silently ignored.
787 """
788 for attr in dir(self):
789 if dict.has_key(attr):
790 dval = dict[attr]
791 if dval is not None:
792 setattr(self, attr, dval)
793
Greg Wardeba20e62004-07-31 16:15:44 +0000794 def _update_loose(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000795 """
796 Update the option values from an arbitrary dictionary,
797 using all keys from the dictionary regardless of whether
798 they have a corresponding attribute in self or not.
799 """
800 self.__dict__.update(dict)
801
Greg Wardeba20e62004-07-31 16:15:44 +0000802 def _update(self, dict, mode):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000803 if mode == "careful":
804 self._update_careful(dict)
805 elif mode == "loose":
806 self._update_loose(dict)
807 else:
808 raise ValueError, "invalid update mode: %r" % mode
809
Greg Wardeba20e62004-07-31 16:15:44 +0000810 def read_module(self, modname, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000811 __import__(modname)
812 mod = sys.modules[modname]
813 self._update(vars(mod), mode)
814
Greg Wardeba20e62004-07-31 16:15:44 +0000815 def read_file(self, filename, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000816 vars = {}
817 execfile(filename, vars)
818 self._update(vars, mode)
819
Greg Wardeba20e62004-07-31 16:15:44 +0000820 def ensure_value(self, attr, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000821 if not hasattr(self, attr) or getattr(self, attr) is None:
822 setattr(self, attr, value)
823 return getattr(self, attr)
824
825
826class OptionContainer:
827
828 """
829 Abstract base class.
830
831 Class attributes:
832 standard_option_list : [Option]
833 list of standard options that will be accepted by all instances
834 of this parser class (intended to be overridden by subclasses).
835
836 Instance attributes:
837 option_list : [Option]
838 the list of Option objects contained by this OptionContainer
839 _short_opt : { string : Option }
840 dictionary mapping short option strings, eg. "-f" or "-X",
841 to the Option instances that implement them. If an Option
842 has multiple short option strings, it will appears in this
843 dictionary multiple times. [1]
844 _long_opt : { string : Option }
845 dictionary mapping long option strings, eg. "--file" or
846 "--exclude", to the Option instances that implement them.
847 Again, a given Option can occur multiple times in this
848 dictionary. [1]
849 defaults : { string : any }
850 dictionary mapping option destination names to default
851 values for each destination [1]
852
853 [1] These mappings are common to (shared by) all components of the
854 controlling OptionParser, where they are initially created.
855
856 """
857
Greg Wardeba20e62004-07-31 16:15:44 +0000858 def __init__(self, option_class, conflict_handler, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000859 # Initialize the option list and related data structures.
860 # This method must be provided by subclasses, and it must
861 # initialize at least the following instance attributes:
862 # option_list, _short_opt, _long_opt, defaults.
863 self._create_option_list()
864
865 self.option_class = option_class
866 self.set_conflict_handler(conflict_handler)
867 self.set_description(description)
868
Greg Wardeba20e62004-07-31 16:15:44 +0000869 def _create_option_mappings(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000870 # For use by OptionParser constructor -- create the master
871 # option mappings used by this OptionParser and all
872 # OptionGroups that it owns.
873 self._short_opt = {} # single letter -> Option instance
874 self._long_opt = {} # long option -> Option instance
875 self.defaults = {} # maps option dest -> default value
876
877
Greg Wardeba20e62004-07-31 16:15:44 +0000878 def _share_option_mappings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000879 # For use by OptionGroup constructor -- use shared option
880 # mappings from the OptionParser that owns this OptionGroup.
881 self._short_opt = parser._short_opt
882 self._long_opt = parser._long_opt
883 self.defaults = parser.defaults
884
Greg Wardeba20e62004-07-31 16:15:44 +0000885 def set_conflict_handler(self, handler):
Greg Ward48aa84b2004-10-27 02:20:04 +0000886 if handler not in ("error", "resolve"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000887 raise ValueError, "invalid conflict_resolution value %r" % handler
888 self.conflict_handler = handler
889
Greg Wardeba20e62004-07-31 16:15:44 +0000890 def set_description(self, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000891 self.description = description
892
Greg Wardeba20e62004-07-31 16:15:44 +0000893 def get_description(self):
894 return self.description
895
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000896
897 # -- Option-adding methods -----------------------------------------
898
Greg Wardeba20e62004-07-31 16:15:44 +0000899 def _check_conflict(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000900 conflict_opts = []
901 for opt in option._short_opts:
902 if self._short_opt.has_key(opt):
903 conflict_opts.append((opt, self._short_opt[opt]))
904 for opt in option._long_opts:
905 if self._long_opt.has_key(opt):
906 conflict_opts.append((opt, self._long_opt[opt]))
907
908 if conflict_opts:
909 handler = self.conflict_handler
Greg Ward48aa84b2004-10-27 02:20:04 +0000910 if handler == "error":
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000911 raise OptionConflictError(
912 "conflicting option string(s): %s"
913 % ", ".join([co[0] for co in conflict_opts]),
914 option)
Greg Ward48aa84b2004-10-27 02:20:04 +0000915 elif handler == "resolve":
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000916 for (opt, c_option) in conflict_opts:
917 if opt.startswith("--"):
918 c_option._long_opts.remove(opt)
919 del self._long_opt[opt]
920 else:
921 c_option._short_opts.remove(opt)
922 del self._short_opt[opt]
923 if not (c_option._short_opts or c_option._long_opts):
924 c_option.container.option_list.remove(c_option)
925
Greg Wardeba20e62004-07-31 16:15:44 +0000926 def add_option(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000927 """add_option(Option)
928 add_option(opt_str, ..., kwarg=val, ...)
929 """
930 if type(args[0]) is types.StringType:
931 option = self.option_class(*args, **kwargs)
932 elif len(args) == 1 and not kwargs:
933 option = args[0]
934 if not isinstance(option, Option):
935 raise TypeError, "not an Option instance: %r" % option
936 else:
937 raise TypeError, "invalid arguments"
938
939 self._check_conflict(option)
940
941 self.option_list.append(option)
942 option.container = self
943 for opt in option._short_opts:
944 self._short_opt[opt] = option
945 for opt in option._long_opts:
946 self._long_opt[opt] = option
947
948 if option.dest is not None: # option has a dest, we need a default
949 if option.default is not NO_DEFAULT:
950 self.defaults[option.dest] = option.default
951 elif not self.defaults.has_key(option.dest):
952 self.defaults[option.dest] = None
953
954 return option
955
Greg Wardeba20e62004-07-31 16:15:44 +0000956 def add_options(self, option_list):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000957 for option in option_list:
958 self.add_option(option)
959
960 # -- Option query/removal methods ----------------------------------
961
Greg Wardeba20e62004-07-31 16:15:44 +0000962 def get_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000963 return (self._short_opt.get(opt_str) or
964 self._long_opt.get(opt_str))
965
Greg Wardeba20e62004-07-31 16:15:44 +0000966 def has_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000967 return (self._short_opt.has_key(opt_str) or
968 self._long_opt.has_key(opt_str))
969
Greg Wardeba20e62004-07-31 16:15:44 +0000970 def remove_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000971 option = self._short_opt.get(opt_str)
972 if option is None:
973 option = self._long_opt.get(opt_str)
974 if option is None:
975 raise ValueError("no such option %r" % opt_str)
976
977 for opt in option._short_opts:
978 del self._short_opt[opt]
979 for opt in option._long_opts:
980 del self._long_opt[opt]
981 option.container.option_list.remove(option)
982
983
984 # -- Help-formatting methods ---------------------------------------
985
Greg Wardeba20e62004-07-31 16:15:44 +0000986 def format_option_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000987 if not self.option_list:
988 return ""
989 result = []
990 for option in self.option_list:
991 if not option.help is SUPPRESS_HELP:
992 result.append(formatter.format_option(option))
993 return "".join(result)
994
Greg Wardeba20e62004-07-31 16:15:44 +0000995 def format_description(self, formatter):
996 return formatter.format_description(self.get_description())
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000997
Greg Wardeba20e62004-07-31 16:15:44 +0000998 def format_help(self, formatter):
999 result = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001000 if self.description:
Greg Wardeba20e62004-07-31 16:15:44 +00001001 result.append(self.format_description(formatter))
1002 if self.option_list:
1003 result.append(self.format_option_help(formatter))
1004 return "\n".join(result)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001005
1006
1007class OptionGroup (OptionContainer):
1008
Greg Wardeba20e62004-07-31 16:15:44 +00001009 def __init__(self, parser, title, description=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001010 self.parser = parser
1011 OptionContainer.__init__(
1012 self, parser.option_class, parser.conflict_handler, description)
1013 self.title = title
1014
Greg Wardeba20e62004-07-31 16:15:44 +00001015 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001016 self.option_list = []
1017 self._share_option_mappings(self.parser)
1018
Greg Wardeba20e62004-07-31 16:15:44 +00001019 def set_title(self, title):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001020 self.title = title
1021
1022 # -- Help-formatting methods ---------------------------------------
1023
Greg Wardeba20e62004-07-31 16:15:44 +00001024 def format_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001025 result = formatter.format_heading(self.title)
1026 formatter.indent()
1027 result += OptionContainer.format_help(self, formatter)
1028 formatter.dedent()
1029 return result
1030
1031
1032class OptionParser (OptionContainer):
1033
1034 """
1035 Class attributes:
1036 standard_option_list : [Option]
1037 list of standard options that will be accepted by all instances
1038 of this parser class (intended to be overridden by subclasses).
1039
1040 Instance attributes:
1041 usage : string
1042 a usage string for your program. Before it is displayed
1043 to the user, "%prog" will be expanded to the name of
Greg Ward2492fcf2003-04-21 02:40:34 +00001044 your program (self.prog or os.path.basename(sys.argv[0])).
1045 prog : string
1046 the name of the current program (to override
1047 os.path.basename(sys.argv[0])).
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001048
Greg Wardeba20e62004-07-31 16:15:44 +00001049 option_groups : [OptionGroup]
1050 list of option groups in this parser (option groups are
1051 irrelevant for parsing the command-line, but very useful
1052 for generating help)
1053
1054 allow_interspersed_args : bool = true
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001055 if true, positional arguments may be interspersed with options.
1056 Assuming -a and -b each take a single argument, the command-line
1057 -ablah foo bar -bboo baz
1058 will be interpreted the same as
1059 -ablah -bboo -- foo bar baz
1060 If this flag were false, that command line would be interpreted as
1061 -ablah -- foo bar -bboo baz
1062 -- ie. we stop processing options as soon as we see the first
1063 non-option argument. (This is the tradition followed by
1064 Python's getopt module, Perl's Getopt::Std, and other argument-
1065 parsing libraries, but it is generally annoying to users.)
1066
Greg Wardeba20e62004-07-31 16:15:44 +00001067 process_default_values : bool = true
1068 if true, option default values are processed similarly to option
1069 values from the command line: that is, they are passed to the
1070 type-checking function for the option's type (as long as the
1071 default value is a string). (This really only matters if you
1072 have defined custom types; see SF bug #955889.) Set it to false
1073 to restore the behaviour of Optik 1.4.1 and earlier.
1074
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001075 rargs : [string]
1076 the argument list currently being parsed. Only set when
1077 parse_args() is active, and continually trimmed down as
1078 we consume arguments. Mainly there for the benefit of
1079 callback options.
1080 largs : [string]
1081 the list of leftover arguments that we have skipped while
1082 parsing options. If allow_interspersed_args is false, this
1083 list is always empty.
1084 values : Values
1085 the set of option values currently being accumulated. Only
1086 set when parse_args() is active. Also mainly for callbacks.
1087
1088 Because of the 'rargs', 'largs', and 'values' attributes,
1089 OptionParser is not thread-safe. If, for some perverse reason, you
1090 need to parse command-line arguments simultaneously in different
1091 threads, use different OptionParser instances.
1092
1093 """
1094
1095 standard_option_list = []
1096
Greg Wardeba20e62004-07-31 16:15:44 +00001097 def __init__(self,
1098 usage=None,
1099 option_list=None,
1100 option_class=Option,
1101 version=None,
1102 conflict_handler="error",
1103 description=None,
1104 formatter=None,
1105 add_help_option=True,
1106 prog=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001107 OptionContainer.__init__(
1108 self, option_class, conflict_handler, description)
1109 self.set_usage(usage)
Greg Ward2492fcf2003-04-21 02:40:34 +00001110 self.prog = prog
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001111 self.version = version
Greg Wardeba20e62004-07-31 16:15:44 +00001112 self.allow_interspersed_args = True
1113 self.process_default_values = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001114 if formatter is None:
1115 formatter = IndentedHelpFormatter()
1116 self.formatter = formatter
Greg Wardeba20e62004-07-31 16:15:44 +00001117 self.formatter.set_parser(self)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001118
1119 # Populate the option list; initial sources are the
1120 # standard_option_list class attribute, the 'option_list'
Greg Wardeba20e62004-07-31 16:15:44 +00001121 # argument, and (if applicable) the _add_version_option() and
1122 # _add_help_option() methods.
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001123 self._populate_option_list(option_list,
1124 add_help=add_help_option)
1125
1126 self._init_parsing_state()
1127
1128 # -- Private methods -----------------------------------------------
1129 # (used by our or OptionContainer's constructor)
1130
Greg Wardeba20e62004-07-31 16:15:44 +00001131 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001132 self.option_list = []
1133 self.option_groups = []
1134 self._create_option_mappings()
1135
Greg Wardeba20e62004-07-31 16:15:44 +00001136 def _add_help_option(self):
1137 self.add_option("-h", "--help",
1138 action="help",
1139 help=_("show this help message and exit"))
1140
1141 def _add_version_option(self):
1142 self.add_option("--version",
1143 action="version",
1144 help=_("show program's version number and exit"))
1145
1146 def _populate_option_list(self, option_list, add_help=True):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001147 if self.standard_option_list:
1148 self.add_options(self.standard_option_list)
1149 if option_list:
1150 self.add_options(option_list)
1151 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001152 self._add_version_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001153 if add_help:
Greg Wardeba20e62004-07-31 16:15:44 +00001154 self._add_help_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001155
Greg Wardeba20e62004-07-31 16:15:44 +00001156 def _init_parsing_state(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001157 # These are set in parse_args() for the convenience of callbacks.
1158 self.rargs = None
1159 self.largs = None
1160 self.values = None
1161
1162
1163 # -- Simple modifier methods ---------------------------------------
1164
Greg Wardeba20e62004-07-31 16:15:44 +00001165 def set_usage(self, usage):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001166 if usage is None:
Greg Wardeba20e62004-07-31 16:15:44 +00001167 self.usage = _("%prog [options]")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001168 elif usage is SUPPRESS_USAGE:
1169 self.usage = None
Greg Wardeba20e62004-07-31 16:15:44 +00001170 # For backwards compatibility with Optik 1.3 and earlier.
1171 elif usage.startswith("usage:" + " "):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001172 self.usage = usage[7:]
1173 else:
1174 self.usage = usage
1175
Greg Wardeba20e62004-07-31 16:15:44 +00001176 def enable_interspersed_args(self):
1177 self.allow_interspersed_args = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001178
Greg Wardeba20e62004-07-31 16:15:44 +00001179 def disable_interspersed_args(self):
1180 self.allow_interspersed_args = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001181
Greg Wardeba20e62004-07-31 16:15:44 +00001182 def set_process_default_values(self, process):
1183 self.process_default_values = process
1184
1185 def set_default(self, dest, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001186 self.defaults[dest] = value
1187
Greg Wardeba20e62004-07-31 16:15:44 +00001188 def set_defaults(self, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001189 self.defaults.update(kwargs)
1190
Greg Wardeba20e62004-07-31 16:15:44 +00001191 def _get_all_options(self):
1192 options = self.option_list[:]
1193 for group in self.option_groups:
1194 options.extend(group.option_list)
1195 return options
1196
1197 def get_default_values(self):
1198 if not self.process_default_values:
1199 # Old, pre-Optik 1.5 behaviour.
1200 return Values(self.defaults)
1201
1202 defaults = self.defaults.copy()
1203 for option in self._get_all_options():
1204 default = defaults.get(option.dest)
1205 if isinstance(default, basestring):
1206 opt_str = option.get_opt_string()
1207 defaults[option.dest] = option.check_value(opt_str, default)
1208
1209 return Values(defaults)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001210
1211
1212 # -- OptionGroup methods -------------------------------------------
1213
Greg Wardeba20e62004-07-31 16:15:44 +00001214 def add_option_group(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001215 # XXX lots of overlap with OptionContainer.add_option()
1216 if type(args[0]) is types.StringType:
1217 group = OptionGroup(self, *args, **kwargs)
1218 elif len(args) == 1 and not kwargs:
1219 group = args[0]
1220 if not isinstance(group, OptionGroup):
1221 raise TypeError, "not an OptionGroup instance: %r" % group
1222 if group.parser is not self:
1223 raise ValueError, "invalid OptionGroup (wrong parser)"
1224 else:
1225 raise TypeError, "invalid arguments"
1226
1227 self.option_groups.append(group)
1228 return group
1229
Greg Wardeba20e62004-07-31 16:15:44 +00001230 def get_option_group(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001231 option = (self._short_opt.get(opt_str) or
1232 self._long_opt.get(opt_str))
1233 if option and option.container is not self:
1234 return option.container
1235 return None
1236
1237
1238 # -- Option-parsing methods ----------------------------------------
1239
Greg Wardeba20e62004-07-31 16:15:44 +00001240 def _get_args(self, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001241 if args is None:
1242 return sys.argv[1:]
1243 else:
1244 return args[:] # don't modify caller's list
1245
Greg Wardeba20e62004-07-31 16:15:44 +00001246 def parse_args(self, args=None, values=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001247 """
1248 parse_args(args : [string] = sys.argv[1:],
1249 values : Values = None)
1250 -> (values : Values, args : [string])
1251
1252 Parse the command-line options found in 'args' (default:
1253 sys.argv[1:]). Any errors result in a call to 'error()', which
1254 by default prints the usage message to stderr and calls
1255 sys.exit() with an error message. On success returns a pair
1256 (values, args) where 'values' is an Values instance (with all
1257 your option values) and 'args' is the list of arguments left
1258 over after parsing options.
1259 """
1260 rargs = self._get_args(args)
1261 if values is None:
1262 values = self.get_default_values()
1263
1264 # Store the halves of the argument list as attributes for the
1265 # convenience of callbacks:
1266 # rargs
1267 # the rest of the command-line (the "r" stands for
1268 # "remaining" or "right-hand")
1269 # largs
1270 # the leftover arguments -- ie. what's left after removing
1271 # options and their arguments (the "l" stands for "leftover"
1272 # or "left-hand")
1273 self.rargs = rargs
1274 self.largs = largs = []
1275 self.values = values
1276
1277 try:
1278 stop = self._process_args(largs, rargs, values)
1279 except (BadOptionError, OptionValueError), err:
1280 self.error(err.msg)
1281
1282 args = largs + rargs
1283 return self.check_values(values, args)
1284
Greg Wardeba20e62004-07-31 16:15:44 +00001285 def check_values(self, values, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001286 """
1287 check_values(values : Values, args : [string])
1288 -> (values : Values, args : [string])
1289
1290 Check that the supplied option values and leftover arguments are
1291 valid. Returns the option values and leftover arguments
1292 (possibly adjusted, possibly completely new -- whatever you
1293 like). Default implementation just returns the passed-in
1294 values; subclasses may override as desired.
1295 """
1296 return (values, args)
1297
Greg Wardeba20e62004-07-31 16:15:44 +00001298 def _process_args(self, largs, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001299 """_process_args(largs : [string],
1300 rargs : [string],
1301 values : Values)
1302
1303 Process command-line arguments and populate 'values', consuming
1304 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1305 false, stop at the first non-option argument. If true, accumulate any
1306 interspersed non-option arguments in 'largs'.
1307 """
1308 while rargs:
1309 arg = rargs[0]
1310 # We handle bare "--" explicitly, and bare "-" is handled by the
1311 # standard arg handler since the short arg case ensures that the
1312 # len of the opt string is greater than 1.
1313 if arg == "--":
1314 del rargs[0]
1315 return
1316 elif arg[0:2] == "--":
1317 # process a single long option (possibly with value(s))
1318 self._process_long_opt(rargs, values)
1319 elif arg[:1] == "-" and len(arg) > 1:
1320 # process a cluster of short options (possibly with
1321 # value(s) for the last one only)
1322 self._process_short_opts(rargs, values)
1323 elif self.allow_interspersed_args:
1324 largs.append(arg)
1325 del rargs[0]
1326 else:
1327 return # stop now, leave this arg in rargs
1328
1329 # Say this is the original argument list:
1330 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1331 # ^
1332 # (we are about to process arg(i)).
1333 #
1334 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1335 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1336 # been removed from largs).
1337 #
1338 # The while loop will usually consume 1 or more arguments per pass.
1339 # If it consumes 1 (eg. arg is an option that takes no arguments),
1340 # then after _process_arg() is done the situation is:
1341 #
1342 # largs = subset of [arg0, ..., arg(i)]
1343 # rargs = [arg(i+1), ..., arg(N-1)]
1344 #
1345 # If allow_interspersed_args is false, largs will always be
1346 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1347 # not a very interesting subset!
1348
Greg Wardeba20e62004-07-31 16:15:44 +00001349 def _match_long_opt(self, opt):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001350 """_match_long_opt(opt : string) -> string
1351
1352 Determine which long option string 'opt' matches, ie. which one
1353 it is an unambiguous abbrevation for. Raises BadOptionError if
1354 'opt' doesn't unambiguously match any long option string.
1355 """
1356 return _match_abbrev(opt, self._long_opt)
1357
Greg Wardeba20e62004-07-31 16:15:44 +00001358 def _process_long_opt(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001359 arg = rargs.pop(0)
1360
1361 # Value explicitly attached to arg? Pretend it's the next
1362 # argument.
1363 if "=" in arg:
1364 (opt, next_arg) = arg.split("=", 1)
1365 rargs.insert(0, next_arg)
Greg Wardeba20e62004-07-31 16:15:44 +00001366 had_explicit_value = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001367 else:
1368 opt = arg
Greg Wardeba20e62004-07-31 16:15:44 +00001369 had_explicit_value = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001370
1371 opt = self._match_long_opt(opt)
1372 option = self._long_opt[opt]
1373 if option.takes_value():
1374 nargs = option.nargs
1375 if len(rargs) < nargs:
1376 if nargs == 1:
Greg Wardeba20e62004-07-31 16:15:44 +00001377 self.error(_("%s option requires an argument") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001378 else:
Greg Wardeba20e62004-07-31 16:15:44 +00001379 self.error(_("%s option requires %d arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001380 % (opt, nargs))
1381 elif nargs == 1:
1382 value = rargs.pop(0)
1383 else:
1384 value = tuple(rargs[0:nargs])
1385 del rargs[0:nargs]
1386
1387 elif had_explicit_value:
Greg Wardeba20e62004-07-31 16:15:44 +00001388 self.error(_("%s option does not take a value") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001389
1390 else:
1391 value = None
1392
1393 option.process(opt, value, values, self)
1394
Greg Wardeba20e62004-07-31 16:15:44 +00001395 def _process_short_opts(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001396 arg = rargs.pop(0)
Greg Wardeba20e62004-07-31 16:15:44 +00001397 stop = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001398 i = 1
1399 for ch in arg[1:]:
1400 opt = "-" + ch
1401 option = self._short_opt.get(opt)
1402 i += 1 # we have consumed a character
1403
1404 if not option:
Greg Wardeba20e62004-07-31 16:15:44 +00001405 self.error(_("no such option: %s") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001406 if option.takes_value():
1407 # Any characters left in arg? Pretend they're the
1408 # next arg, and stop consuming characters of arg.
1409 if i < len(arg):
1410 rargs.insert(0, arg[i:])
Greg Wardeba20e62004-07-31 16:15:44 +00001411 stop = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001412
1413 nargs = option.nargs
1414 if len(rargs) < nargs:
1415 if nargs == 1:
Greg Wardeba20e62004-07-31 16:15:44 +00001416 self.error(_("%s option requires an argument") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001417 else:
Greg Wardeba20e62004-07-31 16:15:44 +00001418 self.error(_("%s option requires %d arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001419 % (opt, nargs))
1420 elif nargs == 1:
1421 value = rargs.pop(0)
1422 else:
1423 value = tuple(rargs[0:nargs])
1424 del rargs[0:nargs]
1425
1426 else: # option doesn't take a value
1427 value = None
1428
1429 option.process(opt, value, values, self)
1430
1431 if stop:
1432 break
1433
1434
1435 # -- Feedback methods ----------------------------------------------
1436
Greg Wardeba20e62004-07-31 16:15:44 +00001437 def get_prog_name(self):
1438 if self.prog is None:
1439 return os.path.basename(sys.argv[0])
1440 else:
1441 return self.prog
1442
1443 def expand_prog_name(self, s):
1444 return s.replace("%prog", self.get_prog_name())
1445
1446 def get_description(self):
1447 return self.expand_prog_name(self.description)
1448
Greg Ward48aa84b2004-10-27 02:20:04 +00001449 def exit(self, status=0, msg=None):
1450 if msg:
1451 sys.stderr.write(msg)
1452 sys.exit(status)
1453
Greg Wardeba20e62004-07-31 16:15:44 +00001454 def error(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001455 """error(msg : string)
1456
1457 Print a usage message incorporating 'msg' to stderr and exit.
1458 If you override this in a subclass, it should not return -- it
1459 should either exit or raise an exception.
1460 """
1461 self.print_usage(sys.stderr)
Greg Ward48aa84b2004-10-27 02:20:04 +00001462 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001463
Greg Wardeba20e62004-07-31 16:15:44 +00001464 def get_usage(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001465 if self.usage:
1466 return self.formatter.format_usage(
Greg Wardeba20e62004-07-31 16:15:44 +00001467 self.expand_prog_name(self.usage))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001468 else:
1469 return ""
1470
Greg Wardeba20e62004-07-31 16:15:44 +00001471 def print_usage(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001472 """print_usage(file : file = stdout)
1473
1474 Print the usage message for the current program (self.usage) to
1475 'file' (default stdout). Any occurence of the string "%prog" in
1476 self.usage is replaced with the name of the current program
1477 (basename of sys.argv[0]). Does nothing if self.usage is empty
1478 or not defined.
1479 """
1480 if self.usage:
1481 print >>file, self.get_usage()
1482
Greg Wardeba20e62004-07-31 16:15:44 +00001483 def get_version(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001484 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001485 return self.expand_prog_name(self.version)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001486 else:
1487 return ""
1488
Greg Wardeba20e62004-07-31 16:15:44 +00001489 def print_version(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001490 """print_version(file : file = stdout)
1491
1492 Print the version message for this program (self.version) to
1493 'file' (default stdout). As with print_usage(), any occurence
1494 of "%prog" in self.version is replaced by the current program's
1495 name. Does nothing if self.version is empty or undefined.
1496 """
1497 if self.version:
1498 print >>file, self.get_version()
1499
Greg Wardeba20e62004-07-31 16:15:44 +00001500 def format_option_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001501 if formatter is None:
1502 formatter = self.formatter
1503 formatter.store_option_strings(self)
1504 result = []
Greg Wardeba20e62004-07-31 16:15:44 +00001505 result.append(formatter.format_heading(_("options")))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001506 formatter.indent()
1507 if self.option_list:
1508 result.append(OptionContainer.format_option_help(self, formatter))
1509 result.append("\n")
1510 for group in self.option_groups:
1511 result.append(group.format_help(formatter))
1512 result.append("\n")
1513 formatter.dedent()
1514 # Drop the last "\n", or the header if no options or option groups:
1515 return "".join(result[:-1])
1516
Greg Wardeba20e62004-07-31 16:15:44 +00001517 def format_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001518 if formatter is None:
1519 formatter = self.formatter
1520 result = []
1521 if self.usage:
1522 result.append(self.get_usage() + "\n")
1523 if self.description:
1524 result.append(self.format_description(formatter) + "\n")
1525 result.append(self.format_option_help(formatter))
1526 return "".join(result)
1527
Greg Wardeba20e62004-07-31 16:15:44 +00001528 def print_help(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001529 """print_help(file : file = stdout)
1530
1531 Print an extended help message, listing all options and any
1532 help text provided with them, to 'file' (default stdout).
1533 """
1534 if file is None:
1535 file = sys.stdout
1536 file.write(self.format_help())
1537
1538# class OptionParser
1539
1540
Greg Wardeba20e62004-07-31 16:15:44 +00001541def _match_abbrev(s, wordmap):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001542 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1543
1544 Return the string key in 'wordmap' for which 's' is an unambiguous
1545 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1546 'words', raise BadOptionError.
1547 """
1548 # Is there an exact match?
1549 if wordmap.has_key(s):
1550 return s
1551 else:
1552 # Isolate all words with s as a prefix.
1553 possibilities = [word for word in wordmap.keys()
1554 if word.startswith(s)]
1555 # No exact match, so there had better be just one possibility.
1556 if len(possibilities) == 1:
1557 return possibilities[0]
1558 elif not possibilities:
Greg Wardeba20e62004-07-31 16:15:44 +00001559 raise BadOptionError(_("no such option: %s") % s)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001560 else:
1561 # More than one possible completion: ambiguous prefix.
Greg Wardeba20e62004-07-31 16:15:44 +00001562 raise BadOptionError(_("ambiguous option: %s (%s?)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001563 % (s, ", ".join(possibilities)))
1564
1565
1566# Some day, there might be many Option classes. As of Optik 1.3, the
1567# preferred way to instantiate Options is indirectly, via make_option(),
1568# which will become a factory function when there are many Option
1569# classes.
1570make_option = Option