blob: bec492d8cdbf1f23e9143dcf249b825403b0ef53 [file] [log] [blame]
Andrew M. Kuchlingddbce9e2008-10-06 12:07:04 +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
Andrew M. Kuchlingddbce9e2008-10-06 12:07:04 +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).
Georg Brandlaa481572009-04-12 20:30:53 +00009
10Simple usage example:
11
12 from optparse import OptionParser
13
14 parser = OptionParser()
15 parser.add_option("-f", "--file", dest="filename",
16 help="write report to FILE", metavar="FILE")
17 parser.add_option("-q", "--quiet",
18 action="store_false", dest="verbose", default=True,
19 help="don't print status messages to stdout")
20
21 (options, args) = parser.parse_args()
Guido van Rossumb9ba4582002-11-14 22:00:19 +000022"""
23
Greg Ward48fae7a2006-07-23 16:05:51 +000024__version__ = "1.5.3"
Greg Ward2492fcf2003-04-21 02:40:34 +000025
Greg Ward4656ed42003-05-08 01:38:52 +000026__all__ = ['Option',
Georg Brandlc5d8c632009-03-31 19:12:17 +000027 'make_option',
Greg Ward4656ed42003-05-08 01:38:52 +000028 'SUPPRESS_HELP',
29 'SUPPRESS_USAGE',
Greg Ward4656ed42003-05-08 01:38:52 +000030 'Values',
31 'OptionContainer',
32 'OptionGroup',
33 'OptionParser',
34 'HelpFormatter',
35 'IndentedHelpFormatter',
36 'TitledHelpFormatter',
37 'OptParseError',
38 'OptionError',
39 'OptionConflictError',
40 'OptionValueError',
41 'BadOptionError']
Greg Ward2492fcf2003-04-21 02:40:34 +000042
Guido van Rossumb9ba4582002-11-14 22:00:19 +000043__copyright__ = """
Greg Wardab05edc2006-04-23 03:47:58 +000044Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
45Copyright (c) 2002-2006 Python Software Foundation. All rights reserved.
Guido van Rossumb9ba4582002-11-14 22:00:19 +000046
47Redistribution and use in source and binary forms, with or without
48modification, are permitted provided that the following conditions are
49met:
50
51 * Redistributions of source code must retain the above copyright
52 notice, this list of conditions and the following disclaimer.
53
54 * Redistributions in binary form must reproduce the above copyright
55 notice, this list of conditions and the following disclaimer in the
56 documentation and/or other materials provided with the distribution.
57
58 * Neither the name of the author nor the names of its
59 contributors may be used to endorse or promote products derived from
60 this software without specific prior written permission.
61
62THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
63IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
64TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
65PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
66CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
67EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
68PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
69PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
70LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
71NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
72SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
73"""
74
75import sys, os
Greg Wardab05edc2006-04-23 03:47:58 +000076import types
Guido van Rossumb9ba4582002-11-14 22:00:19 +000077import textwrap
Greg Wardeba20e62004-07-31 16:15:44 +000078
79def _repr(self):
80 return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
81
82
83# This file was generated from:
Greg Ward48fae7a2006-07-23 16:05:51 +000084# Id: option_parser.py 527 2006-07-23 15:21:30Z greg
Greg Ward0e0c9f42006-06-11 16:24:11 +000085# Id: option.py 522 2006-06-11 16:22:03Z gward
Greg Ward48fae7a2006-07-23 16:05:51 +000086# Id: help.py 527 2006-07-23 15:21:30Z greg
Greg Wardab05edc2006-04-23 03:47:58 +000087# Id: errors.py 509 2006-04-20 00:58:24Z gward
88
89try:
90 from gettext import gettext
91except ImportError:
92 def gettext(message):
93 return message
94_ = gettext
95
Guido van Rossumb9ba4582002-11-14 22:00:19 +000096
Guido van Rossumb9ba4582002-11-14 22:00:19 +000097class OptParseError (Exception):
Greg Wardeba20e62004-07-31 16:15:44 +000098 def __init__(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +000099 self.msg = msg
100
Greg Wardeba20e62004-07-31 16:15:44 +0000101 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000102 return self.msg
103
Greg Ward2492fcf2003-04-21 02:40:34 +0000104
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000105class OptionError (OptParseError):
106 """
107 Raised if an Option instance is created with invalid or
108 inconsistent arguments.
109 """
110
Greg Wardeba20e62004-07-31 16:15:44 +0000111 def __init__(self, msg, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000112 self.msg = msg
113 self.option_id = str(option)
114
Greg Wardeba20e62004-07-31 16:15:44 +0000115 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000116 if self.option_id:
117 return "option %s: %s" % (self.option_id, self.msg)
118 else:
119 return self.msg
120
121class OptionConflictError (OptionError):
122 """
123 Raised if conflicting options are added to an OptionParser.
124 """
125
126class OptionValueError (OptParseError):
127 """
128 Raised if an invalid option value is encountered on the command
129 line.
130 """
131
132class BadOptionError (OptParseError):
133 """
Greg Wardab05edc2006-04-23 03:47:58 +0000134 Raised if an invalid option is seen on the command line.
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000135 """
Greg Wardab05edc2006-04-23 03:47:58 +0000136 def __init__(self, opt_str):
137 self.opt_str = opt_str
138
139 def __str__(self):
140 return _("no such option: %s") % self.opt_str
141
142class AmbiguousOptionError (BadOptionError):
143 """
144 Raised if an ambiguous option is seen on the command line.
145 """
146 def __init__(self, opt_str, possibilities):
147 BadOptionError.__init__(self, opt_str)
148 self.possibilities = possibilities
149
150 def __str__(self):
151 return (_("ambiguous option: %s (%s?)")
152 % (self.opt_str, ", ".join(self.possibilities)))
Greg Ward2492fcf2003-04-21 02:40:34 +0000153
154
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000155class HelpFormatter:
156
157 """
158 Abstract base class for formatting option help. OptionParser
159 instances should use one of the HelpFormatter subclasses for
160 formatting help; by default IndentedHelpFormatter is used.
161
162 Instance attributes:
Greg Wardeba20e62004-07-31 16:15:44 +0000163 parser : OptionParser
164 the controlling OptionParser instance
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000165 indent_increment : int
166 the number of columns to indent per nesting level
167 max_help_position : int
168 the maximum starting column for option help text
169 help_position : int
170 the calculated starting column for option help text;
171 initially the same as the maximum
172 width : int
Greg Wardeba20e62004-07-31 16:15:44 +0000173 total number of columns for output (pass None to constructor for
174 this value to be taken from the $COLUMNS environment variable)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000175 level : int
176 current indentation level
177 current_indent : int
178 current indentation level (in columns)
179 help_width : int
180 number of columns available for option help text (calculated)
Greg Wardeba20e62004-07-31 16:15:44 +0000181 default_tag : str
182 text to replace with each option's default value, "%default"
183 by default. Set to false value to disable default value expansion.
184 option_strings : { Option : str }
185 maps Option instances to the snippet of help text explaining
186 the syntax of that option, e.g. "-h, --help" or
187 "-fFILE, --file=FILE"
188 _short_opt_fmt : str
189 format string controlling how short options with values are
190 printed in help text. Must be either "%s%s" ("-fFILE") or
191 "%s %s" ("-f FILE"), because those are the two syntaxes that
192 Optik supports.
193 _long_opt_fmt : str
194 similar but for long options; must be either "%s %s" ("--file FILE")
195 or "%s=%s" ("--file=FILE").
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000196 """
197
Greg Wardeba20e62004-07-31 16:15:44 +0000198 NO_DEFAULT_VALUE = "none"
199
200 def __init__(self,
201 indent_increment,
202 max_help_position,
203 width,
204 short_first):
205 self.parser = None
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000206 self.indent_increment = indent_increment
Greg Wardeba20e62004-07-31 16:15:44 +0000207 if width is None:
208 try:
209 width = int(os.environ['COLUMNS'])
210 except (KeyError, ValueError):
211 width = 80
212 width -= 2
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000213 self.width = width
Serhiy Storchaka9f8621f2014-01-09 23:13:48 +0200214 self.help_position = self.max_help_position = \
215 min(max_help_position, max(width - 20, indent_increment * 2))
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000216 self.current_indent = 0
217 self.level = 0
Greg Wardeba20e62004-07-31 16:15:44 +0000218 self.help_width = None # computed later
Greg Ward2492fcf2003-04-21 02:40:34 +0000219 self.short_first = short_first
Greg Wardeba20e62004-07-31 16:15:44 +0000220 self.default_tag = "%default"
221 self.option_strings = {}
222 self._short_opt_fmt = "%s %s"
223 self._long_opt_fmt = "%s=%s"
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000224
Greg Wardeba20e62004-07-31 16:15:44 +0000225 def set_parser(self, parser):
226 self.parser = parser
227
228 def set_short_opt_delimiter(self, delim):
229 if delim not in ("", " "):
230 raise ValueError(
231 "invalid metavar delimiter for short options: %r" % delim)
232 self._short_opt_fmt = "%s" + delim + "%s"
233
234 def set_long_opt_delimiter(self, delim):
235 if delim not in ("=", " "):
236 raise ValueError(
237 "invalid metavar delimiter for long options: %r" % delim)
238 self._long_opt_fmt = "%s" + delim + "%s"
239
240 def indent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000241 self.current_indent += self.indent_increment
242 self.level += 1
243
Greg Wardeba20e62004-07-31 16:15:44 +0000244 def dedent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000245 self.current_indent -= self.indent_increment
246 assert self.current_indent >= 0, "Indent decreased below 0."
247 self.level -= 1
248
Greg Wardeba20e62004-07-31 16:15:44 +0000249 def format_usage(self, usage):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000250 raise NotImplementedError, "subclasses must implement"
251
Greg Wardeba20e62004-07-31 16:15:44 +0000252 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000253 raise NotImplementedError, "subclasses must implement"
254
Greg Wardab05edc2006-04-23 03:47:58 +0000255 def _format_text(self, text):
256 """
257 Format a paragraph of free-form text for inclusion in the
258 help output at the current indentation level.
259 """
Serhiy Storchaka9f8621f2014-01-09 23:13:48 +0200260 text_width = max(self.width - self.current_indent, 11)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000261 indent = " "*self.current_indent
Greg Wardab05edc2006-04-23 03:47:58 +0000262 return textwrap.fill(text,
263 text_width,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000264 initial_indent=indent,
Greg Wardab05edc2006-04-23 03:47:58 +0000265 subsequent_indent=indent)
Tim Peters4f96f1f2006-06-11 19:42:51 +0000266
Greg Wardab05edc2006-04-23 03:47:58 +0000267 def format_description(self, description):
268 if description:
269 return self._format_text(description) + "\n"
270 else:
271 return ""
272
273 def format_epilog(self, epilog):
274 if epilog:
275 return "\n" + self._format_text(epilog) + "\n"
276 else:
277 return ""
278
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000279
Greg Wardeba20e62004-07-31 16:15:44 +0000280 def expand_default(self, option):
281 if self.parser is None or not self.default_tag:
282 return option.help
283
284 default_value = self.parser.defaults.get(option.dest)
285 if default_value is NO_DEFAULT or default_value is None:
286 default_value = self.NO_DEFAULT_VALUE
287
288 return option.help.replace(self.default_tag, str(default_value))
289
290 def format_option(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000291 # The help for each option consists of two parts:
292 # * the opt strings and metavars
293 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
294 # * the user-supplied help string
295 # eg. ("turn on expert mode", "read data from FILENAME")
296 #
297 # If possible, we write both of these on the same line:
298 # -x turn on expert mode
299 #
300 # But if the opt string list is too long, we put the help
301 # string on a second line, indented to the same column it would
302 # start in if it fit on the first line.
303 # -fFILENAME, --file=FILENAME
304 # read data from FILENAME
305 result = []
Greg Wardeba20e62004-07-31 16:15:44 +0000306 opts = self.option_strings[option]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000307 opt_width = self.help_position - self.current_indent - 2
308 if len(opts) > opt_width:
309 opts = "%*s%s\n" % (self.current_indent, "", opts)
310 indent_first = self.help_position
311 else: # start help on same line as opts
312 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
313 indent_first = 0
314 result.append(opts)
315 if option.help:
Greg Wardeba20e62004-07-31 16:15:44 +0000316 help_text = self.expand_default(option)
317 help_lines = textwrap.wrap(help_text, self.help_width)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000318 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
319 result.extend(["%*s%s\n" % (self.help_position, "", line)
320 for line in help_lines[1:]])
321 elif opts[-1] != "\n":
322 result.append("\n")
323 return "".join(result)
324
Greg Wardeba20e62004-07-31 16:15:44 +0000325 def store_option_strings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000326 self.indent()
327 max_len = 0
328 for opt in parser.option_list:
329 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000330 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000331 max_len = max(max_len, len(strings) + self.current_indent)
332 self.indent()
333 for group in parser.option_groups:
334 for opt in group.option_list:
335 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000336 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000337 max_len = max(max_len, len(strings) + self.current_indent)
338 self.dedent()
339 self.dedent()
340 self.help_position = min(max_len + 2, self.max_help_position)
Serhiy Storchaka9f8621f2014-01-09 23:13:48 +0200341 self.help_width = max(self.width - self.help_position, 11)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000342
Greg Wardeba20e62004-07-31 16:15:44 +0000343 def format_option_strings(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000344 """Return a comma-separated list of option strings & metavariables."""
Greg Ward2492fcf2003-04-21 02:40:34 +0000345 if option.takes_value():
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000346 metavar = option.metavar or option.dest.upper()
Greg Wardeba20e62004-07-31 16:15:44 +0000347 short_opts = [self._short_opt_fmt % (sopt, metavar)
348 for sopt in option._short_opts]
349 long_opts = [self._long_opt_fmt % (lopt, metavar)
350 for lopt in option._long_opts]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000351 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000352 short_opts = option._short_opts
353 long_opts = option._long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000354
Greg Ward2492fcf2003-04-21 02:40:34 +0000355 if self.short_first:
356 opts = short_opts + long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000357 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000358 opts = long_opts + short_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000359
Greg Ward2492fcf2003-04-21 02:40:34 +0000360 return ", ".join(opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000361
362class IndentedHelpFormatter (HelpFormatter):
363 """Format help with indented section bodies.
364 """
365
Greg Wardeba20e62004-07-31 16:15:44 +0000366 def __init__(self,
367 indent_increment=2,
368 max_help_position=24,
369 width=None,
370 short_first=1):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000371 HelpFormatter.__init__(
372 self, indent_increment, max_help_position, width, short_first)
373
Greg Wardeba20e62004-07-31 16:15:44 +0000374 def format_usage(self, usage):
Greg Wardab05edc2006-04-23 03:47:58 +0000375 return _("Usage: %s\n") % usage
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000376
Greg Wardeba20e62004-07-31 16:15:44 +0000377 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000378 return "%*s%s:\n" % (self.current_indent, "", heading)
379
380
381class TitledHelpFormatter (HelpFormatter):
382 """Format help with underlined section headers.
383 """
384
Greg Wardeba20e62004-07-31 16:15:44 +0000385 def __init__(self,
386 indent_increment=0,
387 max_help_position=24,
388 width=None,
389 short_first=0):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000390 HelpFormatter.__init__ (
391 self, indent_increment, max_help_position, width, short_first)
392
Greg Wardeba20e62004-07-31 16:15:44 +0000393 def format_usage(self, usage):
394 return "%s %s\n" % (self.format_heading(_("Usage")), usage)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000395
Greg Wardeba20e62004-07-31 16:15:44 +0000396 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000397 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
Greg Ward2492fcf2003-04-21 02:40:34 +0000398
399
Greg Wardab05edc2006-04-23 03:47:58 +0000400def _parse_num(val, type):
401 if val[:2].lower() == "0x": # hexadecimal
402 radix = 16
403 elif val[:2].lower() == "0b": # binary
404 radix = 2
405 val = val[2:] or "0" # have to remove "0b" prefix
406 elif val[:1] == "0": # octal
407 radix = 8
408 else: # decimal
409 radix = 10
410
411 return type(val, radix)
412
413def _parse_int(val):
414 return _parse_num(val, int)
415
416def _parse_long(val):
417 return _parse_num(val, long)
418
419_builtin_cvt = { "int" : (_parse_int, _("integer")),
420 "long" : (_parse_long, _("long integer")),
Greg Wardeba20e62004-07-31 16:15:44 +0000421 "float" : (float, _("floating-point")),
422 "complex" : (complex, _("complex")) }
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000423
Greg Wardeba20e62004-07-31 16:15:44 +0000424def check_builtin(option, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000425 (cvt, what) = _builtin_cvt[option.type]
426 try:
427 return cvt(value)
428 except ValueError:
429 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000430 _("option %s: invalid %s value: %r") % (opt, what, value))
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000431
432def check_choice(option, opt, value):
433 if value in option.choices:
434 return value
435 else:
436 choices = ", ".join(map(repr, option.choices))
437 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000438 _("option %s: invalid choice: %r (choose from %s)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000439 % (opt, value, choices))
440
441# Not supplying a default is different from a default of None,
442# so we need an explicit "not supplied" value.
Greg Wardeba20e62004-07-31 16:15:44 +0000443NO_DEFAULT = ("NO", "DEFAULT")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000444
445
446class Option:
447 """
448 Instance attributes:
449 _short_opts : [string]
450 _long_opts : [string]
451
452 action : string
453 type : string
454 dest : string
455 default : any
456 nargs : int
457 const : any
458 choices : [string]
459 callback : function
460 callback_args : (any*)
461 callback_kwargs : { string : any }
462 help : string
463 metavar : string
464 """
465
466 # The list of instance attributes that may be set through
467 # keyword args to the constructor.
468 ATTRS = ['action',
469 'type',
470 'dest',
471 'default',
472 'nargs',
473 'const',
474 'choices',
475 'callback',
476 'callback_args',
477 'callback_kwargs',
478 'help',
479 'metavar']
480
481 # The set of actions allowed by option parsers. Explicitly listed
482 # here so the constructor can validate its arguments.
483 ACTIONS = ("store",
484 "store_const",
485 "store_true",
486 "store_false",
487 "append",
Greg Wardab05edc2006-04-23 03:47:58 +0000488 "append_const",
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000489 "count",
490 "callback",
491 "help",
492 "version")
493
494 # The set of actions that involve storing a value somewhere;
495 # also listed just for constructor argument validation. (If
496 # the action is one of these, there must be a destination.)
497 STORE_ACTIONS = ("store",
498 "store_const",
499 "store_true",
500 "store_false",
501 "append",
Greg Wardab05edc2006-04-23 03:47:58 +0000502 "append_const",
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000503 "count")
504
505 # The set of actions for which it makes sense to supply a value
Greg Ward48aa84b2004-10-27 02:20:04 +0000506 # type, ie. which may consume an argument from the command line.
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000507 TYPED_ACTIONS = ("store",
508 "append",
509 "callback")
510
Greg Ward48aa84b2004-10-27 02:20:04 +0000511 # The set of actions which *require* a value type, ie. that
512 # always consume an argument from the command line.
513 ALWAYS_TYPED_ACTIONS = ("store",
514 "append")
515
Greg Wardab05edc2006-04-23 03:47:58 +0000516 # The set of actions which take a 'const' attribute.
517 CONST_ACTIONS = ("store_const",
518 "append_const")
519
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000520 # The set of known types for option parsers. Again, listed here for
521 # constructor argument validation.
522 TYPES = ("string", "int", "long", "float", "complex", "choice")
523
524 # Dictionary of argument checking functions, which convert and
525 # validate option arguments according to the option type.
526 #
527 # Signature of checking functions is:
528 # check(option : Option, opt : string, value : string) -> any
529 # where
530 # option is the Option instance calling the checker
531 # opt is the actual option seen on the command-line
532 # (eg. "-a", "--file")
533 # value is the option argument seen on the command-line
534 #
535 # The return value should be in the appropriate Python type
536 # for option.type -- eg. an integer if option.type == "int".
537 #
538 # If no checker is defined for a type, arguments will be
539 # unchecked and remain strings.
540 TYPE_CHECKER = { "int" : check_builtin,
541 "long" : check_builtin,
542 "float" : check_builtin,
Greg Wardeba20e62004-07-31 16:15:44 +0000543 "complex": check_builtin,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000544 "choice" : check_choice,
545 }
546
547
548 # CHECK_METHODS is a list of unbound method objects; they are called
549 # by the constructor, in order, after all attributes are
550 # initialized. The list is created and filled in later, after all
551 # the methods are actually defined. (I just put it here because I
552 # like to define and document all class attributes in the same
553 # place.) Subclasses that add another _check_*() method should
554 # define their own CHECK_METHODS list that adds their check method
555 # to those from this class.
556 CHECK_METHODS = None
557
558
559 # -- Constructor/initialization methods ----------------------------
560
Greg Wardeba20e62004-07-31 16:15:44 +0000561 def __init__(self, *opts, **attrs):
Greg Ward2492fcf2003-04-21 02:40:34 +0000562 # Set _short_opts, _long_opts attrs from 'opts' tuple.
563 # Have to be set now, in case no option strings are supplied.
564 self._short_opts = []
565 self._long_opts = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000566 opts = self._check_opt_strings(opts)
567 self._set_opt_strings(opts)
568
569 # Set all other attrs (action, type, etc.) from 'attrs' dict
570 self._set_attrs(attrs)
571
572 # Check all the attributes we just set. There are lots of
573 # complicated interdependencies, but luckily they can be farmed
574 # out to the _check_*() methods listed in CHECK_METHODS -- which
575 # could be handy for subclasses! The one thing these all share
576 # is that they raise OptionError if they discover a problem.
577 for checker in self.CHECK_METHODS:
578 checker(self)
579
Greg Wardeba20e62004-07-31 16:15:44 +0000580 def _check_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000581 # Filter out None because early versions of Optik had exactly
582 # one short option and one long option, either of which
583 # could be None.
584 opts = filter(None, opts)
585 if not opts:
Greg Ward2492fcf2003-04-21 02:40:34 +0000586 raise TypeError("at least one option string must be supplied")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000587 return opts
588
Greg Wardeba20e62004-07-31 16:15:44 +0000589 def _set_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000590 for opt in opts:
591 if len(opt) < 2:
592 raise OptionError(
593 "invalid option string %r: "
594 "must be at least two characters long" % opt, self)
595 elif len(opt) == 2:
596 if not (opt[0] == "-" and opt[1] != "-"):
597 raise OptionError(
598 "invalid short option string %r: "
599 "must be of the form -x, (x any non-dash char)" % opt,
600 self)
601 self._short_opts.append(opt)
602 else:
603 if not (opt[0:2] == "--" and opt[2] != "-"):
604 raise OptionError(
605 "invalid long option string %r: "
606 "must start with --, followed by non-dash" % opt,
607 self)
608 self._long_opts.append(opt)
609
Greg Wardeba20e62004-07-31 16:15:44 +0000610 def _set_attrs(self, attrs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000611 for attr in self.ATTRS:
Raymond Hettinger930795b2008-07-10 15:37:08 +0000612 if attr in attrs:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000613 setattr(self, attr, attrs[attr])
614 del attrs[attr]
615 else:
616 if attr == 'default':
617 setattr(self, attr, NO_DEFAULT)
618 else:
619 setattr(self, attr, None)
620 if attrs:
Armin Rigoa3f09272006-05-28 19:13:17 +0000621 attrs = attrs.keys()
622 attrs.sort()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000623 raise OptionError(
Armin Rigoa3f09272006-05-28 19:13:17 +0000624 "invalid keyword arguments: %s" % ", ".join(attrs),
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000625 self)
626
627
628 # -- Constructor validation methods --------------------------------
629
Greg Wardeba20e62004-07-31 16:15:44 +0000630 def _check_action(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000631 if self.action is None:
632 self.action = "store"
633 elif self.action not in self.ACTIONS:
634 raise OptionError("invalid action: %r" % self.action, self)
635
Greg Wardeba20e62004-07-31 16:15:44 +0000636 def _check_type(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000637 if self.type is None:
Greg Ward48aa84b2004-10-27 02:20:04 +0000638 if self.action in self.ALWAYS_TYPED_ACTIONS:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000639 if self.choices is not None:
640 # The "choices" attribute implies "choice" type.
641 self.type = "choice"
642 else:
643 # No type given? "string" is the most sensible default.
644 self.type = "string"
645 else:
Greg Wardab05edc2006-04-23 03:47:58 +0000646 # Allow type objects or builtin type conversion functions
647 # (int, str, etc.) as an alternative to their names. (The
648 # complicated check of __builtin__ is only necessary for
649 # Python 2.1 and earlier, and is short-circuited by the
650 # first check on modern Pythons.)
651 import __builtin__
652 if ( type(self.type) is types.TypeType or
653 (hasattr(self.type, "__name__") and
654 getattr(__builtin__, self.type.__name__, None) is self.type) ):
Greg Wardeba20e62004-07-31 16:15:44 +0000655 self.type = self.type.__name__
Greg Wardab05edc2006-04-23 03:47:58 +0000656
Greg Wardeba20e62004-07-31 16:15:44 +0000657 if self.type == "str":
658 self.type = "string"
659
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000660 if self.type not in self.TYPES:
661 raise OptionError("invalid option type: %r" % self.type, self)
662 if self.action not in self.TYPED_ACTIONS:
663 raise OptionError(
664 "must not supply a type for action %r" % self.action, self)
665
666 def _check_choice(self):
667 if self.type == "choice":
668 if self.choices is None:
669 raise OptionError(
670 "must supply a list of choices for type 'choice'", self)
Greg Wardab05edc2006-04-23 03:47:58 +0000671 elif type(self.choices) not in (types.TupleType, types.ListType):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000672 raise OptionError(
673 "choices must be a list of strings ('%s' supplied)"
674 % str(type(self.choices)).split("'")[1], self)
675 elif self.choices is not None:
676 raise OptionError(
677 "must not supply choices for type %r" % self.type, self)
678
Greg Wardeba20e62004-07-31 16:15:44 +0000679 def _check_dest(self):
680 # No destination given, and we need one for this action. The
681 # self.type check is for callbacks that take a value.
682 takes_value = (self.action in self.STORE_ACTIONS or
683 self.type is not None)
684 if self.dest is None and takes_value:
685
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000686 # Glean a destination from the first long option string,
687 # or from the first short option string if no long options.
688 if self._long_opts:
689 # eg. "--foo-bar" -> "foo_bar"
690 self.dest = self._long_opts[0][2:].replace('-', '_')
691 else:
692 self.dest = self._short_opts[0][1]
693
Greg Wardeba20e62004-07-31 16:15:44 +0000694 def _check_const(self):
Greg Wardab05edc2006-04-23 03:47:58 +0000695 if self.action not in self.CONST_ACTIONS and self.const is not None:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000696 raise OptionError(
697 "'const' must not be supplied for action %r" % self.action,
698 self)
699
Greg Wardeba20e62004-07-31 16:15:44 +0000700 def _check_nargs(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000701 if self.action in self.TYPED_ACTIONS:
702 if self.nargs is None:
703 self.nargs = 1
704 elif self.nargs is not None:
705 raise OptionError(
706 "'nargs' must not be supplied for action %r" % self.action,
707 self)
708
Greg Wardeba20e62004-07-31 16:15:44 +0000709 def _check_callback(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000710 if self.action == "callback":
Raymond Hettinger930795b2008-07-10 15:37:08 +0000711 if not hasattr(self.callback, '__call__'):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000712 raise OptionError(
713 "callback not callable: %r" % self.callback, self)
714 if (self.callback_args is not None and
Greg Wardab05edc2006-04-23 03:47:58 +0000715 type(self.callback_args) is not types.TupleType):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000716 raise OptionError(
717 "callback_args, if supplied, must be a tuple: not %r"
718 % self.callback_args, self)
719 if (self.callback_kwargs is not None and
Greg Wardab05edc2006-04-23 03:47:58 +0000720 type(self.callback_kwargs) is not types.DictType):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000721 raise OptionError(
722 "callback_kwargs, if supplied, must be a dict: not %r"
723 % self.callback_kwargs, self)
724 else:
725 if self.callback is not None:
726 raise OptionError(
727 "callback supplied (%r) for non-callback option"
728 % self.callback, self)
729 if self.callback_args is not None:
730 raise OptionError(
731 "callback_args supplied for non-callback option", self)
732 if self.callback_kwargs is not None:
733 raise OptionError(
734 "callback_kwargs supplied for non-callback option", self)
735
736
737 CHECK_METHODS = [_check_action,
738 _check_type,
739 _check_choice,
740 _check_dest,
741 _check_const,
742 _check_nargs,
743 _check_callback]
744
745
746 # -- Miscellaneous methods -----------------------------------------
747
Greg Wardeba20e62004-07-31 16:15:44 +0000748 def __str__(self):
Greg Ward2492fcf2003-04-21 02:40:34 +0000749 return "/".join(self._short_opts + self._long_opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000750
Greg Wardeba20e62004-07-31 16:15:44 +0000751 __repr__ = _repr
752
753 def takes_value(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000754 return self.type is not None
755
Greg Wardeba20e62004-07-31 16:15:44 +0000756 def get_opt_string(self):
757 if self._long_opts:
758 return self._long_opts[0]
759 else:
760 return self._short_opts[0]
761
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000762
763 # -- Processing methods --------------------------------------------
764
Greg Wardeba20e62004-07-31 16:15:44 +0000765 def check_value(self, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000766 checker = self.TYPE_CHECKER.get(self.type)
767 if checker is None:
768 return value
769 else:
770 return checker(self, opt, value)
771
Greg Wardeba20e62004-07-31 16:15:44 +0000772 def convert_value(self, opt, value):
773 if value is not None:
774 if self.nargs == 1:
775 return self.check_value(opt, value)
776 else:
777 return tuple([self.check_value(opt, v) for v in value])
778
779 def process(self, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000780
781 # First, convert the value(s) to the right type. Howl if any
782 # value(s) are bogus.
Greg Wardeba20e62004-07-31 16:15:44 +0000783 value = self.convert_value(opt, value)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000784
785 # And then take whatever action is expected of us.
786 # This is a separate method to make life easier for
787 # subclasses to add new actions.
788 return self.take_action(
789 self.action, self.dest, opt, value, values, parser)
790
Greg Wardeba20e62004-07-31 16:15:44 +0000791 def take_action(self, action, dest, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000792 if action == "store":
793 setattr(values, dest, value)
794 elif action == "store_const":
795 setattr(values, dest, self.const)
796 elif action == "store_true":
Greg Ward2492fcf2003-04-21 02:40:34 +0000797 setattr(values, dest, True)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000798 elif action == "store_false":
Greg Ward2492fcf2003-04-21 02:40:34 +0000799 setattr(values, dest, False)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000800 elif action == "append":
801 values.ensure_value(dest, []).append(value)
Greg Wardab05edc2006-04-23 03:47:58 +0000802 elif action == "append_const":
803 values.ensure_value(dest, []).append(self.const)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000804 elif action == "count":
805 setattr(values, dest, values.ensure_value(dest, 0) + 1)
806 elif action == "callback":
807 args = self.callback_args or ()
808 kwargs = self.callback_kwargs or {}
809 self.callback(self, opt, value, parser, *args, **kwargs)
810 elif action == "help":
811 parser.print_help()
Greg Ward48aa84b2004-10-27 02:20:04 +0000812 parser.exit()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000813 elif action == "version":
814 parser.print_version()
Greg Ward48aa84b2004-10-27 02:20:04 +0000815 parser.exit()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000816 else:
Benjamin Peterson21f25d32008-11-23 02:09:41 +0000817 raise ValueError("unknown action %r" % self.action)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000818
819 return 1
820
821# class Option
Greg Ward2492fcf2003-04-21 02:40:34 +0000822
823
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000824SUPPRESS_HELP = "SUPPRESS"+"HELP"
825SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
826
Christian Heimes5b25bc02008-01-27 19:01:45 +0000827try:
828 basestring
829except NameError:
830 def isbasestring(x):
831 return isinstance(x, (types.StringType, types.UnicodeType))
832else:
833 def isbasestring(x):
Christian Heimes082c9b02008-01-23 14:20:50 +0000834 return isinstance(x, basestring)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000835
836class Values:
837
Greg Wardeba20e62004-07-31 16:15:44 +0000838 def __init__(self, defaults=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000839 if defaults:
840 for (attr, val) in defaults.items():
841 setattr(self, attr, val)
842
Greg Wardeba20e62004-07-31 16:15:44 +0000843 def __str__(self):
844 return str(self.__dict__)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000845
Greg Wardeba20e62004-07-31 16:15:44 +0000846 __repr__ = _repr
847
Greg Wardab05edc2006-04-23 03:47:58 +0000848 def __cmp__(self, other):
Greg Wardeba20e62004-07-31 16:15:44 +0000849 if isinstance(other, Values):
Greg Wardab05edc2006-04-23 03:47:58 +0000850 return cmp(self.__dict__, other.__dict__)
851 elif isinstance(other, types.DictType):
852 return cmp(self.__dict__, other)
Greg Wardeba20e62004-07-31 16:15:44 +0000853 else:
Greg Wardab05edc2006-04-23 03:47:58 +0000854 return -1
Greg Wardeba20e62004-07-31 16:15:44 +0000855
856 def _update_careful(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000857 """
858 Update the option values from an arbitrary dictionary, but only
859 use keys from dict that already have a corresponding attribute
860 in self. Any keys in dict without a corresponding attribute
861 are silently ignored.
862 """
863 for attr in dir(self):
Raymond Hettinger930795b2008-07-10 15:37:08 +0000864 if attr in dict:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000865 dval = dict[attr]
866 if dval is not None:
867 setattr(self, attr, dval)
868
Greg Wardeba20e62004-07-31 16:15:44 +0000869 def _update_loose(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000870 """
871 Update the option values from an arbitrary dictionary,
872 using all keys from the dictionary regardless of whether
873 they have a corresponding attribute in self or not.
874 """
875 self.__dict__.update(dict)
876
Greg Wardeba20e62004-07-31 16:15:44 +0000877 def _update(self, dict, mode):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000878 if mode == "careful":
879 self._update_careful(dict)
880 elif mode == "loose":
881 self._update_loose(dict)
882 else:
883 raise ValueError, "invalid update mode: %r" % mode
884
Greg Wardeba20e62004-07-31 16:15:44 +0000885 def read_module(self, modname, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000886 __import__(modname)
887 mod = sys.modules[modname]
888 self._update(vars(mod), mode)
889
Greg Wardeba20e62004-07-31 16:15:44 +0000890 def read_file(self, filename, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000891 vars = {}
892 execfile(filename, vars)
893 self._update(vars, mode)
894
Greg Wardeba20e62004-07-31 16:15:44 +0000895 def ensure_value(self, attr, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000896 if not hasattr(self, attr) or getattr(self, attr) is None:
897 setattr(self, attr, value)
898 return getattr(self, attr)
899
900
901class OptionContainer:
902
903 """
904 Abstract base class.
905
906 Class attributes:
907 standard_option_list : [Option]
908 list of standard options that will be accepted by all instances
909 of this parser class (intended to be overridden by subclasses).
910
911 Instance attributes:
912 option_list : [Option]
913 the list of Option objects contained by this OptionContainer
914 _short_opt : { string : Option }
915 dictionary mapping short option strings, eg. "-f" or "-X",
916 to the Option instances that implement them. If an Option
Martin Panter5b48fa92016-04-19 04:03:41 +0000917 has multiple short option strings, it will appear in this
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000918 dictionary multiple times. [1]
919 _long_opt : { string : Option }
920 dictionary mapping long option strings, eg. "--file" or
921 "--exclude", to the Option instances that implement them.
922 Again, a given Option can occur multiple times in this
923 dictionary. [1]
924 defaults : { string : any }
925 dictionary mapping option destination names to default
926 values for each destination [1]
927
928 [1] These mappings are common to (shared by) all components of the
929 controlling OptionParser, where they are initially created.
930
931 """
932
Greg Wardeba20e62004-07-31 16:15:44 +0000933 def __init__(self, option_class, conflict_handler, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000934 # Initialize the option list and related data structures.
935 # This method must be provided by subclasses, and it must
936 # initialize at least the following instance attributes:
937 # option_list, _short_opt, _long_opt, defaults.
938 self._create_option_list()
939
940 self.option_class = option_class
941 self.set_conflict_handler(conflict_handler)
942 self.set_description(description)
943
Greg Wardeba20e62004-07-31 16:15:44 +0000944 def _create_option_mappings(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000945 # For use by OptionParser constructor -- create the master
946 # option mappings used by this OptionParser and all
947 # OptionGroups that it owns.
948 self._short_opt = {} # single letter -> Option instance
949 self._long_opt = {} # long option -> Option instance
950 self.defaults = {} # maps option dest -> default value
951
952
Greg Wardeba20e62004-07-31 16:15:44 +0000953 def _share_option_mappings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000954 # For use by OptionGroup constructor -- use shared option
955 # mappings from the OptionParser that owns this OptionGroup.
956 self._short_opt = parser._short_opt
957 self._long_opt = parser._long_opt
958 self.defaults = parser.defaults
959
Greg Wardeba20e62004-07-31 16:15:44 +0000960 def set_conflict_handler(self, handler):
Greg Ward48aa84b2004-10-27 02:20:04 +0000961 if handler not in ("error", "resolve"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000962 raise ValueError, "invalid conflict_resolution value %r" % handler
963 self.conflict_handler = handler
964
Greg Wardeba20e62004-07-31 16:15:44 +0000965 def set_description(self, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000966 self.description = description
967
Greg Wardeba20e62004-07-31 16:15:44 +0000968 def get_description(self):
969 return self.description
970
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000971
Greg Wardab05edc2006-04-23 03:47:58 +0000972 def destroy(self):
973 """see OptionParser.destroy()."""
974 del self._short_opt
975 del self._long_opt
976 del self.defaults
977
978
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000979 # -- Option-adding methods -----------------------------------------
980
Greg Wardeba20e62004-07-31 16:15:44 +0000981 def _check_conflict(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000982 conflict_opts = []
983 for opt in option._short_opts:
Raymond Hettinger930795b2008-07-10 15:37:08 +0000984 if opt in self._short_opt:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000985 conflict_opts.append((opt, self._short_opt[opt]))
986 for opt in option._long_opts:
Raymond Hettinger930795b2008-07-10 15:37:08 +0000987 if opt in self._long_opt:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000988 conflict_opts.append((opt, self._long_opt[opt]))
989
990 if conflict_opts:
991 handler = self.conflict_handler
Greg Ward48aa84b2004-10-27 02:20:04 +0000992 if handler == "error":
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000993 raise OptionConflictError(
994 "conflicting option string(s): %s"
995 % ", ".join([co[0] for co in conflict_opts]),
996 option)
Greg Ward48aa84b2004-10-27 02:20:04 +0000997 elif handler == "resolve":
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000998 for (opt, c_option) in conflict_opts:
999 if opt.startswith("--"):
1000 c_option._long_opts.remove(opt)
1001 del self._long_opt[opt]
1002 else:
1003 c_option._short_opts.remove(opt)
1004 del self._short_opt[opt]
1005 if not (c_option._short_opts or c_option._long_opts):
1006 c_option.container.option_list.remove(c_option)
1007
Greg Wardeba20e62004-07-31 16:15:44 +00001008 def add_option(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001009 """add_option(Option)
1010 add_option(opt_str, ..., kwarg=val, ...)
1011 """
R. David Murray3caf7b92010-07-05 16:06:05 +00001012 if type(args[0]) in types.StringTypes:
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001013 option = self.option_class(*args, **kwargs)
1014 elif len(args) == 1 and not kwargs:
1015 option = args[0]
1016 if not isinstance(option, Option):
1017 raise TypeError, "not an Option instance: %r" % option
1018 else:
1019 raise TypeError, "invalid arguments"
1020
1021 self._check_conflict(option)
1022
1023 self.option_list.append(option)
1024 option.container = self
1025 for opt in option._short_opts:
1026 self._short_opt[opt] = option
1027 for opt in option._long_opts:
1028 self._long_opt[opt] = option
1029
1030 if option.dest is not None: # option has a dest, we need a default
1031 if option.default is not NO_DEFAULT:
1032 self.defaults[option.dest] = option.default
Raymond Hettinger930795b2008-07-10 15:37:08 +00001033 elif option.dest not in self.defaults:
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001034 self.defaults[option.dest] = None
1035
1036 return option
1037
Greg Wardeba20e62004-07-31 16:15:44 +00001038 def add_options(self, option_list):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001039 for option in option_list:
1040 self.add_option(option)
1041
1042 # -- Option query/removal methods ----------------------------------
1043
Greg Wardeba20e62004-07-31 16:15:44 +00001044 def get_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001045 return (self._short_opt.get(opt_str) or
1046 self._long_opt.get(opt_str))
1047
Greg Wardeba20e62004-07-31 16:15:44 +00001048 def has_option(self, opt_str):
Raymond Hettinger930795b2008-07-10 15:37:08 +00001049 return (opt_str in self._short_opt or
1050 opt_str in self._long_opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001051
Greg Wardeba20e62004-07-31 16:15:44 +00001052 def remove_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001053 option = self._short_opt.get(opt_str)
1054 if option is None:
1055 option = self._long_opt.get(opt_str)
1056 if option is None:
1057 raise ValueError("no such option %r" % opt_str)
1058
1059 for opt in option._short_opts:
1060 del self._short_opt[opt]
1061 for opt in option._long_opts:
1062 del self._long_opt[opt]
1063 option.container.option_list.remove(option)
1064
1065
1066 # -- Help-formatting methods ---------------------------------------
1067
Greg Wardeba20e62004-07-31 16:15:44 +00001068 def format_option_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001069 if not self.option_list:
1070 return ""
1071 result = []
1072 for option in self.option_list:
1073 if not option.help is SUPPRESS_HELP:
1074 result.append(formatter.format_option(option))
1075 return "".join(result)
1076
Greg Wardeba20e62004-07-31 16:15:44 +00001077 def format_description(self, formatter):
1078 return formatter.format_description(self.get_description())
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001079
Greg Wardeba20e62004-07-31 16:15:44 +00001080 def format_help(self, formatter):
1081 result = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001082 if self.description:
Greg Wardeba20e62004-07-31 16:15:44 +00001083 result.append(self.format_description(formatter))
1084 if self.option_list:
1085 result.append(self.format_option_help(formatter))
1086 return "\n".join(result)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001087
1088
1089class OptionGroup (OptionContainer):
1090
Greg Wardeba20e62004-07-31 16:15:44 +00001091 def __init__(self, parser, title, description=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001092 self.parser = parser
1093 OptionContainer.__init__(
1094 self, parser.option_class, parser.conflict_handler, description)
1095 self.title = title
1096
Greg Wardeba20e62004-07-31 16:15:44 +00001097 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001098 self.option_list = []
1099 self._share_option_mappings(self.parser)
1100
Greg Wardeba20e62004-07-31 16:15:44 +00001101 def set_title(self, title):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001102 self.title = title
1103
Greg Wardab05edc2006-04-23 03:47:58 +00001104 def destroy(self):
1105 """see OptionParser.destroy()."""
1106 OptionContainer.destroy(self)
1107 del self.option_list
1108
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001109 # -- Help-formatting methods ---------------------------------------
1110
Greg Wardeba20e62004-07-31 16:15:44 +00001111 def format_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001112 result = formatter.format_heading(self.title)
1113 formatter.indent()
1114 result += OptionContainer.format_help(self, formatter)
1115 formatter.dedent()
1116 return result
1117
1118
1119class OptionParser (OptionContainer):
1120
1121 """
1122 Class attributes:
1123 standard_option_list : [Option]
1124 list of standard options that will be accepted by all instances
1125 of this parser class (intended to be overridden by subclasses).
1126
1127 Instance attributes:
1128 usage : string
1129 a usage string for your program. Before it is displayed
1130 to the user, "%prog" will be expanded to the name of
Greg Ward2492fcf2003-04-21 02:40:34 +00001131 your program (self.prog or os.path.basename(sys.argv[0])).
1132 prog : string
1133 the name of the current program (to override
1134 os.path.basename(sys.argv[0])).
R David Murraya436e712011-05-04 21:05:52 -04001135 description : string
1136 A paragraph of text giving a brief overview of your program.
1137 optparse reformats this paragraph to fit the current terminal
1138 width and prints it when the user requests help (after usage,
1139 but before the list of options).
Greg Wardab05edc2006-04-23 03:47:58 +00001140 epilog : string
1141 paragraph of help text to print after option help
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001142
Greg Wardeba20e62004-07-31 16:15:44 +00001143 option_groups : [OptionGroup]
1144 list of option groups in this parser (option groups are
1145 irrelevant for parsing the command-line, but very useful
1146 for generating help)
1147
1148 allow_interspersed_args : bool = true
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001149 if true, positional arguments may be interspersed with options.
1150 Assuming -a and -b each take a single argument, the command-line
1151 -ablah foo bar -bboo baz
1152 will be interpreted the same as
1153 -ablah -bboo -- foo bar baz
1154 If this flag were false, that command line would be interpreted as
1155 -ablah -- foo bar -bboo baz
1156 -- ie. we stop processing options as soon as we see the first
1157 non-option argument. (This is the tradition followed by
1158 Python's getopt module, Perl's Getopt::Std, and other argument-
1159 parsing libraries, but it is generally annoying to users.)
1160
Greg Wardeba20e62004-07-31 16:15:44 +00001161 process_default_values : bool = true
1162 if true, option default values are processed similarly to option
1163 values from the command line: that is, they are passed to the
1164 type-checking function for the option's type (as long as the
1165 default value is a string). (This really only matters if you
1166 have defined custom types; see SF bug #955889.) Set it to false
1167 to restore the behaviour of Optik 1.4.1 and earlier.
1168
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001169 rargs : [string]
1170 the argument list currently being parsed. Only set when
1171 parse_args() is active, and continually trimmed down as
1172 we consume arguments. Mainly there for the benefit of
1173 callback options.
1174 largs : [string]
1175 the list of leftover arguments that we have skipped while
1176 parsing options. If allow_interspersed_args is false, this
1177 list is always empty.
1178 values : Values
1179 the set of option values currently being accumulated. Only
1180 set when parse_args() is active. Also mainly for callbacks.
1181
1182 Because of the 'rargs', 'largs', and 'values' attributes,
1183 OptionParser is not thread-safe. If, for some perverse reason, you
1184 need to parse command-line arguments simultaneously in different
1185 threads, use different OptionParser instances.
1186
1187 """
1188
1189 standard_option_list = []
1190
Greg Wardeba20e62004-07-31 16:15:44 +00001191 def __init__(self,
1192 usage=None,
1193 option_list=None,
1194 option_class=Option,
1195 version=None,
1196 conflict_handler="error",
1197 description=None,
1198 formatter=None,
1199 add_help_option=True,
Greg Wardab05edc2006-04-23 03:47:58 +00001200 prog=None,
1201 epilog=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001202 OptionContainer.__init__(
1203 self, option_class, conflict_handler, description)
1204 self.set_usage(usage)
Greg Ward2492fcf2003-04-21 02:40:34 +00001205 self.prog = prog
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001206 self.version = version
Greg Wardeba20e62004-07-31 16:15:44 +00001207 self.allow_interspersed_args = True
1208 self.process_default_values = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001209 if formatter is None:
1210 formatter = IndentedHelpFormatter()
1211 self.formatter = formatter
Greg Wardeba20e62004-07-31 16:15:44 +00001212 self.formatter.set_parser(self)
Greg Wardab05edc2006-04-23 03:47:58 +00001213 self.epilog = epilog
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001214
1215 # Populate the option list; initial sources are the
1216 # standard_option_list class attribute, the 'option_list'
Greg Wardeba20e62004-07-31 16:15:44 +00001217 # argument, and (if applicable) the _add_version_option() and
1218 # _add_help_option() methods.
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001219 self._populate_option_list(option_list,
1220 add_help=add_help_option)
1221
1222 self._init_parsing_state()
1223
Greg Wardab05edc2006-04-23 03:47:58 +00001224
1225 def destroy(self):
1226 """
1227 Declare that you are done with this OptionParser. This cleans up
1228 reference cycles so the OptionParser (and all objects referenced by
Tim Peters4f96f1f2006-06-11 19:42:51 +00001229 it) can be garbage-collected promptly. After calling destroy(), the
Greg Wardab05edc2006-04-23 03:47:58 +00001230 OptionParser is unusable.
1231 """
1232 OptionContainer.destroy(self)
1233 for group in self.option_groups:
1234 group.destroy()
1235 del self.option_list
1236 del self.option_groups
1237 del self.formatter
1238
1239
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001240 # -- Private methods -----------------------------------------------
1241 # (used by our or OptionContainer's constructor)
1242
Greg Wardeba20e62004-07-31 16:15:44 +00001243 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001244 self.option_list = []
1245 self.option_groups = []
1246 self._create_option_mappings()
1247
Greg Wardeba20e62004-07-31 16:15:44 +00001248 def _add_help_option(self):
1249 self.add_option("-h", "--help",
1250 action="help",
1251 help=_("show this help message and exit"))
1252
1253 def _add_version_option(self):
1254 self.add_option("--version",
1255 action="version",
1256 help=_("show program's version number and exit"))
1257
1258 def _populate_option_list(self, option_list, add_help=True):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001259 if self.standard_option_list:
1260 self.add_options(self.standard_option_list)
1261 if option_list:
1262 self.add_options(option_list)
1263 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001264 self._add_version_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001265 if add_help:
Greg Wardeba20e62004-07-31 16:15:44 +00001266 self._add_help_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001267
Greg Wardeba20e62004-07-31 16:15:44 +00001268 def _init_parsing_state(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001269 # These are set in parse_args() for the convenience of callbacks.
1270 self.rargs = None
1271 self.largs = None
1272 self.values = None
1273
1274
1275 # -- Simple modifier methods ---------------------------------------
1276
Greg Wardeba20e62004-07-31 16:15:44 +00001277 def set_usage(self, usage):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001278 if usage is None:
Greg Wardeba20e62004-07-31 16:15:44 +00001279 self.usage = _("%prog [options]")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001280 elif usage is SUPPRESS_USAGE:
1281 self.usage = None
Greg Wardeba20e62004-07-31 16:15:44 +00001282 # For backwards compatibility with Optik 1.3 and earlier.
Greg Wardab05edc2006-04-23 03:47:58 +00001283 elif usage.lower().startswith("usage: "):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001284 self.usage = usage[7:]
1285 else:
1286 self.usage = usage
1287
Greg Wardeba20e62004-07-31 16:15:44 +00001288 def enable_interspersed_args(self):
Andrew M. Kuchlingdcf3b1c2008-10-05 00:11:56 +00001289 """Set parsing to not stop on the first non-option, allowing
1290 interspersing switches with command arguments. This is the
1291 default behavior. See also disable_interspersed_args() and the
1292 class documentation description of the attribute
1293 allow_interspersed_args."""
Greg Wardeba20e62004-07-31 16:15:44 +00001294 self.allow_interspersed_args = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001295
Greg Wardeba20e62004-07-31 16:15:44 +00001296 def disable_interspersed_args(self):
Andrew M. Kuchlingdcf3b1c2008-10-05 00:11:56 +00001297 """Set parsing to stop on the first non-option. Use this if
1298 you have a command processor which runs another command that
1299 has options of its own and you want to make sure these options
1300 don't get confused.
1301 """
Greg Wardeba20e62004-07-31 16:15:44 +00001302 self.allow_interspersed_args = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001303
Greg Wardeba20e62004-07-31 16:15:44 +00001304 def set_process_default_values(self, process):
1305 self.process_default_values = process
1306
1307 def set_default(self, dest, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001308 self.defaults[dest] = value
1309
Greg Wardeba20e62004-07-31 16:15:44 +00001310 def set_defaults(self, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001311 self.defaults.update(kwargs)
1312
Greg Wardeba20e62004-07-31 16:15:44 +00001313 def _get_all_options(self):
1314 options = self.option_list[:]
1315 for group in self.option_groups:
1316 options.extend(group.option_list)
1317 return options
1318
1319 def get_default_values(self):
1320 if not self.process_default_values:
1321 # Old, pre-Optik 1.5 behaviour.
1322 return Values(self.defaults)
1323
1324 defaults = self.defaults.copy()
1325 for option in self._get_all_options():
1326 default = defaults.get(option.dest)
Greg Wardab05edc2006-04-23 03:47:58 +00001327 if isbasestring(default):
Greg Wardeba20e62004-07-31 16:15:44 +00001328 opt_str = option.get_opt_string()
1329 defaults[option.dest] = option.check_value(opt_str, default)
1330
1331 return Values(defaults)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001332
1333
1334 # -- OptionGroup methods -------------------------------------------
1335
Greg Wardeba20e62004-07-31 16:15:44 +00001336 def add_option_group(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001337 # XXX lots of overlap with OptionContainer.add_option()
Greg Wardab05edc2006-04-23 03:47:58 +00001338 if type(args[0]) is types.StringType:
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001339 group = OptionGroup(self, *args, **kwargs)
1340 elif len(args) == 1 and not kwargs:
1341 group = args[0]
1342 if not isinstance(group, OptionGroup):
1343 raise TypeError, "not an OptionGroup instance: %r" % group
1344 if group.parser is not self:
1345 raise ValueError, "invalid OptionGroup (wrong parser)"
1346 else:
1347 raise TypeError, "invalid arguments"
1348
1349 self.option_groups.append(group)
1350 return group
1351
Greg Wardeba20e62004-07-31 16:15:44 +00001352 def get_option_group(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001353 option = (self._short_opt.get(opt_str) or
1354 self._long_opt.get(opt_str))
1355 if option and option.container is not self:
1356 return option.container
1357 return None
1358
1359
1360 # -- Option-parsing methods ----------------------------------------
1361
Greg Wardeba20e62004-07-31 16:15:44 +00001362 def _get_args(self, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001363 if args is None:
1364 return sys.argv[1:]
1365 else:
1366 return args[:] # don't modify caller's list
1367
Greg Wardeba20e62004-07-31 16:15:44 +00001368 def parse_args(self, args=None, values=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001369 """
1370 parse_args(args : [string] = sys.argv[1:],
1371 values : Values = None)
1372 -> (values : Values, args : [string])
1373
1374 Parse the command-line options found in 'args' (default:
1375 sys.argv[1:]). Any errors result in a call to 'error()', which
1376 by default prints the usage message to stderr and calls
1377 sys.exit() with an error message. On success returns a pair
Serhiy Storchaka9a118f12016-04-17 09:37:36 +03001378 (values, args) where 'values' is a Values instance (with all
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001379 your option values) and 'args' is the list of arguments left
1380 over after parsing options.
1381 """
1382 rargs = self._get_args(args)
1383 if values is None:
1384 values = self.get_default_values()
1385
1386 # Store the halves of the argument list as attributes for the
1387 # convenience of callbacks:
1388 # rargs
1389 # the rest of the command-line (the "r" stands for
1390 # "remaining" or "right-hand")
1391 # largs
1392 # the leftover arguments -- ie. what's left after removing
1393 # options and their arguments (the "l" stands for "leftover"
1394 # or "left-hand")
1395 self.rargs = rargs
1396 self.largs = largs = []
1397 self.values = values
1398
1399 try:
1400 stop = self._process_args(largs, rargs, values)
1401 except (BadOptionError, OptionValueError), err:
Greg Wardab05edc2006-04-23 03:47:58 +00001402 self.error(str(err))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001403
1404 args = largs + rargs
1405 return self.check_values(values, args)
1406
Greg Wardeba20e62004-07-31 16:15:44 +00001407 def check_values(self, values, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001408 """
1409 check_values(values : Values, args : [string])
1410 -> (values : Values, args : [string])
1411
1412 Check that the supplied option values and leftover arguments are
1413 valid. Returns the option values and leftover arguments
1414 (possibly adjusted, possibly completely new -- whatever you
1415 like). Default implementation just returns the passed-in
1416 values; subclasses may override as desired.
1417 """
1418 return (values, args)
1419
Greg Wardeba20e62004-07-31 16:15:44 +00001420 def _process_args(self, largs, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001421 """_process_args(largs : [string],
1422 rargs : [string],
1423 values : Values)
1424
1425 Process command-line arguments and populate 'values', consuming
1426 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1427 false, stop at the first non-option argument. If true, accumulate any
1428 interspersed non-option arguments in 'largs'.
1429 """
1430 while rargs:
1431 arg = rargs[0]
1432 # We handle bare "--" explicitly, and bare "-" is handled by the
1433 # standard arg handler since the short arg case ensures that the
1434 # len of the opt string is greater than 1.
1435 if arg == "--":
1436 del rargs[0]
1437 return
1438 elif arg[0:2] == "--":
1439 # process a single long option (possibly with value(s))
1440 self._process_long_opt(rargs, values)
1441 elif arg[:1] == "-" and len(arg) > 1:
1442 # process a cluster of short options (possibly with
1443 # value(s) for the last one only)
1444 self._process_short_opts(rargs, values)
1445 elif self.allow_interspersed_args:
1446 largs.append(arg)
1447 del rargs[0]
1448 else:
1449 return # stop now, leave this arg in rargs
1450
1451 # Say this is the original argument list:
1452 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1453 # ^
1454 # (we are about to process arg(i)).
1455 #
1456 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1457 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1458 # been removed from largs).
1459 #
1460 # The while loop will usually consume 1 or more arguments per pass.
1461 # If it consumes 1 (eg. arg is an option that takes no arguments),
1462 # then after _process_arg() is done the situation is:
1463 #
1464 # largs = subset of [arg0, ..., arg(i)]
1465 # rargs = [arg(i+1), ..., arg(N-1)]
1466 #
1467 # If allow_interspersed_args is false, largs will always be
1468 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1469 # not a very interesting subset!
1470
Greg Wardeba20e62004-07-31 16:15:44 +00001471 def _match_long_opt(self, opt):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001472 """_match_long_opt(opt : string) -> string
1473
1474 Determine which long option string 'opt' matches, ie. which one
Ezio Melottif5469cf2013-08-17 15:43:51 +03001475 it is an unambiguous abbreviation for. Raises BadOptionError if
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001476 'opt' doesn't unambiguously match any long option string.
1477 """
1478 return _match_abbrev(opt, self._long_opt)
1479
Greg Wardeba20e62004-07-31 16:15:44 +00001480 def _process_long_opt(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001481 arg = rargs.pop(0)
1482
1483 # Value explicitly attached to arg? Pretend it's the next
1484 # argument.
1485 if "=" in arg:
1486 (opt, next_arg) = arg.split("=", 1)
1487 rargs.insert(0, next_arg)
Greg Wardeba20e62004-07-31 16:15:44 +00001488 had_explicit_value = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001489 else:
1490 opt = arg
Greg Wardeba20e62004-07-31 16:15:44 +00001491 had_explicit_value = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001492
1493 opt = self._match_long_opt(opt)
1494 option = self._long_opt[opt]
1495 if option.takes_value():
1496 nargs = option.nargs
1497 if len(rargs) < nargs:
1498 if nargs == 1:
Greg Wardeba20e62004-07-31 16:15:44 +00001499 self.error(_("%s option requires an argument") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001500 else:
Greg Wardeba20e62004-07-31 16:15:44 +00001501 self.error(_("%s option requires %d arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001502 % (opt, nargs))
1503 elif nargs == 1:
1504 value = rargs.pop(0)
1505 else:
1506 value = tuple(rargs[0:nargs])
1507 del rargs[0:nargs]
1508
1509 elif had_explicit_value:
Greg Wardeba20e62004-07-31 16:15:44 +00001510 self.error(_("%s option does not take a value") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001511
1512 else:
1513 value = None
1514
1515 option.process(opt, value, values, self)
1516
Greg Wardeba20e62004-07-31 16:15:44 +00001517 def _process_short_opts(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001518 arg = rargs.pop(0)
Greg Wardeba20e62004-07-31 16:15:44 +00001519 stop = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001520 i = 1
1521 for ch in arg[1:]:
1522 opt = "-" + ch
1523 option = self._short_opt.get(opt)
1524 i += 1 # we have consumed a character
1525
1526 if not option:
Greg Wardab05edc2006-04-23 03:47:58 +00001527 raise BadOptionError(opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001528 if option.takes_value():
1529 # Any characters left in arg? Pretend they're the
1530 # next arg, and stop consuming characters of arg.
1531 if i < len(arg):
1532 rargs.insert(0, arg[i:])
Greg Wardeba20e62004-07-31 16:15:44 +00001533 stop = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001534
1535 nargs = option.nargs
1536 if len(rargs) < nargs:
1537 if nargs == 1:
Greg Wardeba20e62004-07-31 16:15:44 +00001538 self.error(_("%s option requires an argument") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001539 else:
Greg Wardeba20e62004-07-31 16:15:44 +00001540 self.error(_("%s option requires %d arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001541 % (opt, nargs))
1542 elif nargs == 1:
1543 value = rargs.pop(0)
1544 else:
1545 value = tuple(rargs[0:nargs])
1546 del rargs[0:nargs]
1547
1548 else: # option doesn't take a value
1549 value = None
1550
1551 option.process(opt, value, values, self)
1552
1553 if stop:
1554 break
1555
1556
1557 # -- Feedback methods ----------------------------------------------
1558
Greg Wardeba20e62004-07-31 16:15:44 +00001559 def get_prog_name(self):
1560 if self.prog is None:
1561 return os.path.basename(sys.argv[0])
1562 else:
1563 return self.prog
1564
1565 def expand_prog_name(self, s):
1566 return s.replace("%prog", self.get_prog_name())
1567
1568 def get_description(self):
1569 return self.expand_prog_name(self.description)
1570
Greg Ward48aa84b2004-10-27 02:20:04 +00001571 def exit(self, status=0, msg=None):
1572 if msg:
1573 sys.stderr.write(msg)
1574 sys.exit(status)
1575
Greg Wardeba20e62004-07-31 16:15:44 +00001576 def error(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001577 """error(msg : string)
1578
1579 Print a usage message incorporating 'msg' to stderr and exit.
1580 If you override this in a subclass, it should not return -- it
1581 should either exit or raise an exception.
1582 """
1583 self.print_usage(sys.stderr)
Greg Ward48aa84b2004-10-27 02:20:04 +00001584 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001585
Greg Wardeba20e62004-07-31 16:15:44 +00001586 def get_usage(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001587 if self.usage:
1588 return self.formatter.format_usage(
Greg Wardeba20e62004-07-31 16:15:44 +00001589 self.expand_prog_name(self.usage))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001590 else:
1591 return ""
1592
Greg Wardeba20e62004-07-31 16:15:44 +00001593 def print_usage(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001594 """print_usage(file : file = stdout)
1595
1596 Print the usage message for the current program (self.usage) to
Mark Dickinson3e4caeb2009-02-21 20:27:01 +00001597 'file' (default stdout). Any occurrence of the string "%prog" in
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001598 self.usage is replaced with the name of the current program
1599 (basename of sys.argv[0]). Does nothing if self.usage is empty
1600 or not defined.
1601 """
1602 if self.usage:
1603 print >>file, self.get_usage()
1604
Greg Wardeba20e62004-07-31 16:15:44 +00001605 def get_version(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001606 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001607 return self.expand_prog_name(self.version)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001608 else:
1609 return ""
1610
Greg Wardeba20e62004-07-31 16:15:44 +00001611 def print_version(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001612 """print_version(file : file = stdout)
1613
1614 Print the version message for this program (self.version) to
Mark Dickinson3e4caeb2009-02-21 20:27:01 +00001615 'file' (default stdout). As with print_usage(), any occurrence
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001616 of "%prog" in self.version is replaced by the current program's
1617 name. Does nothing if self.version is empty or undefined.
1618 """
1619 if self.version:
1620 print >>file, self.get_version()
1621
Greg Wardeba20e62004-07-31 16:15:44 +00001622 def format_option_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001623 if formatter is None:
1624 formatter = self.formatter
1625 formatter.store_option_strings(self)
1626 result = []
Greg Wardab05edc2006-04-23 03:47:58 +00001627 result.append(formatter.format_heading(_("Options")))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001628 formatter.indent()
1629 if self.option_list:
1630 result.append(OptionContainer.format_option_help(self, formatter))
1631 result.append("\n")
1632 for group in self.option_groups:
1633 result.append(group.format_help(formatter))
1634 result.append("\n")
1635 formatter.dedent()
1636 # Drop the last "\n", or the header if no options or option groups:
1637 return "".join(result[:-1])
1638
Greg Wardab05edc2006-04-23 03:47:58 +00001639 def format_epilog(self, formatter):
1640 return formatter.format_epilog(self.epilog)
1641
Greg Wardeba20e62004-07-31 16:15:44 +00001642 def format_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001643 if formatter is None:
1644 formatter = self.formatter
1645 result = []
1646 if self.usage:
1647 result.append(self.get_usage() + "\n")
1648 if self.description:
1649 result.append(self.format_description(formatter) + "\n")
1650 result.append(self.format_option_help(formatter))
Greg Wardab05edc2006-04-23 03:47:58 +00001651 result.append(self.format_epilog(formatter))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001652 return "".join(result)
1653
Greg Ward0e0c9f42006-06-11 16:24:11 +00001654 # used by test suite
1655 def _get_encoding(self, file):
Greg Ward48fae7a2006-07-23 16:05:51 +00001656 encoding = getattr(file, "encoding", None)
1657 if not encoding:
1658 encoding = sys.getdefaultencoding()
1659 return encoding
Greg Ward0e0c9f42006-06-11 16:24:11 +00001660
Greg Wardeba20e62004-07-31 16:15:44 +00001661 def print_help(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001662 """print_help(file : file = stdout)
1663
1664 Print an extended help message, listing all options and any
1665 help text provided with them, to 'file' (default stdout).
1666 """
1667 if file is None:
1668 file = sys.stdout
Greg Ward0e0c9f42006-06-11 16:24:11 +00001669 encoding = self._get_encoding(file)
1670 file.write(self.format_help().encode(encoding, "replace"))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001671
1672# class OptionParser
1673
1674
Greg Wardeba20e62004-07-31 16:15:44 +00001675def _match_abbrev(s, wordmap):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001676 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1677
1678 Return the string key in 'wordmap' for which 's' is an unambiguous
1679 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1680 'words', raise BadOptionError.
1681 """
1682 # Is there an exact match?
Raymond Hettinger930795b2008-07-10 15:37:08 +00001683 if s in wordmap:
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001684 return s
1685 else:
1686 # Isolate all words with s as a prefix.
1687 possibilities = [word for word in wordmap.keys()
1688 if word.startswith(s)]
1689 # No exact match, so there had better be just one possibility.
1690 if len(possibilities) == 1:
1691 return possibilities[0]
1692 elif not possibilities:
Greg Wardab05edc2006-04-23 03:47:58 +00001693 raise BadOptionError(s)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001694 else:
1695 # More than one possible completion: ambiguous prefix.
Armin Rigoa3f09272006-05-28 19:13:17 +00001696 possibilities.sort()
Greg Wardab05edc2006-04-23 03:47:58 +00001697 raise AmbiguousOptionError(s, possibilities)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001698
1699
1700# Some day, there might be many Option classes. As of Optik 1.3, the
1701# preferred way to instantiate Options is indirectly, via make_option(),
1702# which will become a factory function when there are many Option
1703# classes.
1704make_option = Option