blob: 2511595d6a3732c09b90ffaa57a1093e736727cb [file] [log] [blame]
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001"""A powerful, extensible, and easy-to-use option parser.
Guido van Rossumb9ba4582002-11-14 22:00:19 +00002
3By Greg Ward <gward@python.net>
4
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00005Originally distributed as Optik.
Greg Ward2492fcf2003-04-21 02:40:34 +00006
7For support, use the optik-users@lists.sourceforge.net mailing list
8(http://lists.sourceforge.net/lists/listinfo/optik-users).
Guido van Rossumb9ba4582002-11-14 22:00:19 +00009"""
10
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011__version__ = "1.5.3"
Greg Ward2492fcf2003-04-21 02:40:34 +000012
Greg Ward4656ed42003-05-08 01:38:52 +000013__all__ = ['Option',
14 'SUPPRESS_HELP',
15 'SUPPRESS_USAGE',
Greg Ward4656ed42003-05-08 01:38:52 +000016 'Values',
17 'OptionContainer',
18 'OptionGroup',
19 'OptionParser',
20 'HelpFormatter',
21 'IndentedHelpFormatter',
22 'TitledHelpFormatter',
23 'OptParseError',
24 'OptionError',
25 'OptionConflictError',
26 'OptionValueError',
27 'BadOptionError']
Greg Ward2492fcf2003-04-21 02:40:34 +000028
Guido van Rossumb9ba4582002-11-14 22:00:19 +000029__copyright__ = """
Thomas Wouters477c8d52006-05-27 19:21:47 +000030Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
31Copyright (c) 2002-2006 Python Software Foundation. All rights reserved.
Guido van Rossumb9ba4582002-11-14 22:00:19 +000032
33Redistribution and use in source and binary forms, with or without
34modification, are permitted provided that the following conditions are
35met:
36
37 * Redistributions of source code must retain the above copyright
38 notice, this list of conditions and the following disclaimer.
39
40 * Redistributions in binary form must reproduce the above copyright
41 notice, this list of conditions and the following disclaimer in the
42 documentation and/or other materials provided with the distribution.
43
44 * Neither the name of the author nor the names of its
45 contributors may be used to endorse or promote products derived from
46 this software without specific prior written permission.
47
48THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
49IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
50TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
51PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
52CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
53EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
54PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
55PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
56LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
57NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
58SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59"""
60
61import sys, os
Guido van Rossumb9ba4582002-11-14 22:00:19 +000062import textwrap
Greg Wardeba20e62004-07-31 16:15:44 +000063
64def _repr(self):
65 return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
66
67
68# This file was generated from:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000069# Id: option_parser.py 527 2006-07-23 15:21:30Z greg
70# Id: option.py 522 2006-06-11 16:22:03Z gward
71# Id: help.py 527 2006-07-23 15:21:30Z greg
Thomas Wouters477c8d52006-05-27 19:21:47 +000072# Id: errors.py 509 2006-04-20 00:58:24Z gward
73
74try:
75 from gettext import gettext
76except ImportError:
77 def gettext(message):
78 return message
79_ = gettext
80
Guido van Rossumb9ba4582002-11-14 22:00:19 +000081
Guido van Rossumb9ba4582002-11-14 22:00:19 +000082class OptParseError (Exception):
Greg Wardeba20e62004-07-31 16:15:44 +000083 def __init__(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000084 self.msg = msg
85
Greg Wardeba20e62004-07-31 16:15:44 +000086 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000087 return self.msg
88
Greg Ward2492fcf2003-04-21 02:40:34 +000089
Guido van Rossumb9ba4582002-11-14 22:00:19 +000090class OptionError (OptParseError):
91 """
92 Raised if an Option instance is created with invalid or
93 inconsistent arguments.
94 """
95
Greg Wardeba20e62004-07-31 16:15:44 +000096 def __init__(self, msg, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000097 self.msg = msg
98 self.option_id = str(option)
99
Greg Wardeba20e62004-07-31 16:15:44 +0000100 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000101 if self.option_id:
102 return "option %s: %s" % (self.option_id, self.msg)
103 else:
104 return self.msg
105
106class OptionConflictError (OptionError):
107 """
108 Raised if conflicting options are added to an OptionParser.
109 """
110
111class OptionValueError (OptParseError):
112 """
113 Raised if an invalid option value is encountered on the command
114 line.
115 """
116
117class BadOptionError (OptParseError):
118 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000119 Raised if an invalid option is seen on the command line.
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000120 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000121 def __init__(self, opt_str):
122 self.opt_str = opt_str
123
124 def __str__(self):
125 return _("no such option: %s") % self.opt_str
126
127class AmbiguousOptionError (BadOptionError):
128 """
129 Raised if an ambiguous option is seen on the command line.
130 """
131 def __init__(self, opt_str, possibilities):
132 BadOptionError.__init__(self, opt_str)
133 self.possibilities = possibilities
134
135 def __str__(self):
136 return (_("ambiguous option: %s (%s?)")
137 % (self.opt_str, ", ".join(self.possibilities)))
Greg Ward2492fcf2003-04-21 02:40:34 +0000138
139
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000140class HelpFormatter:
141
142 """
143 Abstract base class for formatting option help. OptionParser
144 instances should use one of the HelpFormatter subclasses for
145 formatting help; by default IndentedHelpFormatter is used.
146
147 Instance attributes:
Greg Wardeba20e62004-07-31 16:15:44 +0000148 parser : OptionParser
149 the controlling OptionParser instance
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000150 indent_increment : int
151 the number of columns to indent per nesting level
152 max_help_position : int
153 the maximum starting column for option help text
154 help_position : int
155 the calculated starting column for option help text;
156 initially the same as the maximum
157 width : int
Greg Wardeba20e62004-07-31 16:15:44 +0000158 total number of columns for output (pass None to constructor for
159 this value to be taken from the $COLUMNS environment variable)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000160 level : int
161 current indentation level
162 current_indent : int
163 current indentation level (in columns)
164 help_width : int
165 number of columns available for option help text (calculated)
Greg Wardeba20e62004-07-31 16:15:44 +0000166 default_tag : str
167 text to replace with each option's default value, "%default"
168 by default. Set to false value to disable default value expansion.
169 option_strings : { Option : str }
170 maps Option instances to the snippet of help text explaining
171 the syntax of that option, e.g. "-h, --help" or
172 "-fFILE, --file=FILE"
173 _short_opt_fmt : str
174 format string controlling how short options with values are
175 printed in help text. Must be either "%s%s" ("-fFILE") or
176 "%s %s" ("-f FILE"), because those are the two syntaxes that
177 Optik supports.
178 _long_opt_fmt : str
179 similar but for long options; must be either "%s %s" ("--file FILE")
180 or "%s=%s" ("--file=FILE").
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000181 """
182
Greg Wardeba20e62004-07-31 16:15:44 +0000183 NO_DEFAULT_VALUE = "none"
184
185 def __init__(self,
186 indent_increment,
187 max_help_position,
188 width,
189 short_first):
190 self.parser = None
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000191 self.indent_increment = indent_increment
192 self.help_position = self.max_help_position = max_help_position
Greg Wardeba20e62004-07-31 16:15:44 +0000193 if width is None:
194 try:
195 width = int(os.environ['COLUMNS'])
196 except (KeyError, ValueError):
197 width = 80
198 width -= 2
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000199 self.width = width
200 self.current_indent = 0
201 self.level = 0
Greg Wardeba20e62004-07-31 16:15:44 +0000202 self.help_width = None # computed later
Greg Ward2492fcf2003-04-21 02:40:34 +0000203 self.short_first = short_first
Greg Wardeba20e62004-07-31 16:15:44 +0000204 self.default_tag = "%default"
205 self.option_strings = {}
206 self._short_opt_fmt = "%s %s"
207 self._long_opt_fmt = "%s=%s"
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000208
Greg Wardeba20e62004-07-31 16:15:44 +0000209 def set_parser(self, parser):
210 self.parser = parser
211
212 def set_short_opt_delimiter(self, delim):
213 if delim not in ("", " "):
214 raise ValueError(
215 "invalid metavar delimiter for short options: %r" % delim)
216 self._short_opt_fmt = "%s" + delim + "%s"
217
218 def set_long_opt_delimiter(self, delim):
219 if delim not in ("=", " "):
220 raise ValueError(
221 "invalid metavar delimiter for long options: %r" % delim)
222 self._long_opt_fmt = "%s" + delim + "%s"
223
224 def indent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000225 self.current_indent += self.indent_increment
226 self.level += 1
227
Greg Wardeba20e62004-07-31 16:15:44 +0000228 def dedent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000229 self.current_indent -= self.indent_increment
230 assert self.current_indent >= 0, "Indent decreased below 0."
231 self.level -= 1
232
Greg Wardeba20e62004-07-31 16:15:44 +0000233 def format_usage(self, usage):
Collin Winterce36ad82007-08-30 01:19:48 +0000234 raise NotImplementedError("subclasses must implement")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000235
Greg Wardeba20e62004-07-31 16:15:44 +0000236 def format_heading(self, heading):
Collin Winterce36ad82007-08-30 01:19:48 +0000237 raise NotImplementedError("subclasses must implement")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000238
Thomas Wouters477c8d52006-05-27 19:21:47 +0000239 def _format_text(self, text):
240 """
241 Format a paragraph of free-form text for inclusion in the
242 help output at the current indentation level.
243 """
244 text_width = self.width - self.current_indent
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000245 indent = " "*self.current_indent
Thomas Wouters477c8d52006-05-27 19:21:47 +0000246 return textwrap.fill(text,
247 text_width,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000248 initial_indent=indent,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000249 subsequent_indent=indent)
250
251 def format_description(self, description):
252 if description:
253 return self._format_text(description) + "\n"
254 else:
255 return ""
256
257 def format_epilog(self, epilog):
258 if epilog:
259 return "\n" + self._format_text(epilog) + "\n"
260 else:
261 return ""
262
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000263
Greg Wardeba20e62004-07-31 16:15:44 +0000264 def expand_default(self, option):
265 if self.parser is None or not self.default_tag:
266 return option.help
267
268 default_value = self.parser.defaults.get(option.dest)
269 if default_value is NO_DEFAULT or default_value is None:
270 default_value = self.NO_DEFAULT_VALUE
271
272 return option.help.replace(self.default_tag, str(default_value))
273
274 def format_option(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000275 # The help for each option consists of two parts:
276 # * the opt strings and metavars
277 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
278 # * the user-supplied help string
279 # eg. ("turn on expert mode", "read data from FILENAME")
280 #
281 # If possible, we write both of these on the same line:
282 # -x turn on expert mode
283 #
284 # But if the opt string list is too long, we put the help
285 # string on a second line, indented to the same column it would
286 # start in if it fit on the first line.
287 # -fFILENAME, --file=FILENAME
288 # read data from FILENAME
289 result = []
Greg Wardeba20e62004-07-31 16:15:44 +0000290 opts = self.option_strings[option]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000291 opt_width = self.help_position - self.current_indent - 2
292 if len(opts) > opt_width:
293 opts = "%*s%s\n" % (self.current_indent, "", opts)
294 indent_first = self.help_position
295 else: # start help on same line as opts
296 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
297 indent_first = 0
298 result.append(opts)
299 if option.help:
Greg Wardeba20e62004-07-31 16:15:44 +0000300 help_text = self.expand_default(option)
301 help_lines = textwrap.wrap(help_text, self.help_width)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000302 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
303 result.extend(["%*s%s\n" % (self.help_position, "", line)
304 for line in help_lines[1:]])
305 elif opts[-1] != "\n":
306 result.append("\n")
307 return "".join(result)
308
Greg Wardeba20e62004-07-31 16:15:44 +0000309 def store_option_strings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000310 self.indent()
311 max_len = 0
312 for opt in parser.option_list:
313 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000314 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000315 max_len = max(max_len, len(strings) + self.current_indent)
316 self.indent()
317 for group in parser.option_groups:
318 for opt in group.option_list:
319 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000320 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000321 max_len = max(max_len, len(strings) + self.current_indent)
322 self.dedent()
323 self.dedent()
324 self.help_position = min(max_len + 2, self.max_help_position)
Greg Wardeba20e62004-07-31 16:15:44 +0000325 self.help_width = self.width - self.help_position
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000326
Greg Wardeba20e62004-07-31 16:15:44 +0000327 def format_option_strings(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000328 """Return a comma-separated list of option strings & metavariables."""
Greg Ward2492fcf2003-04-21 02:40:34 +0000329 if option.takes_value():
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000330 metavar = option.metavar or option.dest.upper()
Greg Wardeba20e62004-07-31 16:15:44 +0000331 short_opts = [self._short_opt_fmt % (sopt, metavar)
332 for sopt in option._short_opts]
333 long_opts = [self._long_opt_fmt % (lopt, metavar)
334 for lopt in option._long_opts]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000335 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000336 short_opts = option._short_opts
337 long_opts = option._long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000338
Greg Ward2492fcf2003-04-21 02:40:34 +0000339 if self.short_first:
340 opts = short_opts + long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000341 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000342 opts = long_opts + short_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000343
Greg Ward2492fcf2003-04-21 02:40:34 +0000344 return ", ".join(opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000345
346class IndentedHelpFormatter (HelpFormatter):
347 """Format help with indented section bodies.
348 """
349
Greg Wardeba20e62004-07-31 16:15:44 +0000350 def __init__(self,
351 indent_increment=2,
352 max_help_position=24,
353 width=None,
354 short_first=1):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000355 HelpFormatter.__init__(
356 self, indent_increment, max_help_position, width, short_first)
357
Greg Wardeba20e62004-07-31 16:15:44 +0000358 def format_usage(self, usage):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000359 return _("Usage: %s\n") % usage
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000360
Greg Wardeba20e62004-07-31 16:15:44 +0000361 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000362 return "%*s%s:\n" % (self.current_indent, "", heading)
363
364
365class TitledHelpFormatter (HelpFormatter):
366 """Format help with underlined section headers.
367 """
368
Greg Wardeba20e62004-07-31 16:15:44 +0000369 def __init__(self,
370 indent_increment=0,
371 max_help_position=24,
372 width=None,
373 short_first=0):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000374 HelpFormatter.__init__ (
375 self, indent_increment, max_help_position, width, short_first)
376
Greg Wardeba20e62004-07-31 16:15:44 +0000377 def format_usage(self, usage):
378 return "%s %s\n" % (self.format_heading(_("Usage")), usage)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000379
Greg Wardeba20e62004-07-31 16:15:44 +0000380 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000381 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
Greg Ward2492fcf2003-04-21 02:40:34 +0000382
383
Thomas Wouters477c8d52006-05-27 19:21:47 +0000384def _parse_num(val, type):
385 if val[:2].lower() == "0x": # hexadecimal
386 radix = 16
387 elif val[:2].lower() == "0b": # binary
388 radix = 2
389 val = val[2:] or "0" # have to remove "0b" prefix
390 elif val[:1] == "0": # octal
391 radix = 8
392 else: # decimal
393 radix = 10
394
395 return type(val, radix)
396
397def _parse_int(val):
398 return _parse_num(val, int)
399
400def _parse_long(val):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000401 return _parse_num(val, int)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000402
403_builtin_cvt = { "int" : (_parse_int, _("integer")),
404 "long" : (_parse_long, _("long integer")),
Greg Wardeba20e62004-07-31 16:15:44 +0000405 "float" : (float, _("floating-point")),
406 "complex" : (complex, _("complex")) }
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000407
Greg Wardeba20e62004-07-31 16:15:44 +0000408def check_builtin(option, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000409 (cvt, what) = _builtin_cvt[option.type]
410 try:
411 return cvt(value)
412 except ValueError:
413 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000414 _("option %s: invalid %s value: %r") % (opt, what, value))
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000415
416def check_choice(option, opt, value):
417 if value in option.choices:
418 return value
419 else:
420 choices = ", ".join(map(repr, option.choices))
421 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000422 _("option %s: invalid choice: %r (choose from %s)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000423 % (opt, value, choices))
424
425# Not supplying a default is different from a default of None,
426# so we need an explicit "not supplied" value.
Greg Wardeba20e62004-07-31 16:15:44 +0000427NO_DEFAULT = ("NO", "DEFAULT")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000428
429
430class Option:
431 """
432 Instance attributes:
433 _short_opts : [string]
434 _long_opts : [string]
435
436 action : string
437 type : string
438 dest : string
439 default : any
440 nargs : int
441 const : any
442 choices : [string]
443 callback : function
444 callback_args : (any*)
445 callback_kwargs : { string : any }
446 help : string
447 metavar : string
448 """
449
450 # The list of instance attributes that may be set through
451 # keyword args to the constructor.
452 ATTRS = ['action',
453 'type',
454 'dest',
455 'default',
456 'nargs',
457 'const',
458 'choices',
459 'callback',
460 'callback_args',
461 'callback_kwargs',
462 'help',
463 'metavar']
464
465 # The set of actions allowed by option parsers. Explicitly listed
466 # here so the constructor can validate its arguments.
467 ACTIONS = ("store",
468 "store_const",
469 "store_true",
470 "store_false",
471 "append",
Thomas Wouters477c8d52006-05-27 19:21:47 +0000472 "append_const",
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000473 "count",
474 "callback",
475 "help",
476 "version")
477
478 # The set of actions that involve storing a value somewhere;
479 # also listed just for constructor argument validation. (If
480 # the action is one of these, there must be a destination.)
481 STORE_ACTIONS = ("store",
482 "store_const",
483 "store_true",
484 "store_false",
485 "append",
Thomas Wouters477c8d52006-05-27 19:21:47 +0000486 "append_const",
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000487 "count")
488
489 # The set of actions for which it makes sense to supply a value
Greg Ward48aa84b2004-10-27 02:20:04 +0000490 # type, ie. which may consume an argument from the command line.
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000491 TYPED_ACTIONS = ("store",
492 "append",
493 "callback")
494
Greg Ward48aa84b2004-10-27 02:20:04 +0000495 # The set of actions which *require* a value type, ie. that
496 # always consume an argument from the command line.
497 ALWAYS_TYPED_ACTIONS = ("store",
498 "append")
499
Thomas Wouters477c8d52006-05-27 19:21:47 +0000500 # The set of actions which take a 'const' attribute.
501 CONST_ACTIONS = ("store_const",
502 "append_const")
503
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000504 # The set of known types for option parsers. Again, listed here for
505 # constructor argument validation.
506 TYPES = ("string", "int", "long", "float", "complex", "choice")
507
508 # Dictionary of argument checking functions, which convert and
509 # validate option arguments according to the option type.
510 #
511 # Signature of checking functions is:
512 # check(option : Option, opt : string, value : string) -> any
513 # where
514 # option is the Option instance calling the checker
515 # opt is the actual option seen on the command-line
516 # (eg. "-a", "--file")
517 # value is the option argument seen on the command-line
518 #
519 # The return value should be in the appropriate Python type
520 # for option.type -- eg. an integer if option.type == "int".
521 #
522 # If no checker is defined for a type, arguments will be
523 # unchecked and remain strings.
524 TYPE_CHECKER = { "int" : check_builtin,
525 "long" : check_builtin,
526 "float" : check_builtin,
Greg Wardeba20e62004-07-31 16:15:44 +0000527 "complex": check_builtin,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000528 "choice" : check_choice,
529 }
530
531
532 # CHECK_METHODS is a list of unbound method objects; they are called
533 # by the constructor, in order, after all attributes are
534 # initialized. The list is created and filled in later, after all
535 # the methods are actually defined. (I just put it here because I
536 # like to define and document all class attributes in the same
537 # place.) Subclasses that add another _check_*() method should
538 # define their own CHECK_METHODS list that adds their check method
539 # to those from this class.
540 CHECK_METHODS = None
541
542
543 # -- Constructor/initialization methods ----------------------------
544
Greg Wardeba20e62004-07-31 16:15:44 +0000545 def __init__(self, *opts, **attrs):
Greg Ward2492fcf2003-04-21 02:40:34 +0000546 # Set _short_opts, _long_opts attrs from 'opts' tuple.
547 # Have to be set now, in case no option strings are supplied.
548 self._short_opts = []
549 self._long_opts = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000550 opts = self._check_opt_strings(opts)
551 self._set_opt_strings(opts)
552
553 # Set all other attrs (action, type, etc.) from 'attrs' dict
554 self._set_attrs(attrs)
555
556 # Check all the attributes we just set. There are lots of
557 # complicated interdependencies, but luckily they can be farmed
558 # out to the _check_*() methods listed in CHECK_METHODS -- which
559 # could be handy for subclasses! The one thing these all share
560 # is that they raise OptionError if they discover a problem.
561 for checker in self.CHECK_METHODS:
562 checker(self)
563
Greg Wardeba20e62004-07-31 16:15:44 +0000564 def _check_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000565 # Filter out None because early versions of Optik had exactly
566 # one short option and one long option, either of which
567 # could be None.
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000568 opts = [opt for opt in opts if opt]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000569 if not opts:
Greg Ward2492fcf2003-04-21 02:40:34 +0000570 raise TypeError("at least one option string must be supplied")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000571 return opts
572
Greg Wardeba20e62004-07-31 16:15:44 +0000573 def _set_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000574 for opt in opts:
575 if len(opt) < 2:
576 raise OptionError(
577 "invalid option string %r: "
578 "must be at least two characters long" % opt, self)
579 elif len(opt) == 2:
580 if not (opt[0] == "-" and opt[1] != "-"):
581 raise OptionError(
582 "invalid short option string %r: "
583 "must be of the form -x, (x any non-dash char)" % opt,
584 self)
585 self._short_opts.append(opt)
586 else:
587 if not (opt[0:2] == "--" and opt[2] != "-"):
588 raise OptionError(
589 "invalid long option string %r: "
590 "must start with --, followed by non-dash" % opt,
591 self)
592 self._long_opts.append(opt)
593
Greg Wardeba20e62004-07-31 16:15:44 +0000594 def _set_attrs(self, attrs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000595 for attr in self.ATTRS:
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000596 if attr in attrs:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000597 setattr(self, attr, attrs[attr])
598 del attrs[attr]
599 else:
600 if attr == 'default':
601 setattr(self, attr, NO_DEFAULT)
602 else:
603 setattr(self, attr, None)
604 if attrs:
Georg Brandlc2d9d7f2007-02-11 23:06:17 +0000605 attrs = sorted(attrs.keys())
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000606 raise OptionError(
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000607 "invalid keyword arguments: %s" % ", ".join(attrs),
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000608 self)
609
610
611 # -- Constructor validation methods --------------------------------
612
Greg Wardeba20e62004-07-31 16:15:44 +0000613 def _check_action(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000614 if self.action is None:
615 self.action = "store"
616 elif self.action not in self.ACTIONS:
617 raise OptionError("invalid action: %r" % self.action, self)
618
Greg Wardeba20e62004-07-31 16:15:44 +0000619 def _check_type(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000620 if self.type is None:
Greg Ward48aa84b2004-10-27 02:20:04 +0000621 if self.action in self.ALWAYS_TYPED_ACTIONS:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000622 if self.choices is not None:
623 # The "choices" attribute implies "choice" type.
624 self.type = "choice"
625 else:
626 # No type given? "string" is the most sensible default.
627 self.type = "string"
628 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000629 # Allow type objects or builtin type conversion functions
630 # (int, str, etc.) as an alternative to their names. (The
Georg Brandl1a3284e2007-12-02 09:40:06 +0000631 # complicated check of builtins is only necessary for
Thomas Wouters477c8d52006-05-27 19:21:47 +0000632 # Python 2.1 and earlier, and is short-circuited by the
633 # first check on modern Pythons.)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000634 import builtins
Guido van Rossum13257902007-06-07 23:15:56 +0000635 if ( isinstance(self.type, type) or
Thomas Wouters477c8d52006-05-27 19:21:47 +0000636 (hasattr(self.type, "__name__") and
Georg Brandl1a3284e2007-12-02 09:40:06 +0000637 getattr(builtins, self.type.__name__, None) is self.type) ):
Greg Wardeba20e62004-07-31 16:15:44 +0000638 self.type = self.type.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000639
Greg Wardeba20e62004-07-31 16:15:44 +0000640 if self.type == "str":
641 self.type = "string"
642
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000643 if self.type not in self.TYPES:
644 raise OptionError("invalid option type: %r" % self.type, self)
645 if self.action not in self.TYPED_ACTIONS:
646 raise OptionError(
647 "must not supply a type for action %r" % self.action, self)
648
649 def _check_choice(self):
650 if self.type == "choice":
651 if self.choices is None:
652 raise OptionError(
653 "must supply a list of choices for type 'choice'", self)
Guido van Rossum13257902007-06-07 23:15:56 +0000654 elif not isinstance(self.choices, (tuple, list)):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000655 raise OptionError(
656 "choices must be a list of strings ('%s' supplied)"
657 % str(type(self.choices)).split("'")[1], self)
658 elif self.choices is not None:
659 raise OptionError(
660 "must not supply choices for type %r" % self.type, self)
661
Greg Wardeba20e62004-07-31 16:15:44 +0000662 def _check_dest(self):
663 # No destination given, and we need one for this action. The
664 # self.type check is for callbacks that take a value.
665 takes_value = (self.action in self.STORE_ACTIONS or
666 self.type is not None)
667 if self.dest is None and takes_value:
668
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000669 # Glean a destination from the first long option string,
670 # or from the first short option string if no long options.
671 if self._long_opts:
672 # eg. "--foo-bar" -> "foo_bar"
673 self.dest = self._long_opts[0][2:].replace('-', '_')
674 else:
675 self.dest = self._short_opts[0][1]
676
Greg Wardeba20e62004-07-31 16:15:44 +0000677 def _check_const(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000678 if self.action not in self.CONST_ACTIONS and self.const is not None:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000679 raise OptionError(
680 "'const' must not be supplied for action %r" % self.action,
681 self)
682
Greg Wardeba20e62004-07-31 16:15:44 +0000683 def _check_nargs(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000684 if self.action in self.TYPED_ACTIONS:
685 if self.nargs is None:
686 self.nargs = 1
687 elif self.nargs is not None:
688 raise OptionError(
689 "'nargs' must not be supplied for action %r" % self.action,
690 self)
691
Greg Wardeba20e62004-07-31 16:15:44 +0000692 def _check_callback(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000693 if self.action == "callback":
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000694 if not hasattr(self.callback, '__call__'):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000695 raise OptionError(
696 "callback not callable: %r" % self.callback, self)
697 if (self.callback_args is not None and
Guido van Rossum13257902007-06-07 23:15:56 +0000698 not isinstance(self.callback_args, tuple)):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000699 raise OptionError(
700 "callback_args, if supplied, must be a tuple: not %r"
701 % self.callback_args, self)
702 if (self.callback_kwargs is not None and
Guido van Rossum13257902007-06-07 23:15:56 +0000703 not isinstance(self.callback_kwargs, dict)):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000704 raise OptionError(
705 "callback_kwargs, if supplied, must be a dict: not %r"
706 % self.callback_kwargs, self)
707 else:
708 if self.callback is not None:
709 raise OptionError(
710 "callback supplied (%r) for non-callback option"
711 % self.callback, self)
712 if self.callback_args is not None:
713 raise OptionError(
714 "callback_args supplied for non-callback option", self)
715 if self.callback_kwargs is not None:
716 raise OptionError(
717 "callback_kwargs supplied for non-callback option", self)
718
719
720 CHECK_METHODS = [_check_action,
721 _check_type,
722 _check_choice,
723 _check_dest,
724 _check_const,
725 _check_nargs,
726 _check_callback]
727
728
729 # -- Miscellaneous methods -----------------------------------------
730
Greg Wardeba20e62004-07-31 16:15:44 +0000731 def __str__(self):
Greg Ward2492fcf2003-04-21 02:40:34 +0000732 return "/".join(self._short_opts + self._long_opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000733
Greg Wardeba20e62004-07-31 16:15:44 +0000734 __repr__ = _repr
735
736 def takes_value(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000737 return self.type is not None
738
Greg Wardeba20e62004-07-31 16:15:44 +0000739 def get_opt_string(self):
740 if self._long_opts:
741 return self._long_opts[0]
742 else:
743 return self._short_opts[0]
744
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000745
746 # -- Processing methods --------------------------------------------
747
Greg Wardeba20e62004-07-31 16:15:44 +0000748 def check_value(self, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000749 checker = self.TYPE_CHECKER.get(self.type)
750 if checker is None:
751 return value
752 else:
753 return checker(self, opt, value)
754
Greg Wardeba20e62004-07-31 16:15:44 +0000755 def convert_value(self, opt, value):
756 if value is not None:
757 if self.nargs == 1:
758 return self.check_value(opt, value)
759 else:
760 return tuple([self.check_value(opt, v) for v in value])
761
762 def process(self, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000763
764 # First, convert the value(s) to the right type. Howl if any
765 # value(s) are bogus.
Greg Wardeba20e62004-07-31 16:15:44 +0000766 value = self.convert_value(opt, value)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000767
768 # And then take whatever action is expected of us.
769 # This is a separate method to make life easier for
770 # subclasses to add new actions.
771 return self.take_action(
772 self.action, self.dest, opt, value, values, parser)
773
Greg Wardeba20e62004-07-31 16:15:44 +0000774 def take_action(self, action, dest, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000775 if action == "store":
776 setattr(values, dest, value)
777 elif action == "store_const":
778 setattr(values, dest, self.const)
779 elif action == "store_true":
Greg Ward2492fcf2003-04-21 02:40:34 +0000780 setattr(values, dest, True)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000781 elif action == "store_false":
Greg Ward2492fcf2003-04-21 02:40:34 +0000782 setattr(values, dest, False)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000783 elif action == "append":
784 values.ensure_value(dest, []).append(value)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000785 elif action == "append_const":
786 values.ensure_value(dest, []).append(self.const)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000787 elif action == "count":
788 setattr(values, dest, values.ensure_value(dest, 0) + 1)
789 elif action == "callback":
790 args = self.callback_args or ()
791 kwargs = self.callback_kwargs or {}
792 self.callback(self, opt, value, parser, *args, **kwargs)
793 elif action == "help":
794 parser.print_help()
Greg Ward48aa84b2004-10-27 02:20:04 +0000795 parser.exit()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000796 elif action == "version":
797 parser.print_version()
Greg Ward48aa84b2004-10-27 02:20:04 +0000798 parser.exit()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000799 else:
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000800 raise ValueError("unknown action %r" % self.action)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000801
802 return 1
803
804# class Option
Greg Ward2492fcf2003-04-21 02:40:34 +0000805
806
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000807SUPPRESS_HELP = "SUPPRESS"+"HELP"
808SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
809
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000810class Values:
811
Greg Wardeba20e62004-07-31 16:15:44 +0000812 def __init__(self, defaults=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000813 if defaults:
814 for (attr, val) in defaults.items():
815 setattr(self, attr, val)
816
Greg Wardeba20e62004-07-31 16:15:44 +0000817 def __str__(self):
818 return str(self.__dict__)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000819
Greg Wardeba20e62004-07-31 16:15:44 +0000820 __repr__ = _repr
821
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000822 def __eq__(self, other):
Greg Wardeba20e62004-07-31 16:15:44 +0000823 if isinstance(other, Values):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000824 return self.__dict__ == other.__dict__
Guido van Rossum13257902007-06-07 23:15:56 +0000825 elif isinstance(other, dict):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000826 return self.__dict__ == other
Greg Wardeba20e62004-07-31 16:15:44 +0000827 else:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000828 return NotImplemented
Greg Wardeba20e62004-07-31 16:15:44 +0000829
830 def _update_careful(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000831 """
832 Update the option values from an arbitrary dictionary, but only
833 use keys from dict that already have a corresponding attribute
834 in self. Any keys in dict without a corresponding attribute
835 are silently ignored.
836 """
837 for attr in dir(self):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000838 if attr in dict:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000839 dval = dict[attr]
840 if dval is not None:
841 setattr(self, attr, dval)
842
Greg Wardeba20e62004-07-31 16:15:44 +0000843 def _update_loose(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000844 """
845 Update the option values from an arbitrary dictionary,
846 using all keys from the dictionary regardless of whether
847 they have a corresponding attribute in self or not.
848 """
849 self.__dict__.update(dict)
850
Greg Wardeba20e62004-07-31 16:15:44 +0000851 def _update(self, dict, mode):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000852 if mode == "careful":
853 self._update_careful(dict)
854 elif mode == "loose":
855 self._update_loose(dict)
856 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000857 raise ValueError("invalid update mode: %r" % mode)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000858
Greg Wardeba20e62004-07-31 16:15:44 +0000859 def read_module(self, modname, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000860 __import__(modname)
861 mod = sys.modules[modname]
862 self._update(vars(mod), mode)
863
Greg Wardeba20e62004-07-31 16:15:44 +0000864 def read_file(self, filename, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000865 vars = {}
Neal Norwitz01688022007-08-12 00:43:29 +0000866 exec(open(filename).read(), vars)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000867 self._update(vars, mode)
868
Greg Wardeba20e62004-07-31 16:15:44 +0000869 def ensure_value(self, attr, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000870 if not hasattr(self, attr) or getattr(self, attr) is None:
871 setattr(self, attr, value)
872 return getattr(self, attr)
873
874
875class OptionContainer:
876
877 """
878 Abstract base class.
879
880 Class attributes:
881 standard_option_list : [Option]
882 list of standard options that will be accepted by all instances
883 of this parser class (intended to be overridden by subclasses).
884
885 Instance attributes:
886 option_list : [Option]
887 the list of Option objects contained by this OptionContainer
888 _short_opt : { string : Option }
889 dictionary mapping short option strings, eg. "-f" or "-X",
890 to the Option instances that implement them. If an Option
891 has multiple short option strings, it will appears in this
892 dictionary multiple times. [1]
893 _long_opt : { string : Option }
894 dictionary mapping long option strings, eg. "--file" or
895 "--exclude", to the Option instances that implement them.
896 Again, a given Option can occur multiple times in this
897 dictionary. [1]
898 defaults : { string : any }
899 dictionary mapping option destination names to default
900 values for each destination [1]
901
902 [1] These mappings are common to (shared by) all components of the
903 controlling OptionParser, where they are initially created.
904
905 """
906
Greg Wardeba20e62004-07-31 16:15:44 +0000907 def __init__(self, option_class, conflict_handler, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000908 # Initialize the option list and related data structures.
909 # This method must be provided by subclasses, and it must
910 # initialize at least the following instance attributes:
911 # option_list, _short_opt, _long_opt, defaults.
912 self._create_option_list()
913
914 self.option_class = option_class
915 self.set_conflict_handler(conflict_handler)
916 self.set_description(description)
917
Greg Wardeba20e62004-07-31 16:15:44 +0000918 def _create_option_mappings(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000919 # For use by OptionParser constructor -- create the master
920 # option mappings used by this OptionParser and all
921 # OptionGroups that it owns.
922 self._short_opt = {} # single letter -> Option instance
923 self._long_opt = {} # long option -> Option instance
924 self.defaults = {} # maps option dest -> default value
925
926
Greg Wardeba20e62004-07-31 16:15:44 +0000927 def _share_option_mappings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000928 # For use by OptionGroup constructor -- use shared option
929 # mappings from the OptionParser that owns this OptionGroup.
930 self._short_opt = parser._short_opt
931 self._long_opt = parser._long_opt
932 self.defaults = parser.defaults
933
Greg Wardeba20e62004-07-31 16:15:44 +0000934 def set_conflict_handler(self, handler):
Greg Ward48aa84b2004-10-27 02:20:04 +0000935 if handler not in ("error", "resolve"):
Collin Winterce36ad82007-08-30 01:19:48 +0000936 raise ValueError("invalid conflict_resolution value %r" % handler)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000937 self.conflict_handler = handler
938
Greg Wardeba20e62004-07-31 16:15:44 +0000939 def set_description(self, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000940 self.description = description
941
Greg Wardeba20e62004-07-31 16:15:44 +0000942 def get_description(self):
943 return self.description
944
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000945
Thomas Wouters477c8d52006-05-27 19:21:47 +0000946 def destroy(self):
947 """see OptionParser.destroy()."""
948 del self._short_opt
949 del self._long_opt
950 del self.defaults
951
952
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000953 # -- Option-adding methods -----------------------------------------
954
Greg Wardeba20e62004-07-31 16:15:44 +0000955 def _check_conflict(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000956 conflict_opts = []
957 for opt in option._short_opts:
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000958 if opt in self._short_opt:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000959 conflict_opts.append((opt, self._short_opt[opt]))
960 for opt in option._long_opts:
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000961 if opt in self._long_opt:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000962 conflict_opts.append((opt, self._long_opt[opt]))
963
964 if conflict_opts:
965 handler = self.conflict_handler
Greg Ward48aa84b2004-10-27 02:20:04 +0000966 if handler == "error":
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000967 raise OptionConflictError(
968 "conflicting option string(s): %s"
969 % ", ".join([co[0] for co in conflict_opts]),
970 option)
Greg Ward48aa84b2004-10-27 02:20:04 +0000971 elif handler == "resolve":
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000972 for (opt, c_option) in conflict_opts:
973 if opt.startswith("--"):
974 c_option._long_opts.remove(opt)
975 del self._long_opt[opt]
976 else:
977 c_option._short_opts.remove(opt)
978 del self._short_opt[opt]
979 if not (c_option._short_opts or c_option._long_opts):
980 c_option.container.option_list.remove(c_option)
981
Greg Wardeba20e62004-07-31 16:15:44 +0000982 def add_option(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000983 """add_option(Option)
984 add_option(opt_str, ..., kwarg=val, ...)
985 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000986 if isinstance(args[0], str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000987 option = self.option_class(*args, **kwargs)
988 elif len(args) == 1 and not kwargs:
989 option = args[0]
990 if not isinstance(option, Option):
Collin Winterce36ad82007-08-30 01:19:48 +0000991 raise TypeError("not an Option instance: %r" % option)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000992 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000993 raise TypeError("invalid arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000994
995 self._check_conflict(option)
996
997 self.option_list.append(option)
998 option.container = self
999 for opt in option._short_opts:
1000 self._short_opt[opt] = option
1001 for opt in option._long_opts:
1002 self._long_opt[opt] = option
1003
1004 if option.dest is not None: # option has a dest, we need a default
1005 if option.default is not NO_DEFAULT:
1006 self.defaults[option.dest] = option.default
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001007 elif option.dest not in self.defaults:
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001008 self.defaults[option.dest] = None
1009
1010 return option
1011
Greg Wardeba20e62004-07-31 16:15:44 +00001012 def add_options(self, option_list):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001013 for option in option_list:
1014 self.add_option(option)
1015
1016 # -- Option query/removal methods ----------------------------------
1017
Greg Wardeba20e62004-07-31 16:15:44 +00001018 def get_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001019 return (self._short_opt.get(opt_str) or
1020 self._long_opt.get(opt_str))
1021
Greg Wardeba20e62004-07-31 16:15:44 +00001022 def has_option(self, opt_str):
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001023 return (opt_str in self._short_opt or
Guido van Rossum93662412006-08-19 16:09:41 +00001024 opt_str in self._long_opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001025
Greg Wardeba20e62004-07-31 16:15:44 +00001026 def remove_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001027 option = self._short_opt.get(opt_str)
1028 if option is None:
1029 option = self._long_opt.get(opt_str)
1030 if option is None:
1031 raise ValueError("no such option %r" % opt_str)
1032
1033 for opt in option._short_opts:
1034 del self._short_opt[opt]
1035 for opt in option._long_opts:
1036 del self._long_opt[opt]
1037 option.container.option_list.remove(option)
1038
1039
1040 # -- Help-formatting methods ---------------------------------------
1041
Greg Wardeba20e62004-07-31 16:15:44 +00001042 def format_option_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001043 if not self.option_list:
1044 return ""
1045 result = []
1046 for option in self.option_list:
1047 if not option.help is SUPPRESS_HELP:
1048 result.append(formatter.format_option(option))
1049 return "".join(result)
1050
Greg Wardeba20e62004-07-31 16:15:44 +00001051 def format_description(self, formatter):
1052 return formatter.format_description(self.get_description())
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001053
Greg Wardeba20e62004-07-31 16:15:44 +00001054 def format_help(self, formatter):
1055 result = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001056 if self.description:
Greg Wardeba20e62004-07-31 16:15:44 +00001057 result.append(self.format_description(formatter))
1058 if self.option_list:
1059 result.append(self.format_option_help(formatter))
1060 return "\n".join(result)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001061
1062
1063class OptionGroup (OptionContainer):
1064
Greg Wardeba20e62004-07-31 16:15:44 +00001065 def __init__(self, parser, title, description=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001066 self.parser = parser
1067 OptionContainer.__init__(
1068 self, parser.option_class, parser.conflict_handler, description)
1069 self.title = title
1070
Greg Wardeba20e62004-07-31 16:15:44 +00001071 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001072 self.option_list = []
1073 self._share_option_mappings(self.parser)
1074
Greg Wardeba20e62004-07-31 16:15:44 +00001075 def set_title(self, title):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001076 self.title = title
1077
Thomas Wouters477c8d52006-05-27 19:21:47 +00001078 def destroy(self):
1079 """see OptionParser.destroy()."""
1080 OptionContainer.destroy(self)
1081 del self.option_list
1082
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001083 # -- Help-formatting methods ---------------------------------------
1084
Greg Wardeba20e62004-07-31 16:15:44 +00001085 def format_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001086 result = formatter.format_heading(self.title)
1087 formatter.indent()
1088 result += OptionContainer.format_help(self, formatter)
1089 formatter.dedent()
1090 return result
1091
1092
1093class OptionParser (OptionContainer):
1094
1095 """
1096 Class attributes:
1097 standard_option_list : [Option]
1098 list of standard options that will be accepted by all instances
1099 of this parser class (intended to be overridden by subclasses).
1100
1101 Instance attributes:
1102 usage : string
1103 a usage string for your program. Before it is displayed
1104 to the user, "%prog" will be expanded to the name of
Greg Ward2492fcf2003-04-21 02:40:34 +00001105 your program (self.prog or os.path.basename(sys.argv[0])).
1106 prog : string
1107 the name of the current program (to override
1108 os.path.basename(sys.argv[0])).
Thomas Wouters477c8d52006-05-27 19:21:47 +00001109 epilog : string
1110 paragraph of help text to print after option help
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001111
Greg Wardeba20e62004-07-31 16:15:44 +00001112 option_groups : [OptionGroup]
1113 list of option groups in this parser (option groups are
1114 irrelevant for parsing the command-line, but very useful
1115 for generating help)
1116
1117 allow_interspersed_args : bool = true
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001118 if true, positional arguments may be interspersed with options.
1119 Assuming -a and -b each take a single argument, the command-line
1120 -ablah foo bar -bboo baz
1121 will be interpreted the same as
1122 -ablah -bboo -- foo bar baz
1123 If this flag were false, that command line would be interpreted as
1124 -ablah -- foo bar -bboo baz
1125 -- ie. we stop processing options as soon as we see the first
1126 non-option argument. (This is the tradition followed by
1127 Python's getopt module, Perl's Getopt::Std, and other argument-
1128 parsing libraries, but it is generally annoying to users.)
1129
Greg Wardeba20e62004-07-31 16:15:44 +00001130 process_default_values : bool = true
1131 if true, option default values are processed similarly to option
1132 values from the command line: that is, they are passed to the
1133 type-checking function for the option's type (as long as the
1134 default value is a string). (This really only matters if you
1135 have defined custom types; see SF bug #955889.) Set it to false
1136 to restore the behaviour of Optik 1.4.1 and earlier.
1137
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001138 rargs : [string]
1139 the argument list currently being parsed. Only set when
1140 parse_args() is active, and continually trimmed down as
1141 we consume arguments. Mainly there for the benefit of
1142 callback options.
1143 largs : [string]
1144 the list of leftover arguments that we have skipped while
1145 parsing options. If allow_interspersed_args is false, this
1146 list is always empty.
1147 values : Values
1148 the set of option values currently being accumulated. Only
1149 set when parse_args() is active. Also mainly for callbacks.
1150
1151 Because of the 'rargs', 'largs', and 'values' attributes,
1152 OptionParser is not thread-safe. If, for some perverse reason, you
1153 need to parse command-line arguments simultaneously in different
1154 threads, use different OptionParser instances.
1155
1156 """
1157
1158 standard_option_list = []
1159
Greg Wardeba20e62004-07-31 16:15:44 +00001160 def __init__(self,
1161 usage=None,
1162 option_list=None,
1163 option_class=Option,
1164 version=None,
1165 conflict_handler="error",
1166 description=None,
1167 formatter=None,
1168 add_help_option=True,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001169 prog=None,
1170 epilog=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001171 OptionContainer.__init__(
1172 self, option_class, conflict_handler, description)
1173 self.set_usage(usage)
Greg Ward2492fcf2003-04-21 02:40:34 +00001174 self.prog = prog
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001175 self.version = version
Greg Wardeba20e62004-07-31 16:15:44 +00001176 self.allow_interspersed_args = True
1177 self.process_default_values = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001178 if formatter is None:
1179 formatter = IndentedHelpFormatter()
1180 self.formatter = formatter
Greg Wardeba20e62004-07-31 16:15:44 +00001181 self.formatter.set_parser(self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001182 self.epilog = epilog
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001183
1184 # Populate the option list; initial sources are the
1185 # standard_option_list class attribute, the 'option_list'
Greg Wardeba20e62004-07-31 16:15:44 +00001186 # argument, and (if applicable) the _add_version_option() and
1187 # _add_help_option() methods.
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001188 self._populate_option_list(option_list,
1189 add_help=add_help_option)
1190
1191 self._init_parsing_state()
1192
Thomas Wouters477c8d52006-05-27 19:21:47 +00001193
1194 def destroy(self):
1195 """
1196 Declare that you are done with this OptionParser. This cleans up
1197 reference cycles so the OptionParser (and all objects referenced by
1198 it) can be garbage-collected promptly. After calling destroy(), the
1199 OptionParser is unusable.
1200 """
1201 OptionContainer.destroy(self)
1202 for group in self.option_groups:
1203 group.destroy()
1204 del self.option_list
1205 del self.option_groups
1206 del self.formatter
1207
1208
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001209 # -- Private methods -----------------------------------------------
1210 # (used by our or OptionContainer's constructor)
1211
Greg Wardeba20e62004-07-31 16:15:44 +00001212 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001213 self.option_list = []
1214 self.option_groups = []
1215 self._create_option_mappings()
1216
Greg Wardeba20e62004-07-31 16:15:44 +00001217 def _add_help_option(self):
1218 self.add_option("-h", "--help",
1219 action="help",
1220 help=_("show this help message and exit"))
1221
1222 def _add_version_option(self):
1223 self.add_option("--version",
1224 action="version",
1225 help=_("show program's version number and exit"))
1226
1227 def _populate_option_list(self, option_list, add_help=True):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001228 if self.standard_option_list:
1229 self.add_options(self.standard_option_list)
1230 if option_list:
1231 self.add_options(option_list)
1232 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001233 self._add_version_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001234 if add_help:
Greg Wardeba20e62004-07-31 16:15:44 +00001235 self._add_help_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001236
Greg Wardeba20e62004-07-31 16:15:44 +00001237 def _init_parsing_state(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001238 # These are set in parse_args() for the convenience of callbacks.
1239 self.rargs = None
1240 self.largs = None
1241 self.values = None
1242
1243
1244 # -- Simple modifier methods ---------------------------------------
1245
Greg Wardeba20e62004-07-31 16:15:44 +00001246 def set_usage(self, usage):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001247 if usage is None:
Greg Wardeba20e62004-07-31 16:15:44 +00001248 self.usage = _("%prog [options]")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001249 elif usage is SUPPRESS_USAGE:
1250 self.usage = None
Greg Wardeba20e62004-07-31 16:15:44 +00001251 # For backwards compatibility with Optik 1.3 and earlier.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001252 elif usage.lower().startswith("usage: "):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001253 self.usage = usage[7:]
1254 else:
1255 self.usage = usage
1256
Greg Wardeba20e62004-07-31 16:15:44 +00001257 def enable_interspersed_args(self):
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001258 """Set parsing to not stop on the first non-option, allowing
1259 interspersing switches with command arguments. This is the
1260 default behavior. See also disable_interspersed_args() and the
1261 class documentation description of the attribute
1262 allow_interspersed_args."""
Greg Wardeba20e62004-07-31 16:15:44 +00001263 self.allow_interspersed_args = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001264
Greg Wardeba20e62004-07-31 16:15:44 +00001265 def disable_interspersed_args(self):
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001266 """Set parsing to stop on the first non-option. Use this if
1267 you have a command processor which runs another command that
1268 has options of its own and you want to make sure these options
1269 don't get confused.
1270 """
Greg Wardeba20e62004-07-31 16:15:44 +00001271 self.allow_interspersed_args = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001272
Greg Wardeba20e62004-07-31 16:15:44 +00001273 def set_process_default_values(self, process):
1274 self.process_default_values = process
1275
1276 def set_default(self, dest, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001277 self.defaults[dest] = value
1278
Greg Wardeba20e62004-07-31 16:15:44 +00001279 def set_defaults(self, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001280 self.defaults.update(kwargs)
1281
Greg Wardeba20e62004-07-31 16:15:44 +00001282 def _get_all_options(self):
1283 options = self.option_list[:]
1284 for group in self.option_groups:
1285 options.extend(group.option_list)
1286 return options
1287
1288 def get_default_values(self):
1289 if not self.process_default_values:
1290 # Old, pre-Optik 1.5 behaviour.
1291 return Values(self.defaults)
1292
1293 defaults = self.defaults.copy()
1294 for option in self._get_all_options():
1295 default = defaults.get(option.dest)
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001296 if isinstance(default, str):
Greg Wardeba20e62004-07-31 16:15:44 +00001297 opt_str = option.get_opt_string()
1298 defaults[option.dest] = option.check_value(opt_str, default)
1299
1300 return Values(defaults)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001301
1302
1303 # -- OptionGroup methods -------------------------------------------
1304
Greg Wardeba20e62004-07-31 16:15:44 +00001305 def add_option_group(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001306 # XXX lots of overlap with OptionContainer.add_option()
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001307 if isinstance(args[0], str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001308 group = OptionGroup(self, *args, **kwargs)
1309 elif len(args) == 1 and not kwargs:
1310 group = args[0]
1311 if not isinstance(group, OptionGroup):
Collin Winterce36ad82007-08-30 01:19:48 +00001312 raise TypeError("not an OptionGroup instance: %r" % group)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001313 if group.parser is not self:
Collin Winterce36ad82007-08-30 01:19:48 +00001314 raise ValueError("invalid OptionGroup (wrong parser)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001315 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001316 raise TypeError("invalid arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001317
1318 self.option_groups.append(group)
1319 return group
1320
Greg Wardeba20e62004-07-31 16:15:44 +00001321 def get_option_group(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001322 option = (self._short_opt.get(opt_str) or
1323 self._long_opt.get(opt_str))
1324 if option and option.container is not self:
1325 return option.container
1326 return None
1327
1328
1329 # -- Option-parsing methods ----------------------------------------
1330
Greg Wardeba20e62004-07-31 16:15:44 +00001331 def _get_args(self, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001332 if args is None:
1333 return sys.argv[1:]
1334 else:
1335 return args[:] # don't modify caller's list
1336
Greg Wardeba20e62004-07-31 16:15:44 +00001337 def parse_args(self, args=None, values=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001338 """
1339 parse_args(args : [string] = sys.argv[1:],
1340 values : Values = None)
1341 -> (values : Values, args : [string])
1342
1343 Parse the command-line options found in 'args' (default:
1344 sys.argv[1:]). Any errors result in a call to 'error()', which
1345 by default prints the usage message to stderr and calls
1346 sys.exit() with an error message. On success returns a pair
1347 (values, args) where 'values' is an Values instance (with all
1348 your option values) and 'args' is the list of arguments left
1349 over after parsing options.
1350 """
1351 rargs = self._get_args(args)
1352 if values is None:
1353 values = self.get_default_values()
1354
1355 # Store the halves of the argument list as attributes for the
1356 # convenience of callbacks:
1357 # rargs
1358 # the rest of the command-line (the "r" stands for
1359 # "remaining" or "right-hand")
1360 # largs
1361 # the leftover arguments -- ie. what's left after removing
1362 # options and their arguments (the "l" stands for "leftover"
1363 # or "left-hand")
1364 self.rargs = rargs
1365 self.largs = largs = []
1366 self.values = values
1367
1368 try:
1369 stop = self._process_args(largs, rargs, values)
Guido van Rossumb940e112007-01-10 16:19:56 +00001370 except (BadOptionError, OptionValueError) as err:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001371 self.error(str(err))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001372
1373 args = largs + rargs
1374 return self.check_values(values, args)
1375
Greg Wardeba20e62004-07-31 16:15:44 +00001376 def check_values(self, values, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001377 """
1378 check_values(values : Values, args : [string])
1379 -> (values : Values, args : [string])
1380
1381 Check that the supplied option values and leftover arguments are
1382 valid. Returns the option values and leftover arguments
1383 (possibly adjusted, possibly completely new -- whatever you
1384 like). Default implementation just returns the passed-in
1385 values; subclasses may override as desired.
1386 """
1387 return (values, args)
1388
Greg Wardeba20e62004-07-31 16:15:44 +00001389 def _process_args(self, largs, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001390 """_process_args(largs : [string],
1391 rargs : [string],
1392 values : Values)
1393
1394 Process command-line arguments and populate 'values', consuming
1395 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1396 false, stop at the first non-option argument. If true, accumulate any
1397 interspersed non-option arguments in 'largs'.
1398 """
1399 while rargs:
1400 arg = rargs[0]
1401 # We handle bare "--" explicitly, and bare "-" is handled by the
1402 # standard arg handler since the short arg case ensures that the
1403 # len of the opt string is greater than 1.
1404 if arg == "--":
1405 del rargs[0]
1406 return
1407 elif arg[0:2] == "--":
1408 # process a single long option (possibly with value(s))
1409 self._process_long_opt(rargs, values)
1410 elif arg[:1] == "-" and len(arg) > 1:
1411 # process a cluster of short options (possibly with
1412 # value(s) for the last one only)
1413 self._process_short_opts(rargs, values)
1414 elif self.allow_interspersed_args:
1415 largs.append(arg)
1416 del rargs[0]
1417 else:
1418 return # stop now, leave this arg in rargs
1419
1420 # Say this is the original argument list:
1421 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1422 # ^
1423 # (we are about to process arg(i)).
1424 #
1425 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1426 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1427 # been removed from largs).
1428 #
1429 # The while loop will usually consume 1 or more arguments per pass.
1430 # If it consumes 1 (eg. arg is an option that takes no arguments),
1431 # then after _process_arg() is done the situation is:
1432 #
1433 # largs = subset of [arg0, ..., arg(i)]
1434 # rargs = [arg(i+1), ..., arg(N-1)]
1435 #
1436 # If allow_interspersed_args is false, largs will always be
1437 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1438 # not a very interesting subset!
1439
Greg Wardeba20e62004-07-31 16:15:44 +00001440 def _match_long_opt(self, opt):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001441 """_match_long_opt(opt : string) -> string
1442
1443 Determine which long option string 'opt' matches, ie. which one
1444 it is an unambiguous abbrevation for. Raises BadOptionError if
1445 'opt' doesn't unambiguously match any long option string.
1446 """
1447 return _match_abbrev(opt, self._long_opt)
1448
Greg Wardeba20e62004-07-31 16:15:44 +00001449 def _process_long_opt(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001450 arg = rargs.pop(0)
1451
1452 # Value explicitly attached to arg? Pretend it's the next
1453 # argument.
1454 if "=" in arg:
1455 (opt, next_arg) = arg.split("=", 1)
1456 rargs.insert(0, next_arg)
Greg Wardeba20e62004-07-31 16:15:44 +00001457 had_explicit_value = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001458 else:
1459 opt = arg
Greg Wardeba20e62004-07-31 16:15:44 +00001460 had_explicit_value = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001461
1462 opt = self._match_long_opt(opt)
1463 option = self._long_opt[opt]
1464 if option.takes_value():
1465 nargs = option.nargs
1466 if len(rargs) < nargs:
1467 if nargs == 1:
Greg Wardeba20e62004-07-31 16:15:44 +00001468 self.error(_("%s option requires an argument") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001469 else:
Greg Wardeba20e62004-07-31 16:15:44 +00001470 self.error(_("%s option requires %d arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001471 % (opt, nargs))
1472 elif nargs == 1:
1473 value = rargs.pop(0)
1474 else:
1475 value = tuple(rargs[0:nargs])
1476 del rargs[0:nargs]
1477
1478 elif had_explicit_value:
Greg Wardeba20e62004-07-31 16:15:44 +00001479 self.error(_("%s option does not take a value") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001480
1481 else:
1482 value = None
1483
1484 option.process(opt, value, values, self)
1485
Greg Wardeba20e62004-07-31 16:15:44 +00001486 def _process_short_opts(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001487 arg = rargs.pop(0)
Greg Wardeba20e62004-07-31 16:15:44 +00001488 stop = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001489 i = 1
1490 for ch in arg[1:]:
1491 opt = "-" + ch
1492 option = self._short_opt.get(opt)
1493 i += 1 # we have consumed a character
1494
1495 if not option:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001496 raise BadOptionError(opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001497 if option.takes_value():
1498 # Any characters left in arg? Pretend they're the
1499 # next arg, and stop consuming characters of arg.
1500 if i < len(arg):
1501 rargs.insert(0, arg[i:])
Greg Wardeba20e62004-07-31 16:15:44 +00001502 stop = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001503
1504 nargs = option.nargs
1505 if len(rargs) < nargs:
1506 if nargs == 1:
Greg Wardeba20e62004-07-31 16:15:44 +00001507 self.error(_("%s option requires an argument") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001508 else:
Greg Wardeba20e62004-07-31 16:15:44 +00001509 self.error(_("%s option requires %d arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001510 % (opt, nargs))
1511 elif nargs == 1:
1512 value = rargs.pop(0)
1513 else:
1514 value = tuple(rargs[0:nargs])
1515 del rargs[0:nargs]
1516
1517 else: # option doesn't take a value
1518 value = None
1519
1520 option.process(opt, value, values, self)
1521
1522 if stop:
1523 break
1524
1525
1526 # -- Feedback methods ----------------------------------------------
1527
Greg Wardeba20e62004-07-31 16:15:44 +00001528 def get_prog_name(self):
1529 if self.prog is None:
1530 return os.path.basename(sys.argv[0])
1531 else:
1532 return self.prog
1533
1534 def expand_prog_name(self, s):
1535 return s.replace("%prog", self.get_prog_name())
1536
1537 def get_description(self):
1538 return self.expand_prog_name(self.description)
1539
Greg Ward48aa84b2004-10-27 02:20:04 +00001540 def exit(self, status=0, msg=None):
1541 if msg:
1542 sys.stderr.write(msg)
1543 sys.exit(status)
1544
Greg Wardeba20e62004-07-31 16:15:44 +00001545 def error(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001546 """error(msg : string)
1547
1548 Print a usage message incorporating 'msg' to stderr and exit.
1549 If you override this in a subclass, it should not return -- it
1550 should either exit or raise an exception.
1551 """
1552 self.print_usage(sys.stderr)
Greg Ward48aa84b2004-10-27 02:20:04 +00001553 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001554
Greg Wardeba20e62004-07-31 16:15:44 +00001555 def get_usage(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001556 if self.usage:
1557 return self.formatter.format_usage(
Greg Wardeba20e62004-07-31 16:15:44 +00001558 self.expand_prog_name(self.usage))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001559 else:
1560 return ""
1561
Greg Wardeba20e62004-07-31 16:15:44 +00001562 def print_usage(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001563 """print_usage(file : file = stdout)
1564
1565 Print the usage message for the current program (self.usage) to
1566 'file' (default stdout). Any occurence of the string "%prog" in
1567 self.usage is replaced with the name of the current program
1568 (basename of sys.argv[0]). Does nothing if self.usage is empty
1569 or not defined.
1570 """
1571 if self.usage:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001572 print(self.get_usage(), file=file)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001573
Greg Wardeba20e62004-07-31 16:15:44 +00001574 def get_version(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001575 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001576 return self.expand_prog_name(self.version)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001577 else:
1578 return ""
1579
Greg Wardeba20e62004-07-31 16:15:44 +00001580 def print_version(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001581 """print_version(file : file = stdout)
1582
1583 Print the version message for this program (self.version) to
1584 'file' (default stdout). As with print_usage(), any occurence
1585 of "%prog" in self.version is replaced by the current program's
1586 name. Does nothing if self.version is empty or undefined.
1587 """
1588 if self.version:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001589 print(self.get_version(), file=file)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001590
Greg Wardeba20e62004-07-31 16:15:44 +00001591 def format_option_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001592 if formatter is None:
1593 formatter = self.formatter
1594 formatter.store_option_strings(self)
1595 result = []
Thomas Wouters477c8d52006-05-27 19:21:47 +00001596 result.append(formatter.format_heading(_("Options")))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001597 formatter.indent()
1598 if self.option_list:
1599 result.append(OptionContainer.format_option_help(self, formatter))
1600 result.append("\n")
1601 for group in self.option_groups:
1602 result.append(group.format_help(formatter))
1603 result.append("\n")
1604 formatter.dedent()
1605 # Drop the last "\n", or the header if no options or option groups:
1606 return "".join(result[:-1])
1607
Thomas Wouters477c8d52006-05-27 19:21:47 +00001608 def format_epilog(self, formatter):
1609 return formatter.format_epilog(self.epilog)
1610
Greg Wardeba20e62004-07-31 16:15:44 +00001611 def format_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001612 if formatter is None:
1613 formatter = self.formatter
1614 result = []
1615 if self.usage:
1616 result.append(self.get_usage() + "\n")
1617 if self.description:
1618 result.append(self.format_description(formatter) + "\n")
1619 result.append(self.format_option_help(formatter))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001620 result.append(self.format_epilog(formatter))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001621 return "".join(result)
1622
Greg Wardeba20e62004-07-31 16:15:44 +00001623 def print_help(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001624 """print_help(file : file = stdout)
1625
1626 Print an extended help message, listing all options and any
1627 help text provided with them, to 'file' (default stdout).
1628 """
1629 if file is None:
1630 file = sys.stdout
Guido van Rossum34d19282007-08-09 01:03:29 +00001631 file.write(self.format_help())
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001632
1633# class OptionParser
1634
1635
Greg Wardeba20e62004-07-31 16:15:44 +00001636def _match_abbrev(s, wordmap):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001637 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1638
1639 Return the string key in 'wordmap' for which 's' is an unambiguous
1640 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1641 'words', raise BadOptionError.
1642 """
1643 # Is there an exact match?
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001644 if s in wordmap:
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001645 return s
1646 else:
1647 # Isolate all words with s as a prefix.
1648 possibilities = [word for word in wordmap.keys()
1649 if word.startswith(s)]
1650 # No exact match, so there had better be just one possibility.
1651 if len(possibilities) == 1:
1652 return possibilities[0]
1653 elif not possibilities:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001654 raise BadOptionError(s)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001655 else:
1656 # More than one possible completion: ambiguous prefix.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001657 possibilities.sort()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001658 raise AmbiguousOptionError(s, possibilities)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001659
1660
1661# Some day, there might be many Option classes. As of Optik 1.3, the
1662# preferred way to instantiate Options is indirectly, via make_option(),
1663# which will become a factory function when there are many Option
1664# classes.
1665make_option = Option