blob: ae3d00dc51635ec4fef0b7fab23c60645f631b68 [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
Guido van Rossumb9ba4582002-11-14 22:00:19 +000070import textwrap
Brett Cannon84667c02004-12-07 03:25:18 +000071try:
72 from gettext import gettext as _
73except ImportError:
74 _ = lambda arg: arg
Greg Wardeba20e62004-07-31 16:15:44 +000075
76def _repr(self):
77 return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
78
79
80# This file was generated from:
Greg Ward48aa84b2004-10-27 02:20:04 +000081# Id: option_parser.py 421 2004-10-26 00:45:16Z greg
82# Id: option.py 422 2004-10-26 00:53:47Z greg
83# Id: help.py 367 2004-07-24 23:21:21Z gward
84# Id: errors.py 367 2004-07-24 23:21:21Z gward
Guido van Rossumb9ba4582002-11-14 22:00:19 +000085
Guido van Rossumb9ba4582002-11-14 22:00:19 +000086class OptParseError (Exception):
Greg Wardeba20e62004-07-31 16:15:44 +000087 def __init__(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000088 self.msg = msg
89
Greg Wardeba20e62004-07-31 16:15:44 +000090 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000091 return self.msg
92
Greg Ward2492fcf2003-04-21 02:40:34 +000093
Guido van Rossumb9ba4582002-11-14 22:00:19 +000094class OptionError (OptParseError):
95 """
96 Raised if an Option instance is created with invalid or
97 inconsistent arguments.
98 """
99
Greg Wardeba20e62004-07-31 16:15:44 +0000100 def __init__(self, msg, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000101 self.msg = msg
102 self.option_id = str(option)
103
Greg Wardeba20e62004-07-31 16:15:44 +0000104 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000105 if self.option_id:
106 return "option %s: %s" % (self.option_id, self.msg)
107 else:
108 return self.msg
109
110class OptionConflictError (OptionError):
111 """
112 Raised if conflicting options are added to an OptionParser.
113 """
114
115class OptionValueError (OptParseError):
116 """
117 Raised if an invalid option value is encountered on the command
118 line.
119 """
120
121class BadOptionError (OptParseError):
122 """
123 Raised if an invalid or ambiguous option is seen on the command-line.
124 """
Greg Ward2492fcf2003-04-21 02:40:34 +0000125
126
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000127class HelpFormatter:
128
129 """
130 Abstract base class for formatting option help. OptionParser
131 instances should use one of the HelpFormatter subclasses for
132 formatting help; by default IndentedHelpFormatter is used.
133
134 Instance attributes:
Greg Wardeba20e62004-07-31 16:15:44 +0000135 parser : OptionParser
136 the controlling OptionParser instance
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000137 indent_increment : int
138 the number of columns to indent per nesting level
139 max_help_position : int
140 the maximum starting column for option help text
141 help_position : int
142 the calculated starting column for option help text;
143 initially the same as the maximum
144 width : int
Greg Wardeba20e62004-07-31 16:15:44 +0000145 total number of columns for output (pass None to constructor for
146 this value to be taken from the $COLUMNS environment variable)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000147 level : int
148 current indentation level
149 current_indent : int
150 current indentation level (in columns)
151 help_width : int
152 number of columns available for option help text (calculated)
Greg Wardeba20e62004-07-31 16:15:44 +0000153 default_tag : str
154 text to replace with each option's default value, "%default"
155 by default. Set to false value to disable default value expansion.
156 option_strings : { Option : str }
157 maps Option instances to the snippet of help text explaining
158 the syntax of that option, e.g. "-h, --help" or
159 "-fFILE, --file=FILE"
160 _short_opt_fmt : str
161 format string controlling how short options with values are
162 printed in help text. Must be either "%s%s" ("-fFILE") or
163 "%s %s" ("-f FILE"), because those are the two syntaxes that
164 Optik supports.
165 _long_opt_fmt : str
166 similar but for long options; must be either "%s %s" ("--file FILE")
167 or "%s=%s" ("--file=FILE").
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000168 """
169
Greg Wardeba20e62004-07-31 16:15:44 +0000170 NO_DEFAULT_VALUE = "none"
171
172 def __init__(self,
173 indent_increment,
174 max_help_position,
175 width,
176 short_first):
177 self.parser = None
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000178 self.indent_increment = indent_increment
179 self.help_position = self.max_help_position = max_help_position
Greg Wardeba20e62004-07-31 16:15:44 +0000180 if width is None:
181 try:
182 width = int(os.environ['COLUMNS'])
183 except (KeyError, ValueError):
184 width = 80
185 width -= 2
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000186 self.width = width
187 self.current_indent = 0
188 self.level = 0
Greg Wardeba20e62004-07-31 16:15:44 +0000189 self.help_width = None # computed later
Greg Ward2492fcf2003-04-21 02:40:34 +0000190 self.short_first = short_first
Greg Wardeba20e62004-07-31 16:15:44 +0000191 self.default_tag = "%default"
192 self.option_strings = {}
193 self._short_opt_fmt = "%s %s"
194 self._long_opt_fmt = "%s=%s"
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000195
Greg Wardeba20e62004-07-31 16:15:44 +0000196 def set_parser(self, parser):
197 self.parser = parser
198
199 def set_short_opt_delimiter(self, delim):
200 if delim not in ("", " "):
201 raise ValueError(
202 "invalid metavar delimiter for short options: %r" % delim)
203 self._short_opt_fmt = "%s" + delim + "%s"
204
205 def set_long_opt_delimiter(self, delim):
206 if delim not in ("=", " "):
207 raise ValueError(
208 "invalid metavar delimiter for long options: %r" % delim)
209 self._long_opt_fmt = "%s" + delim + "%s"
210
211 def indent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000212 self.current_indent += self.indent_increment
213 self.level += 1
214
Greg Wardeba20e62004-07-31 16:15:44 +0000215 def dedent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000216 self.current_indent -= self.indent_increment
217 assert self.current_indent >= 0, "Indent decreased below 0."
218 self.level -= 1
219
Greg Wardeba20e62004-07-31 16:15:44 +0000220 def format_usage(self, usage):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000221 raise NotImplementedError, "subclasses must implement"
222
Greg Wardeba20e62004-07-31 16:15:44 +0000223 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000224 raise NotImplementedError, "subclasses must implement"
225
Greg Wardeba20e62004-07-31 16:15:44 +0000226 def format_description(self, description):
227 if not description:
228 return ""
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000229 desc_width = self.width - self.current_indent
230 indent = " "*self.current_indent
Greg Wardeba20e62004-07-31 16:15:44 +0000231 return textwrap.fill(description,
232 desc_width,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000233 initial_indent=indent,
Greg Wardeba20e62004-07-31 16:15:44 +0000234 subsequent_indent=indent) + "\n"
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000235
Greg Wardeba20e62004-07-31 16:15:44 +0000236 def expand_default(self, option):
237 if self.parser is None or not self.default_tag:
238 return option.help
239
240 default_value = self.parser.defaults.get(option.dest)
241 if default_value is NO_DEFAULT or default_value is None:
242 default_value = self.NO_DEFAULT_VALUE
243
244 return option.help.replace(self.default_tag, str(default_value))
245
246 def format_option(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000247 # The help for each option consists of two parts:
248 # * the opt strings and metavars
249 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
250 # * the user-supplied help string
251 # eg. ("turn on expert mode", "read data from FILENAME")
252 #
253 # If possible, we write both of these on the same line:
254 # -x turn on expert mode
255 #
256 # But if the opt string list is too long, we put the help
257 # string on a second line, indented to the same column it would
258 # start in if it fit on the first line.
259 # -fFILENAME, --file=FILENAME
260 # read data from FILENAME
261 result = []
Greg Wardeba20e62004-07-31 16:15:44 +0000262 opts = self.option_strings[option]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000263 opt_width = self.help_position - self.current_indent - 2
264 if len(opts) > opt_width:
265 opts = "%*s%s\n" % (self.current_indent, "", opts)
266 indent_first = self.help_position
267 else: # start help on same line as opts
268 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
269 indent_first = 0
270 result.append(opts)
271 if option.help:
Greg Wardeba20e62004-07-31 16:15:44 +0000272 help_text = self.expand_default(option)
273 help_lines = textwrap.wrap(help_text, self.help_width)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000274 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
275 result.extend(["%*s%s\n" % (self.help_position, "", line)
276 for line in help_lines[1:]])
277 elif opts[-1] != "\n":
278 result.append("\n")
279 return "".join(result)
280
Greg Wardeba20e62004-07-31 16:15:44 +0000281 def store_option_strings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000282 self.indent()
283 max_len = 0
284 for opt in parser.option_list:
285 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000286 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000287 max_len = max(max_len, len(strings) + self.current_indent)
288 self.indent()
289 for group in parser.option_groups:
290 for opt in group.option_list:
291 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000292 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000293 max_len = max(max_len, len(strings) + self.current_indent)
294 self.dedent()
295 self.dedent()
296 self.help_position = min(max_len + 2, self.max_help_position)
Greg Wardeba20e62004-07-31 16:15:44 +0000297 self.help_width = self.width - self.help_position
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000298
Greg Wardeba20e62004-07-31 16:15:44 +0000299 def format_option_strings(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000300 """Return a comma-separated list of option strings & metavariables."""
Greg Ward2492fcf2003-04-21 02:40:34 +0000301 if option.takes_value():
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000302 metavar = option.metavar or option.dest.upper()
Greg Wardeba20e62004-07-31 16:15:44 +0000303 short_opts = [self._short_opt_fmt % (sopt, metavar)
304 for sopt in option._short_opts]
305 long_opts = [self._long_opt_fmt % (lopt, metavar)
306 for lopt in option._long_opts]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000307 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000308 short_opts = option._short_opts
309 long_opts = option._long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000310
Greg Ward2492fcf2003-04-21 02:40:34 +0000311 if self.short_first:
312 opts = short_opts + long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000313 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000314 opts = long_opts + short_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000315
Greg Ward2492fcf2003-04-21 02:40:34 +0000316 return ", ".join(opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000317
318class IndentedHelpFormatter (HelpFormatter):
319 """Format help with indented section bodies.
320 """
321
Greg Wardeba20e62004-07-31 16:15:44 +0000322 def __init__(self,
323 indent_increment=2,
324 max_help_position=24,
325 width=None,
326 short_first=1):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000327 HelpFormatter.__init__(
328 self, indent_increment, max_help_position, width, short_first)
329
Greg Wardeba20e62004-07-31 16:15:44 +0000330 def format_usage(self, usage):
331 return _("usage: %s\n") % usage
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000332
Greg Wardeba20e62004-07-31 16:15:44 +0000333 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000334 return "%*s%s:\n" % (self.current_indent, "", heading)
335
336
337class TitledHelpFormatter (HelpFormatter):
338 """Format help with underlined section headers.
339 """
340
Greg Wardeba20e62004-07-31 16:15:44 +0000341 def __init__(self,
342 indent_increment=0,
343 max_help_position=24,
344 width=None,
345 short_first=0):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000346 HelpFormatter.__init__ (
347 self, indent_increment, max_help_position, width, short_first)
348
Greg Wardeba20e62004-07-31 16:15:44 +0000349 def format_usage(self, usage):
350 return "%s %s\n" % (self.format_heading(_("Usage")), usage)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000351
Greg Wardeba20e62004-07-31 16:15:44 +0000352 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000353 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
Greg Ward2492fcf2003-04-21 02:40:34 +0000354
355
Greg Wardeba20e62004-07-31 16:15:44 +0000356_builtin_cvt = { "int" : (int, _("integer")),
357 "long" : (long, _("long integer")),
358 "float" : (float, _("floating-point")),
359 "complex" : (complex, _("complex")) }
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000360
Greg Wardeba20e62004-07-31 16:15:44 +0000361def check_builtin(option, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000362 (cvt, what) = _builtin_cvt[option.type]
363 try:
364 return cvt(value)
365 except ValueError:
366 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000367 _("option %s: invalid %s value: %r") % (opt, what, value))
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000368
369def check_choice(option, opt, value):
370 if value in option.choices:
371 return value
372 else:
373 choices = ", ".join(map(repr, option.choices))
374 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000375 _("option %s: invalid choice: %r (choose from %s)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000376 % (opt, value, choices))
377
378# Not supplying a default is different from a default of None,
379# so we need an explicit "not supplied" value.
Greg Wardeba20e62004-07-31 16:15:44 +0000380NO_DEFAULT = ("NO", "DEFAULT")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000381
382
383class Option:
384 """
385 Instance attributes:
386 _short_opts : [string]
387 _long_opts : [string]
388
389 action : string
390 type : string
391 dest : string
392 default : any
393 nargs : int
394 const : any
395 choices : [string]
396 callback : function
397 callback_args : (any*)
398 callback_kwargs : { string : any }
399 help : string
400 metavar : string
401 """
402
403 # The list of instance attributes that may be set through
404 # keyword args to the constructor.
405 ATTRS = ['action',
406 'type',
407 'dest',
408 'default',
409 'nargs',
410 'const',
411 'choices',
412 'callback',
413 'callback_args',
414 'callback_kwargs',
415 'help',
416 'metavar']
417
418 # The set of actions allowed by option parsers. Explicitly listed
419 # here so the constructor can validate its arguments.
420 ACTIONS = ("store",
421 "store_const",
422 "store_true",
423 "store_false",
424 "append",
425 "count",
426 "callback",
427 "help",
428 "version")
429
430 # The set of actions that involve storing a value somewhere;
431 # also listed just for constructor argument validation. (If
432 # the action is one of these, there must be a destination.)
433 STORE_ACTIONS = ("store",
434 "store_const",
435 "store_true",
436 "store_false",
437 "append",
438 "count")
439
440 # The set of actions for which it makes sense to supply a value
Greg Ward48aa84b2004-10-27 02:20:04 +0000441 # type, ie. which may consume an argument from the command line.
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000442 TYPED_ACTIONS = ("store",
443 "append",
444 "callback")
445
Greg Ward48aa84b2004-10-27 02:20:04 +0000446 # The set of actions which *require* a value type, ie. that
447 # always consume an argument from the command line.
448 ALWAYS_TYPED_ACTIONS = ("store",
449 "append")
450
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000451 # The set of known types for option parsers. Again, listed here for
452 # constructor argument validation.
453 TYPES = ("string", "int", "long", "float", "complex", "choice")
454
455 # Dictionary of argument checking functions, which convert and
456 # validate option arguments according to the option type.
457 #
458 # Signature of checking functions is:
459 # check(option : Option, opt : string, value : string) -> any
460 # where
461 # option is the Option instance calling the checker
462 # opt is the actual option seen on the command-line
463 # (eg. "-a", "--file")
464 # value is the option argument seen on the command-line
465 #
466 # The return value should be in the appropriate Python type
467 # for option.type -- eg. an integer if option.type == "int".
468 #
469 # If no checker is defined for a type, arguments will be
470 # unchecked and remain strings.
471 TYPE_CHECKER = { "int" : check_builtin,
472 "long" : check_builtin,
473 "float" : check_builtin,
Greg Wardeba20e62004-07-31 16:15:44 +0000474 "complex": check_builtin,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000475 "choice" : check_choice,
476 }
477
478
479 # CHECK_METHODS is a list of unbound method objects; they are called
480 # by the constructor, in order, after all attributes are
481 # initialized. The list is created and filled in later, after all
482 # the methods are actually defined. (I just put it here because I
483 # like to define and document all class attributes in the same
484 # place.) Subclasses that add another _check_*() method should
485 # define their own CHECK_METHODS list that adds their check method
486 # to those from this class.
487 CHECK_METHODS = None
488
489
490 # -- Constructor/initialization methods ----------------------------
491
Greg Wardeba20e62004-07-31 16:15:44 +0000492 def __init__(self, *opts, **attrs):
Greg Ward2492fcf2003-04-21 02:40:34 +0000493 # Set _short_opts, _long_opts attrs from 'opts' tuple.
494 # Have to be set now, in case no option strings are supplied.
495 self._short_opts = []
496 self._long_opts = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000497 opts = self._check_opt_strings(opts)
498 self._set_opt_strings(opts)
499
500 # Set all other attrs (action, type, etc.) from 'attrs' dict
501 self._set_attrs(attrs)
502
503 # Check all the attributes we just set. There are lots of
504 # complicated interdependencies, but luckily they can be farmed
505 # out to the _check_*() methods listed in CHECK_METHODS -- which
506 # could be handy for subclasses! The one thing these all share
507 # is that they raise OptionError if they discover a problem.
508 for checker in self.CHECK_METHODS:
509 checker(self)
510
Greg Wardeba20e62004-07-31 16:15:44 +0000511 def _check_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000512 # Filter out None because early versions of Optik had exactly
513 # one short option and one long option, either of which
514 # could be None.
515 opts = filter(None, opts)
516 if not opts:
Greg Ward2492fcf2003-04-21 02:40:34 +0000517 raise TypeError("at least one option string must be supplied")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000518 return opts
519
Greg Wardeba20e62004-07-31 16:15:44 +0000520 def _set_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000521 for opt in opts:
522 if len(opt) < 2:
523 raise OptionError(
524 "invalid option string %r: "
525 "must be at least two characters long" % opt, self)
526 elif len(opt) == 2:
527 if not (opt[0] == "-" and opt[1] != "-"):
528 raise OptionError(
529 "invalid short option string %r: "
530 "must be of the form -x, (x any non-dash char)" % opt,
531 self)
532 self._short_opts.append(opt)
533 else:
534 if not (opt[0:2] == "--" and opt[2] != "-"):
535 raise OptionError(
536 "invalid long option string %r: "
537 "must start with --, followed by non-dash" % opt,
538 self)
539 self._long_opts.append(opt)
540
Greg Wardeba20e62004-07-31 16:15:44 +0000541 def _set_attrs(self, attrs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000542 for attr in self.ATTRS:
543 if attrs.has_key(attr):
544 setattr(self, attr, attrs[attr])
545 del attrs[attr]
546 else:
547 if attr == 'default':
548 setattr(self, attr, NO_DEFAULT)
549 else:
550 setattr(self, attr, None)
551 if attrs:
552 raise OptionError(
553 "invalid keyword arguments: %s" % ", ".join(attrs.keys()),
554 self)
555
556
557 # -- Constructor validation methods --------------------------------
558
Greg Wardeba20e62004-07-31 16:15:44 +0000559 def _check_action(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000560 if self.action is None:
561 self.action = "store"
562 elif self.action not in self.ACTIONS:
563 raise OptionError("invalid action: %r" % self.action, self)
564
Greg Wardeba20e62004-07-31 16:15:44 +0000565 def _check_type(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000566 if self.type is None:
Greg Ward48aa84b2004-10-27 02:20:04 +0000567 if self.action in self.ALWAYS_TYPED_ACTIONS:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000568 if self.choices is not None:
569 # The "choices" attribute implies "choice" type.
570 self.type = "choice"
571 else:
572 # No type given? "string" is the most sensible default.
573 self.type = "string"
574 else:
Greg Wardeba20e62004-07-31 16:15:44 +0000575 # Allow type objects as an alternative to their names.
576 if type(self.type) is type:
577 self.type = self.type.__name__
578 if self.type == "str":
579 self.type = "string"
580
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000581 if self.type not in self.TYPES:
582 raise OptionError("invalid option type: %r" % self.type, self)
583 if self.action not in self.TYPED_ACTIONS:
584 raise OptionError(
585 "must not supply a type for action %r" % self.action, self)
586
587 def _check_choice(self):
588 if self.type == "choice":
589 if self.choices is None:
590 raise OptionError(
591 "must supply a list of choices for type 'choice'", self)
Raymond Hettingerf7153662005-02-07 14:16:21 +0000592 elif type(self.choices) not in (tuple, list):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000593 raise OptionError(
594 "choices must be a list of strings ('%s' supplied)"
595 % str(type(self.choices)).split("'")[1], self)
596 elif self.choices is not None:
597 raise OptionError(
598 "must not supply choices for type %r" % self.type, self)
599
Greg Wardeba20e62004-07-31 16:15:44 +0000600 def _check_dest(self):
601 # No destination given, and we need one for this action. The
602 # self.type check is for callbacks that take a value.
603 takes_value = (self.action in self.STORE_ACTIONS or
604 self.type is not None)
605 if self.dest is None and takes_value:
606
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000607 # Glean a destination from the first long option string,
608 # or from the first short option string if no long options.
609 if self._long_opts:
610 # eg. "--foo-bar" -> "foo_bar"
611 self.dest = self._long_opts[0][2:].replace('-', '_')
612 else:
613 self.dest = self._short_opts[0][1]
614
Greg Wardeba20e62004-07-31 16:15:44 +0000615 def _check_const(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000616 if self.action != "store_const" and self.const is not None:
617 raise OptionError(
618 "'const' must not be supplied for action %r" % self.action,
619 self)
620
Greg Wardeba20e62004-07-31 16:15:44 +0000621 def _check_nargs(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000622 if self.action in self.TYPED_ACTIONS:
623 if self.nargs is None:
624 self.nargs = 1
625 elif self.nargs is not None:
626 raise OptionError(
627 "'nargs' must not be supplied for action %r" % self.action,
628 self)
629
Greg Wardeba20e62004-07-31 16:15:44 +0000630 def _check_callback(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000631 if self.action == "callback":
632 if not callable(self.callback):
633 raise OptionError(
634 "callback not callable: %r" % self.callback, self)
635 if (self.callback_args is not None and
Raymond Hettingerf7153662005-02-07 14:16:21 +0000636 type(self.callback_args) is not tuple):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000637 raise OptionError(
638 "callback_args, if supplied, must be a tuple: not %r"
639 % self.callback_args, self)
640 if (self.callback_kwargs is not None and
Raymond Hettingerf7153662005-02-07 14:16:21 +0000641 type(self.callback_kwargs) is not dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000642 raise OptionError(
643 "callback_kwargs, if supplied, must be a dict: not %r"
644 % self.callback_kwargs, self)
645 else:
646 if self.callback is not None:
647 raise OptionError(
648 "callback supplied (%r) for non-callback option"
649 % self.callback, self)
650 if self.callback_args is not None:
651 raise OptionError(
652 "callback_args supplied for non-callback option", self)
653 if self.callback_kwargs is not None:
654 raise OptionError(
655 "callback_kwargs supplied for non-callback option", self)
656
657
658 CHECK_METHODS = [_check_action,
659 _check_type,
660 _check_choice,
661 _check_dest,
662 _check_const,
663 _check_nargs,
664 _check_callback]
665
666
667 # -- Miscellaneous methods -----------------------------------------
668
Greg Wardeba20e62004-07-31 16:15:44 +0000669 def __str__(self):
Greg Ward2492fcf2003-04-21 02:40:34 +0000670 return "/".join(self._short_opts + self._long_opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000671
Greg Wardeba20e62004-07-31 16:15:44 +0000672 __repr__ = _repr
673
674 def takes_value(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000675 return self.type is not None
676
Greg Wardeba20e62004-07-31 16:15:44 +0000677 def get_opt_string(self):
678 if self._long_opts:
679 return self._long_opts[0]
680 else:
681 return self._short_opts[0]
682
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000683
684 # -- Processing methods --------------------------------------------
685
Greg Wardeba20e62004-07-31 16:15:44 +0000686 def check_value(self, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000687 checker = self.TYPE_CHECKER.get(self.type)
688 if checker is None:
689 return value
690 else:
691 return checker(self, opt, value)
692
Greg Wardeba20e62004-07-31 16:15:44 +0000693 def convert_value(self, opt, value):
694 if value is not None:
695 if self.nargs == 1:
696 return self.check_value(opt, value)
697 else:
698 return tuple([self.check_value(opt, v) for v in value])
699
700 def process(self, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000701
702 # First, convert the value(s) to the right type. Howl if any
703 # value(s) are bogus.
Greg Wardeba20e62004-07-31 16:15:44 +0000704 value = self.convert_value(opt, value)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000705
706 # And then take whatever action is expected of us.
707 # This is a separate method to make life easier for
708 # subclasses to add new actions.
709 return self.take_action(
710 self.action, self.dest, opt, value, values, parser)
711
Greg Wardeba20e62004-07-31 16:15:44 +0000712 def take_action(self, action, dest, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000713 if action == "store":
714 setattr(values, dest, value)
715 elif action == "store_const":
716 setattr(values, dest, self.const)
717 elif action == "store_true":
Greg Ward2492fcf2003-04-21 02:40:34 +0000718 setattr(values, dest, True)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000719 elif action == "store_false":
Greg Ward2492fcf2003-04-21 02:40:34 +0000720 setattr(values, dest, False)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000721 elif action == "append":
722 values.ensure_value(dest, []).append(value)
723 elif action == "count":
724 setattr(values, dest, values.ensure_value(dest, 0) + 1)
725 elif action == "callback":
726 args = self.callback_args or ()
727 kwargs = self.callback_kwargs or {}
728 self.callback(self, opt, value, parser, *args, **kwargs)
729 elif action == "help":
730 parser.print_help()
Greg Ward48aa84b2004-10-27 02:20:04 +0000731 parser.exit()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000732 elif action == "version":
733 parser.print_version()
Greg Ward48aa84b2004-10-27 02:20:04 +0000734 parser.exit()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000735 else:
736 raise RuntimeError, "unknown action %r" % self.action
737
738 return 1
739
740# class Option
Greg Ward2492fcf2003-04-21 02:40:34 +0000741
742
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000743SUPPRESS_HELP = "SUPPRESS"+"HELP"
744SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
745
Greg Wardeba20e62004-07-31 16:15:44 +0000746# For compatibility with Python 2.2
747try:
748 True, False
749except NameError:
750 (True, False) = (1, 0)
751try:
752 basestring
753except NameError:
754 basestring = (str, unicode)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000755
756
757class Values:
758
Greg Wardeba20e62004-07-31 16:15:44 +0000759 def __init__(self, defaults=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000760 if defaults:
761 for (attr, val) in defaults.items():
762 setattr(self, attr, val)
763
Greg Wardeba20e62004-07-31 16:15:44 +0000764 def __str__(self):
765 return str(self.__dict__)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000766
Greg Wardeba20e62004-07-31 16:15:44 +0000767 __repr__ = _repr
768
769 def __eq__(self, other):
770 if isinstance(other, Values):
771 return self.__dict__ == other.__dict__
772 elif isinstance(other, dict):
773 return self.__dict__ == other
774 else:
Neal Norwitz13389462004-10-17 16:24:25 +0000775 return False
Greg Wardeba20e62004-07-31 16:15:44 +0000776
777 def __ne__(self, other):
778 return not (self == other)
779
780 def _update_careful(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000781 """
782 Update the option values from an arbitrary dictionary, but only
783 use keys from dict that already have a corresponding attribute
784 in self. Any keys in dict without a corresponding attribute
785 are silently ignored.
786 """
787 for attr in dir(self):
788 if dict.has_key(attr):
789 dval = dict[attr]
790 if dval is not None:
791 setattr(self, attr, dval)
792
Greg Wardeba20e62004-07-31 16:15:44 +0000793 def _update_loose(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000794 """
795 Update the option values from an arbitrary dictionary,
796 using all keys from the dictionary regardless of whether
797 they have a corresponding attribute in self or not.
798 """
799 self.__dict__.update(dict)
800
Greg Wardeba20e62004-07-31 16:15:44 +0000801 def _update(self, dict, mode):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000802 if mode == "careful":
803 self._update_careful(dict)
804 elif mode == "loose":
805 self._update_loose(dict)
806 else:
807 raise ValueError, "invalid update mode: %r" % mode
808
Greg Wardeba20e62004-07-31 16:15:44 +0000809 def read_module(self, modname, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000810 __import__(modname)
811 mod = sys.modules[modname]
812 self._update(vars(mod), mode)
813
Greg Wardeba20e62004-07-31 16:15:44 +0000814 def read_file(self, filename, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000815 vars = {}
816 execfile(filename, vars)
817 self._update(vars, mode)
818
Greg Wardeba20e62004-07-31 16:15:44 +0000819 def ensure_value(self, attr, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000820 if not hasattr(self, attr) or getattr(self, attr) is None:
821 setattr(self, attr, value)
822 return getattr(self, attr)
823
824
825class OptionContainer:
826
827 """
828 Abstract base class.
829
830 Class attributes:
831 standard_option_list : [Option]
832 list of standard options that will be accepted by all instances
833 of this parser class (intended to be overridden by subclasses).
834
835 Instance attributes:
836 option_list : [Option]
837 the list of Option objects contained by this OptionContainer
838 _short_opt : { string : Option }
839 dictionary mapping short option strings, eg. "-f" or "-X",
840 to the Option instances that implement them. If an Option
841 has multiple short option strings, it will appears in this
842 dictionary multiple times. [1]
843 _long_opt : { string : Option }
844 dictionary mapping long option strings, eg. "--file" or
845 "--exclude", to the Option instances that implement them.
846 Again, a given Option can occur multiple times in this
847 dictionary. [1]
848 defaults : { string : any }
849 dictionary mapping option destination names to default
850 values for each destination [1]
851
852 [1] These mappings are common to (shared by) all components of the
853 controlling OptionParser, where they are initially created.
854
855 """
856
Greg Wardeba20e62004-07-31 16:15:44 +0000857 def __init__(self, option_class, conflict_handler, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000858 # Initialize the option list and related data structures.
859 # This method must be provided by subclasses, and it must
860 # initialize at least the following instance attributes:
861 # option_list, _short_opt, _long_opt, defaults.
862 self._create_option_list()
863
864 self.option_class = option_class
865 self.set_conflict_handler(conflict_handler)
866 self.set_description(description)
867
Greg Wardeba20e62004-07-31 16:15:44 +0000868 def _create_option_mappings(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000869 # For use by OptionParser constructor -- create the master
870 # option mappings used by this OptionParser and all
871 # OptionGroups that it owns.
872 self._short_opt = {} # single letter -> Option instance
873 self._long_opt = {} # long option -> Option instance
874 self.defaults = {} # maps option dest -> default value
875
876
Greg Wardeba20e62004-07-31 16:15:44 +0000877 def _share_option_mappings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000878 # For use by OptionGroup constructor -- use shared option
879 # mappings from the OptionParser that owns this OptionGroup.
880 self._short_opt = parser._short_opt
881 self._long_opt = parser._long_opt
882 self.defaults = parser.defaults
883
Greg Wardeba20e62004-07-31 16:15:44 +0000884 def set_conflict_handler(self, handler):
Greg Ward48aa84b2004-10-27 02:20:04 +0000885 if handler not in ("error", "resolve"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000886 raise ValueError, "invalid conflict_resolution value %r" % handler
887 self.conflict_handler = handler
888
Greg Wardeba20e62004-07-31 16:15:44 +0000889 def set_description(self, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000890 self.description = description
891
Greg Wardeba20e62004-07-31 16:15:44 +0000892 def get_description(self):
893 return self.description
894
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000895
896 # -- Option-adding methods -----------------------------------------
897
Greg Wardeba20e62004-07-31 16:15:44 +0000898 def _check_conflict(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000899 conflict_opts = []
900 for opt in option._short_opts:
901 if self._short_opt.has_key(opt):
902 conflict_opts.append((opt, self._short_opt[opt]))
903 for opt in option._long_opts:
904 if self._long_opt.has_key(opt):
905 conflict_opts.append((opt, self._long_opt[opt]))
906
907 if conflict_opts:
908 handler = self.conflict_handler
Greg Ward48aa84b2004-10-27 02:20:04 +0000909 if handler == "error":
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000910 raise OptionConflictError(
911 "conflicting option string(s): %s"
912 % ", ".join([co[0] for co in conflict_opts]),
913 option)
Greg Ward48aa84b2004-10-27 02:20:04 +0000914 elif handler == "resolve":
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000915 for (opt, c_option) in conflict_opts:
916 if opt.startswith("--"):
917 c_option._long_opts.remove(opt)
918 del self._long_opt[opt]
919 else:
920 c_option._short_opts.remove(opt)
921 del self._short_opt[opt]
922 if not (c_option._short_opts or c_option._long_opts):
923 c_option.container.option_list.remove(c_option)
924
Greg Wardeba20e62004-07-31 16:15:44 +0000925 def add_option(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000926 """add_option(Option)
927 add_option(opt_str, ..., kwarg=val, ...)
928 """
Raymond Hettingerf7153662005-02-07 14:16:21 +0000929 if type(args[0]) is str:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000930 option = self.option_class(*args, **kwargs)
931 elif len(args) == 1 and not kwargs:
932 option = args[0]
933 if not isinstance(option, Option):
934 raise TypeError, "not an Option instance: %r" % option
935 else:
936 raise TypeError, "invalid arguments"
937
938 self._check_conflict(option)
939
940 self.option_list.append(option)
941 option.container = self
942 for opt in option._short_opts:
943 self._short_opt[opt] = option
944 for opt in option._long_opts:
945 self._long_opt[opt] = option
946
947 if option.dest is not None: # option has a dest, we need a default
948 if option.default is not NO_DEFAULT:
949 self.defaults[option.dest] = option.default
950 elif not self.defaults.has_key(option.dest):
951 self.defaults[option.dest] = None
952
953 return option
954
Greg Wardeba20e62004-07-31 16:15:44 +0000955 def add_options(self, option_list):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000956 for option in option_list:
957 self.add_option(option)
958
959 # -- Option query/removal methods ----------------------------------
960
Greg Wardeba20e62004-07-31 16:15:44 +0000961 def get_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000962 return (self._short_opt.get(opt_str) or
963 self._long_opt.get(opt_str))
964
Greg Wardeba20e62004-07-31 16:15:44 +0000965 def has_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000966 return (self._short_opt.has_key(opt_str) or
967 self._long_opt.has_key(opt_str))
968
Greg Wardeba20e62004-07-31 16:15:44 +0000969 def remove_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000970 option = self._short_opt.get(opt_str)
971 if option is None:
972 option = self._long_opt.get(opt_str)
973 if option is None:
974 raise ValueError("no such option %r" % opt_str)
975
976 for opt in option._short_opts:
977 del self._short_opt[opt]
978 for opt in option._long_opts:
979 del self._long_opt[opt]
980 option.container.option_list.remove(option)
981
982
983 # -- Help-formatting methods ---------------------------------------
984
Greg Wardeba20e62004-07-31 16:15:44 +0000985 def format_option_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000986 if not self.option_list:
987 return ""
988 result = []
989 for option in self.option_list:
990 if not option.help is SUPPRESS_HELP:
991 result.append(formatter.format_option(option))
992 return "".join(result)
993
Greg Wardeba20e62004-07-31 16:15:44 +0000994 def format_description(self, formatter):
995 return formatter.format_description(self.get_description())
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000996
Greg Wardeba20e62004-07-31 16:15:44 +0000997 def format_help(self, formatter):
998 result = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000999 if self.description:
Greg Wardeba20e62004-07-31 16:15:44 +00001000 result.append(self.format_description(formatter))
1001 if self.option_list:
1002 result.append(self.format_option_help(formatter))
1003 return "\n".join(result)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001004
1005
1006class OptionGroup (OptionContainer):
1007
Greg Wardeba20e62004-07-31 16:15:44 +00001008 def __init__(self, parser, title, description=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001009 self.parser = parser
1010 OptionContainer.__init__(
1011 self, parser.option_class, parser.conflict_handler, description)
1012 self.title = title
1013
Greg Wardeba20e62004-07-31 16:15:44 +00001014 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001015 self.option_list = []
1016 self._share_option_mappings(self.parser)
1017
Greg Wardeba20e62004-07-31 16:15:44 +00001018 def set_title(self, title):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001019 self.title = title
1020
1021 # -- Help-formatting methods ---------------------------------------
1022
Greg Wardeba20e62004-07-31 16:15:44 +00001023 def format_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001024 result = formatter.format_heading(self.title)
1025 formatter.indent()
1026 result += OptionContainer.format_help(self, formatter)
1027 formatter.dedent()
1028 return result
1029
1030
1031class OptionParser (OptionContainer):
1032
1033 """
1034 Class attributes:
1035 standard_option_list : [Option]
1036 list of standard options that will be accepted by all instances
1037 of this parser class (intended to be overridden by subclasses).
1038
1039 Instance attributes:
1040 usage : string
1041 a usage string for your program. Before it is displayed
1042 to the user, "%prog" will be expanded to the name of
Greg Ward2492fcf2003-04-21 02:40:34 +00001043 your program (self.prog or os.path.basename(sys.argv[0])).
1044 prog : string
1045 the name of the current program (to override
1046 os.path.basename(sys.argv[0])).
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001047
Greg Wardeba20e62004-07-31 16:15:44 +00001048 option_groups : [OptionGroup]
1049 list of option groups in this parser (option groups are
1050 irrelevant for parsing the command-line, but very useful
1051 for generating help)
1052
1053 allow_interspersed_args : bool = true
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001054 if true, positional arguments may be interspersed with options.
1055 Assuming -a and -b each take a single argument, the command-line
1056 -ablah foo bar -bboo baz
1057 will be interpreted the same as
1058 -ablah -bboo -- foo bar baz
1059 If this flag were false, that command line would be interpreted as
1060 -ablah -- foo bar -bboo baz
1061 -- ie. we stop processing options as soon as we see the first
1062 non-option argument. (This is the tradition followed by
1063 Python's getopt module, Perl's Getopt::Std, and other argument-
1064 parsing libraries, but it is generally annoying to users.)
1065
Greg Wardeba20e62004-07-31 16:15:44 +00001066 process_default_values : bool = true
1067 if true, option default values are processed similarly to option
1068 values from the command line: that is, they are passed to the
1069 type-checking function for the option's type (as long as the
1070 default value is a string). (This really only matters if you
1071 have defined custom types; see SF bug #955889.) Set it to false
1072 to restore the behaviour of Optik 1.4.1 and earlier.
1073
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001074 rargs : [string]
1075 the argument list currently being parsed. Only set when
1076 parse_args() is active, and continually trimmed down as
1077 we consume arguments. Mainly there for the benefit of
1078 callback options.
1079 largs : [string]
1080 the list of leftover arguments that we have skipped while
1081 parsing options. If allow_interspersed_args is false, this
1082 list is always empty.
1083 values : Values
1084 the set of option values currently being accumulated. Only
1085 set when parse_args() is active. Also mainly for callbacks.
1086
1087 Because of the 'rargs', 'largs', and 'values' attributes,
1088 OptionParser is not thread-safe. If, for some perverse reason, you
1089 need to parse command-line arguments simultaneously in different
1090 threads, use different OptionParser instances.
1091
1092 """
1093
1094 standard_option_list = []
1095
Greg Wardeba20e62004-07-31 16:15:44 +00001096 def __init__(self,
1097 usage=None,
1098 option_list=None,
1099 option_class=Option,
1100 version=None,
1101 conflict_handler="error",
1102 description=None,
1103 formatter=None,
1104 add_help_option=True,
1105 prog=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001106 OptionContainer.__init__(
1107 self, option_class, conflict_handler, description)
1108 self.set_usage(usage)
Greg Ward2492fcf2003-04-21 02:40:34 +00001109 self.prog = prog
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001110 self.version = version
Greg Wardeba20e62004-07-31 16:15:44 +00001111 self.allow_interspersed_args = True
1112 self.process_default_values = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001113 if formatter is None:
1114 formatter = IndentedHelpFormatter()
1115 self.formatter = formatter
Greg Wardeba20e62004-07-31 16:15:44 +00001116 self.formatter.set_parser(self)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001117
1118 # Populate the option list; initial sources are the
1119 # standard_option_list class attribute, the 'option_list'
Greg Wardeba20e62004-07-31 16:15:44 +00001120 # argument, and (if applicable) the _add_version_option() and
1121 # _add_help_option() methods.
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001122 self._populate_option_list(option_list,
1123 add_help=add_help_option)
1124
1125 self._init_parsing_state()
1126
1127 # -- Private methods -----------------------------------------------
1128 # (used by our or OptionContainer's constructor)
1129
Greg Wardeba20e62004-07-31 16:15:44 +00001130 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001131 self.option_list = []
1132 self.option_groups = []
1133 self._create_option_mappings()
1134
Greg Wardeba20e62004-07-31 16:15:44 +00001135 def _add_help_option(self):
1136 self.add_option("-h", "--help",
1137 action="help",
1138 help=_("show this help message and exit"))
1139
1140 def _add_version_option(self):
1141 self.add_option("--version",
1142 action="version",
1143 help=_("show program's version number and exit"))
1144
1145 def _populate_option_list(self, option_list, add_help=True):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001146 if self.standard_option_list:
1147 self.add_options(self.standard_option_list)
1148 if option_list:
1149 self.add_options(option_list)
1150 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001151 self._add_version_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001152 if add_help:
Greg Wardeba20e62004-07-31 16:15:44 +00001153 self._add_help_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001154
Greg Wardeba20e62004-07-31 16:15:44 +00001155 def _init_parsing_state(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001156 # These are set in parse_args() for the convenience of callbacks.
1157 self.rargs = None
1158 self.largs = None
1159 self.values = None
1160
1161
1162 # -- Simple modifier methods ---------------------------------------
1163
Greg Wardeba20e62004-07-31 16:15:44 +00001164 def set_usage(self, usage):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001165 if usage is None:
Greg Wardeba20e62004-07-31 16:15:44 +00001166 self.usage = _("%prog [options]")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001167 elif usage is SUPPRESS_USAGE:
1168 self.usage = None
Greg Wardeba20e62004-07-31 16:15:44 +00001169 # For backwards compatibility with Optik 1.3 and earlier.
1170 elif usage.startswith("usage:" + " "):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001171 self.usage = usage[7:]
1172 else:
1173 self.usage = usage
1174
Greg Wardeba20e62004-07-31 16:15:44 +00001175 def enable_interspersed_args(self):
1176 self.allow_interspersed_args = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001177
Greg Wardeba20e62004-07-31 16:15:44 +00001178 def disable_interspersed_args(self):
1179 self.allow_interspersed_args = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001180
Greg Wardeba20e62004-07-31 16:15:44 +00001181 def set_process_default_values(self, process):
1182 self.process_default_values = process
1183
1184 def set_default(self, dest, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001185 self.defaults[dest] = value
1186
Greg Wardeba20e62004-07-31 16:15:44 +00001187 def set_defaults(self, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001188 self.defaults.update(kwargs)
1189
Greg Wardeba20e62004-07-31 16:15:44 +00001190 def _get_all_options(self):
1191 options = self.option_list[:]
1192 for group in self.option_groups:
1193 options.extend(group.option_list)
1194 return options
1195
1196 def get_default_values(self):
1197 if not self.process_default_values:
1198 # Old, pre-Optik 1.5 behaviour.
1199 return Values(self.defaults)
1200
1201 defaults = self.defaults.copy()
1202 for option in self._get_all_options():
1203 default = defaults.get(option.dest)
1204 if isinstance(default, basestring):
1205 opt_str = option.get_opt_string()
1206 defaults[option.dest] = option.check_value(opt_str, default)
1207
1208 return Values(defaults)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001209
1210
1211 # -- OptionGroup methods -------------------------------------------
1212
Greg Wardeba20e62004-07-31 16:15:44 +00001213 def add_option_group(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001214 # XXX lots of overlap with OptionContainer.add_option()
Raymond Hettingerf7153662005-02-07 14:16:21 +00001215 if type(args[0]) is str:
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001216 group = OptionGroup(self, *args, **kwargs)
1217 elif len(args) == 1 and not kwargs:
1218 group = args[0]
1219 if not isinstance(group, OptionGroup):
1220 raise TypeError, "not an OptionGroup instance: %r" % group
1221 if group.parser is not self:
1222 raise ValueError, "invalid OptionGroup (wrong parser)"
1223 else:
1224 raise TypeError, "invalid arguments"
1225
1226 self.option_groups.append(group)
1227 return group
1228
Greg Wardeba20e62004-07-31 16:15:44 +00001229 def get_option_group(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001230 option = (self._short_opt.get(opt_str) or
1231 self._long_opt.get(opt_str))
1232 if option and option.container is not self:
1233 return option.container
1234 return None
1235
1236
1237 # -- Option-parsing methods ----------------------------------------
1238
Greg Wardeba20e62004-07-31 16:15:44 +00001239 def _get_args(self, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001240 if args is None:
1241 return sys.argv[1:]
1242 else:
1243 return args[:] # don't modify caller's list
1244
Greg Wardeba20e62004-07-31 16:15:44 +00001245 def parse_args(self, args=None, values=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001246 """
1247 parse_args(args : [string] = sys.argv[1:],
1248 values : Values = None)
1249 -> (values : Values, args : [string])
1250
1251 Parse the command-line options found in 'args' (default:
1252 sys.argv[1:]). Any errors result in a call to 'error()', which
1253 by default prints the usage message to stderr and calls
1254 sys.exit() with an error message. On success returns a pair
1255 (values, args) where 'values' is an Values instance (with all
1256 your option values) and 'args' is the list of arguments left
1257 over after parsing options.
1258 """
1259 rargs = self._get_args(args)
1260 if values is None:
1261 values = self.get_default_values()
1262
1263 # Store the halves of the argument list as attributes for the
1264 # convenience of callbacks:
1265 # rargs
1266 # the rest of the command-line (the "r" stands for
1267 # "remaining" or "right-hand")
1268 # largs
1269 # the leftover arguments -- ie. what's left after removing
1270 # options and their arguments (the "l" stands for "leftover"
1271 # or "left-hand")
1272 self.rargs = rargs
1273 self.largs = largs = []
1274 self.values = values
1275
1276 try:
1277 stop = self._process_args(largs, rargs, values)
1278 except (BadOptionError, OptionValueError), err:
1279 self.error(err.msg)
1280
1281 args = largs + rargs
1282 return self.check_values(values, args)
1283
Greg Wardeba20e62004-07-31 16:15:44 +00001284 def check_values(self, values, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001285 """
1286 check_values(values : Values, args : [string])
1287 -> (values : Values, args : [string])
1288
1289 Check that the supplied option values and leftover arguments are
1290 valid. Returns the option values and leftover arguments
1291 (possibly adjusted, possibly completely new -- whatever you
1292 like). Default implementation just returns the passed-in
1293 values; subclasses may override as desired.
1294 """
1295 return (values, args)
1296
Greg Wardeba20e62004-07-31 16:15:44 +00001297 def _process_args(self, largs, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001298 """_process_args(largs : [string],
1299 rargs : [string],
1300 values : Values)
1301
1302 Process command-line arguments and populate 'values', consuming
1303 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1304 false, stop at the first non-option argument. If true, accumulate any
1305 interspersed non-option arguments in 'largs'.
1306 """
1307 while rargs:
1308 arg = rargs[0]
1309 # We handle bare "--" explicitly, and bare "-" is handled by the
1310 # standard arg handler since the short arg case ensures that the
1311 # len of the opt string is greater than 1.
1312 if arg == "--":
1313 del rargs[0]
1314 return
1315 elif arg[0:2] == "--":
1316 # process a single long option (possibly with value(s))
1317 self._process_long_opt(rargs, values)
1318 elif arg[:1] == "-" and len(arg) > 1:
1319 # process a cluster of short options (possibly with
1320 # value(s) for the last one only)
1321 self._process_short_opts(rargs, values)
1322 elif self.allow_interspersed_args:
1323 largs.append(arg)
1324 del rargs[0]
1325 else:
1326 return # stop now, leave this arg in rargs
1327
1328 # Say this is the original argument list:
1329 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1330 # ^
1331 # (we are about to process arg(i)).
1332 #
1333 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1334 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1335 # been removed from largs).
1336 #
1337 # The while loop will usually consume 1 or more arguments per pass.
1338 # If it consumes 1 (eg. arg is an option that takes no arguments),
1339 # then after _process_arg() is done the situation is:
1340 #
1341 # largs = subset of [arg0, ..., arg(i)]
1342 # rargs = [arg(i+1), ..., arg(N-1)]
1343 #
1344 # If allow_interspersed_args is false, largs will always be
1345 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1346 # not a very interesting subset!
1347
Greg Wardeba20e62004-07-31 16:15:44 +00001348 def _match_long_opt(self, opt):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001349 """_match_long_opt(opt : string) -> string
1350
1351 Determine which long option string 'opt' matches, ie. which one
1352 it is an unambiguous abbrevation for. Raises BadOptionError if
1353 'opt' doesn't unambiguously match any long option string.
1354 """
1355 return _match_abbrev(opt, self._long_opt)
1356
Greg Wardeba20e62004-07-31 16:15:44 +00001357 def _process_long_opt(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001358 arg = rargs.pop(0)
1359
1360 # Value explicitly attached to arg? Pretend it's the next
1361 # argument.
1362 if "=" in arg:
1363 (opt, next_arg) = arg.split("=", 1)
1364 rargs.insert(0, next_arg)
Greg Wardeba20e62004-07-31 16:15:44 +00001365 had_explicit_value = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001366 else:
1367 opt = arg
Greg Wardeba20e62004-07-31 16:15:44 +00001368 had_explicit_value = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001369
1370 opt = self._match_long_opt(opt)
1371 option = self._long_opt[opt]
1372 if option.takes_value():
1373 nargs = option.nargs
1374 if len(rargs) < nargs:
1375 if nargs == 1:
Greg Wardeba20e62004-07-31 16:15:44 +00001376 self.error(_("%s option requires an argument") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001377 else:
Greg Wardeba20e62004-07-31 16:15:44 +00001378 self.error(_("%s option requires %d arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001379 % (opt, nargs))
1380 elif nargs == 1:
1381 value = rargs.pop(0)
1382 else:
1383 value = tuple(rargs[0:nargs])
1384 del rargs[0:nargs]
1385
1386 elif had_explicit_value:
Greg Wardeba20e62004-07-31 16:15:44 +00001387 self.error(_("%s option does not take a value") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001388
1389 else:
1390 value = None
1391
1392 option.process(opt, value, values, self)
1393
Greg Wardeba20e62004-07-31 16:15:44 +00001394 def _process_short_opts(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001395 arg = rargs.pop(0)
Greg Wardeba20e62004-07-31 16:15:44 +00001396 stop = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001397 i = 1
1398 for ch in arg[1:]:
1399 opt = "-" + ch
1400 option = self._short_opt.get(opt)
1401 i += 1 # we have consumed a character
1402
1403 if not option:
Greg Wardeba20e62004-07-31 16:15:44 +00001404 self.error(_("no such option: %s") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001405 if option.takes_value():
1406 # Any characters left in arg? Pretend they're the
1407 # next arg, and stop consuming characters of arg.
1408 if i < len(arg):
1409 rargs.insert(0, arg[i:])
Greg Wardeba20e62004-07-31 16:15:44 +00001410 stop = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001411
1412 nargs = option.nargs
1413 if len(rargs) < nargs:
1414 if nargs == 1:
Greg Wardeba20e62004-07-31 16:15:44 +00001415 self.error(_("%s option requires an argument") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001416 else:
Greg Wardeba20e62004-07-31 16:15:44 +00001417 self.error(_("%s option requires %d arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001418 % (opt, nargs))
1419 elif nargs == 1:
1420 value = rargs.pop(0)
1421 else:
1422 value = tuple(rargs[0:nargs])
1423 del rargs[0:nargs]
1424
1425 else: # option doesn't take a value
1426 value = None
1427
1428 option.process(opt, value, values, self)
1429
1430 if stop:
1431 break
1432
1433
1434 # -- Feedback methods ----------------------------------------------
1435
Greg Wardeba20e62004-07-31 16:15:44 +00001436 def get_prog_name(self):
1437 if self.prog is None:
1438 return os.path.basename(sys.argv[0])
1439 else:
1440 return self.prog
1441
1442 def expand_prog_name(self, s):
1443 return s.replace("%prog", self.get_prog_name())
1444
1445 def get_description(self):
1446 return self.expand_prog_name(self.description)
1447
Greg Ward48aa84b2004-10-27 02:20:04 +00001448 def exit(self, status=0, msg=None):
1449 if msg:
1450 sys.stderr.write(msg)
1451 sys.exit(status)
1452
Greg Wardeba20e62004-07-31 16:15:44 +00001453 def error(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001454 """error(msg : string)
1455
1456 Print a usage message incorporating 'msg' to stderr and exit.
1457 If you override this in a subclass, it should not return -- it
1458 should either exit or raise an exception.
1459 """
1460 self.print_usage(sys.stderr)
Greg Ward48aa84b2004-10-27 02:20:04 +00001461 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001462
Greg Wardeba20e62004-07-31 16:15:44 +00001463 def get_usage(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001464 if self.usage:
1465 return self.formatter.format_usage(
Greg Wardeba20e62004-07-31 16:15:44 +00001466 self.expand_prog_name(self.usage))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001467 else:
1468 return ""
1469
Greg Wardeba20e62004-07-31 16:15:44 +00001470 def print_usage(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001471 """print_usage(file : file = stdout)
1472
1473 Print the usage message for the current program (self.usage) to
1474 'file' (default stdout). Any occurence of the string "%prog" in
1475 self.usage is replaced with the name of the current program
1476 (basename of sys.argv[0]). Does nothing if self.usage is empty
1477 or not defined.
1478 """
1479 if self.usage:
1480 print >>file, self.get_usage()
1481
Greg Wardeba20e62004-07-31 16:15:44 +00001482 def get_version(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001483 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001484 return self.expand_prog_name(self.version)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001485 else:
1486 return ""
1487
Greg Wardeba20e62004-07-31 16:15:44 +00001488 def print_version(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001489 """print_version(file : file = stdout)
1490
1491 Print the version message for this program (self.version) to
1492 'file' (default stdout). As with print_usage(), any occurence
1493 of "%prog" in self.version is replaced by the current program's
1494 name. Does nothing if self.version is empty or undefined.
1495 """
1496 if self.version:
1497 print >>file, self.get_version()
1498
Greg Wardeba20e62004-07-31 16:15:44 +00001499 def format_option_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001500 if formatter is None:
1501 formatter = self.formatter
1502 formatter.store_option_strings(self)
1503 result = []
Greg Wardeba20e62004-07-31 16:15:44 +00001504 result.append(formatter.format_heading(_("options")))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001505 formatter.indent()
1506 if self.option_list:
1507 result.append(OptionContainer.format_option_help(self, formatter))
1508 result.append("\n")
1509 for group in self.option_groups:
1510 result.append(group.format_help(formatter))
1511 result.append("\n")
1512 formatter.dedent()
1513 # Drop the last "\n", or the header if no options or option groups:
1514 return "".join(result[:-1])
1515
Greg Wardeba20e62004-07-31 16:15:44 +00001516 def format_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001517 if formatter is None:
1518 formatter = self.formatter
1519 result = []
1520 if self.usage:
1521 result.append(self.get_usage() + "\n")
1522 if self.description:
1523 result.append(self.format_description(formatter) + "\n")
1524 result.append(self.format_option_help(formatter))
1525 return "".join(result)
1526
Greg Wardeba20e62004-07-31 16:15:44 +00001527 def print_help(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001528 """print_help(file : file = stdout)
1529
1530 Print an extended help message, listing all options and any
1531 help text provided with them, to 'file' (default stdout).
1532 """
1533 if file is None:
1534 file = sys.stdout
1535 file.write(self.format_help())
1536
1537# class OptionParser
1538
1539
Greg Wardeba20e62004-07-31 16:15:44 +00001540def _match_abbrev(s, wordmap):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001541 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1542
1543 Return the string key in 'wordmap' for which 's' is an unambiguous
1544 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1545 'words', raise BadOptionError.
1546 """
1547 # Is there an exact match?
1548 if wordmap.has_key(s):
1549 return s
1550 else:
1551 # Isolate all words with s as a prefix.
1552 possibilities = [word for word in wordmap.keys()
1553 if word.startswith(s)]
1554 # No exact match, so there had better be just one possibility.
1555 if len(possibilities) == 1:
1556 return possibilities[0]
1557 elif not possibilities:
Greg Wardeba20e62004-07-31 16:15:44 +00001558 raise BadOptionError(_("no such option: %s") % s)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001559 else:
1560 # More than one possible completion: ambiguous prefix.
Greg Wardeba20e62004-07-31 16:15:44 +00001561 raise BadOptionError(_("ambiguous option: %s (%s?)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001562 % (s, ", ".join(possibilities)))
1563
1564
1565# Some day, there might be many Option classes. As of Optik 1.3, the
1566# preferred way to instantiate Options is indirectly, via make_option(),
1567# which will become a factory function when there are many Option
1568# classes.
1569make_option = Option