blob: e8ac1e156a2b29c1e8dd686219a581c4adced6f6 [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).
Georg Brandlf3532df2009-04-27 16:41:41 +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
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024__version__ = "1.5.3"
Greg Ward2492fcf2003-04-21 02:40:34 +000025
Greg Ward4656ed42003-05-08 01:38:52 +000026__all__ = ['Option',
Benjamin Petersond23f8222009-04-05 19:13:16 +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',
Martin Panter19e69c52015-11-14 12:46:42 +000041 'BadOptionError',
42 'check_choice']
Greg Ward2492fcf2003-04-21 02:40:34 +000043
Guido van Rossumb9ba4582002-11-14 22:00:19 +000044__copyright__ = """
Thomas Wouters477c8d52006-05-27 19:21:47 +000045Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
46Copyright (c) 2002-2006 Python Software Foundation. All rights reserved.
Guido van Rossumb9ba4582002-11-14 22:00:19 +000047
48Redistribution and use in source and binary forms, with or without
49modification, are permitted provided that the following conditions are
50met:
51
52 * Redistributions of source code must retain the above copyright
53 notice, this list of conditions and the following disclaimer.
54
55 * Redistributions in binary form must reproduce the above copyright
56 notice, this list of conditions and the following disclaimer in the
57 documentation and/or other materials provided with the distribution.
58
59 * Neither the name of the author nor the names of its
60 contributors may be used to endorse or promote products derived from
61 this software without specific prior written permission.
62
63THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
64IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
65TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
66PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
67CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
68EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
69PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
70PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
71LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
72NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
73SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
74"""
75
76import sys, os
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:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000084# Id: option_parser.py 527 2006-07-23 15:21:30Z greg
85# Id: option.py 522 2006-06-11 16:22:03Z gward
86# Id: help.py 527 2006-07-23 15:21:30Z greg
Thomas Wouters477c8d52006-05-27 19:21:47 +000087# Id: errors.py 509 2006-04-20 00:58:24Z gward
88
89try:
Éric Araujo6a1454f2011-03-20 19:59:25 +010090 from gettext import gettext, ngettext
Thomas Wouters477c8d52006-05-27 19:21:47 +000091except ImportError:
92 def gettext(message):
93 return message
Éric Araujo6a1454f2011-03-20 19:59:25 +010094
95 def ngettext(singular, plural, n):
96 if n == 1:
97 return singular
98 return plural
99
Thomas Wouters477c8d52006-05-27 19:21:47 +0000100_ = gettext
101
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000102
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000103class OptParseError (Exception):
Greg Wardeba20e62004-07-31 16:15:44 +0000104 def __init__(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000105 self.msg = msg
106
Greg Wardeba20e62004-07-31 16:15:44 +0000107 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000108 return self.msg
109
Greg Ward2492fcf2003-04-21 02:40:34 +0000110
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000111class OptionError (OptParseError):
112 """
113 Raised if an Option instance is created with invalid or
114 inconsistent arguments.
115 """
116
Greg Wardeba20e62004-07-31 16:15:44 +0000117 def __init__(self, msg, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000118 self.msg = msg
119 self.option_id = str(option)
120
Greg Wardeba20e62004-07-31 16:15:44 +0000121 def __str__(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000122 if self.option_id:
123 return "option %s: %s" % (self.option_id, self.msg)
124 else:
125 return self.msg
126
127class OptionConflictError (OptionError):
128 """
129 Raised if conflicting options are added to an OptionParser.
130 """
131
132class OptionValueError (OptParseError):
133 """
134 Raised if an invalid option value is encountered on the command
135 line.
136 """
137
138class BadOptionError (OptParseError):
139 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000140 Raised if an invalid option is seen on the command line.
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000141 """
Thomas Wouters477c8d52006-05-27 19:21:47 +0000142 def __init__(self, opt_str):
143 self.opt_str = opt_str
144
145 def __str__(self):
146 return _("no such option: %s") % self.opt_str
147
148class AmbiguousOptionError (BadOptionError):
149 """
150 Raised if an ambiguous option is seen on the command line.
151 """
152 def __init__(self, opt_str, possibilities):
153 BadOptionError.__init__(self, opt_str)
154 self.possibilities = possibilities
155
156 def __str__(self):
157 return (_("ambiguous option: %s (%s?)")
158 % (self.opt_str, ", ".join(self.possibilities)))
Greg Ward2492fcf2003-04-21 02:40:34 +0000159
160
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000161class HelpFormatter:
162
163 """
164 Abstract base class for formatting option help. OptionParser
165 instances should use one of the HelpFormatter subclasses for
166 formatting help; by default IndentedHelpFormatter is used.
167
168 Instance attributes:
Greg Wardeba20e62004-07-31 16:15:44 +0000169 parser : OptionParser
170 the controlling OptionParser instance
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000171 indent_increment : int
172 the number of columns to indent per nesting level
173 max_help_position : int
174 the maximum starting column for option help text
175 help_position : int
176 the calculated starting column for option help text;
177 initially the same as the maximum
178 width : int
Greg Wardeba20e62004-07-31 16:15:44 +0000179 total number of columns for output (pass None to constructor for
180 this value to be taken from the $COLUMNS environment variable)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000181 level : int
182 current indentation level
183 current_indent : int
184 current indentation level (in columns)
185 help_width : int
186 number of columns available for option help text (calculated)
Greg Wardeba20e62004-07-31 16:15:44 +0000187 default_tag : str
188 text to replace with each option's default value, "%default"
189 by default. Set to false value to disable default value expansion.
190 option_strings : { Option : str }
191 maps Option instances to the snippet of help text explaining
192 the syntax of that option, e.g. "-h, --help" or
193 "-fFILE, --file=FILE"
194 _short_opt_fmt : str
195 format string controlling how short options with values are
196 printed in help text. Must be either "%s%s" ("-fFILE") or
197 "%s %s" ("-f FILE"), because those are the two syntaxes that
198 Optik supports.
199 _long_opt_fmt : str
200 similar but for long options; must be either "%s %s" ("--file FILE")
201 or "%s=%s" ("--file=FILE").
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000202 """
203
Greg Wardeba20e62004-07-31 16:15:44 +0000204 NO_DEFAULT_VALUE = "none"
205
206 def __init__(self,
207 indent_increment,
208 max_help_position,
209 width,
210 short_first):
211 self.parser = None
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000212 self.indent_increment = indent_increment
Greg Wardeba20e62004-07-31 16:15:44 +0000213 if width is None:
214 try:
215 width = int(os.environ['COLUMNS'])
216 except (KeyError, ValueError):
217 width = 80
218 width -= 2
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000219 self.width = width
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200220 self.help_position = self.max_help_position = \
221 min(max_help_position, max(width - 20, indent_increment * 2))
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000222 self.current_indent = 0
223 self.level = 0
Greg Wardeba20e62004-07-31 16:15:44 +0000224 self.help_width = None # computed later
Greg Ward2492fcf2003-04-21 02:40:34 +0000225 self.short_first = short_first
Greg Wardeba20e62004-07-31 16:15:44 +0000226 self.default_tag = "%default"
227 self.option_strings = {}
228 self._short_opt_fmt = "%s %s"
229 self._long_opt_fmt = "%s=%s"
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000230
Greg Wardeba20e62004-07-31 16:15:44 +0000231 def set_parser(self, parser):
232 self.parser = parser
233
234 def set_short_opt_delimiter(self, delim):
235 if delim not in ("", " "):
236 raise ValueError(
237 "invalid metavar delimiter for short options: %r" % delim)
238 self._short_opt_fmt = "%s" + delim + "%s"
239
240 def set_long_opt_delimiter(self, delim):
241 if delim not in ("=", " "):
242 raise ValueError(
243 "invalid metavar delimiter for long options: %r" % delim)
244 self._long_opt_fmt = "%s" + delim + "%s"
245
246 def indent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000247 self.current_indent += self.indent_increment
248 self.level += 1
249
Greg Wardeba20e62004-07-31 16:15:44 +0000250 def dedent(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000251 self.current_indent -= self.indent_increment
252 assert self.current_indent >= 0, "Indent decreased below 0."
253 self.level -= 1
254
Greg Wardeba20e62004-07-31 16:15:44 +0000255 def format_usage(self, usage):
Collin Winterce36ad82007-08-30 01:19:48 +0000256 raise NotImplementedError("subclasses must implement")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000257
Greg Wardeba20e62004-07-31 16:15:44 +0000258 def format_heading(self, heading):
Collin Winterce36ad82007-08-30 01:19:48 +0000259 raise NotImplementedError("subclasses must implement")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000260
Thomas Wouters477c8d52006-05-27 19:21:47 +0000261 def _format_text(self, text):
262 """
263 Format a paragraph of free-form text for inclusion in the
264 help output at the current indentation level.
265 """
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200266 text_width = max(self.width - self.current_indent, 11)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000267 indent = " "*self.current_indent
Thomas Wouters477c8d52006-05-27 19:21:47 +0000268 return textwrap.fill(text,
269 text_width,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000270 initial_indent=indent,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000271 subsequent_indent=indent)
272
273 def format_description(self, description):
274 if description:
275 return self._format_text(description) + "\n"
276 else:
277 return ""
278
279 def format_epilog(self, epilog):
280 if epilog:
281 return "\n" + self._format_text(epilog) + "\n"
282 else:
283 return ""
284
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000285
Greg Wardeba20e62004-07-31 16:15:44 +0000286 def expand_default(self, option):
287 if self.parser is None or not self.default_tag:
288 return option.help
289
290 default_value = self.parser.defaults.get(option.dest)
291 if default_value is NO_DEFAULT or default_value is None:
292 default_value = self.NO_DEFAULT_VALUE
293
294 return option.help.replace(self.default_tag, str(default_value))
295
296 def format_option(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000297 # The help for each option consists of two parts:
298 # * the opt strings and metavars
299 # eg. ("-x", or "-fFILENAME, --file=FILENAME")
300 # * the user-supplied help string
301 # eg. ("turn on expert mode", "read data from FILENAME")
302 #
303 # If possible, we write both of these on the same line:
304 # -x turn on expert mode
305 #
306 # But if the opt string list is too long, we put the help
307 # string on a second line, indented to the same column it would
308 # start in if it fit on the first line.
309 # -fFILENAME, --file=FILENAME
310 # read data from FILENAME
311 result = []
Greg Wardeba20e62004-07-31 16:15:44 +0000312 opts = self.option_strings[option]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000313 opt_width = self.help_position - self.current_indent - 2
314 if len(opts) > opt_width:
315 opts = "%*s%s\n" % (self.current_indent, "", opts)
316 indent_first = self.help_position
317 else: # start help on same line as opts
318 opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
319 indent_first = 0
320 result.append(opts)
321 if option.help:
Greg Wardeba20e62004-07-31 16:15:44 +0000322 help_text = self.expand_default(option)
323 help_lines = textwrap.wrap(help_text, self.help_width)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000324 result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
325 result.extend(["%*s%s\n" % (self.help_position, "", line)
326 for line in help_lines[1:]])
327 elif opts[-1] != "\n":
328 result.append("\n")
329 return "".join(result)
330
Greg Wardeba20e62004-07-31 16:15:44 +0000331 def store_option_strings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000332 self.indent()
333 max_len = 0
334 for opt in parser.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.indent()
339 for group in parser.option_groups:
340 for opt in group.option_list:
341 strings = self.format_option_strings(opt)
Greg Wardeba20e62004-07-31 16:15:44 +0000342 self.option_strings[opt] = strings
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000343 max_len = max(max_len, len(strings) + self.current_indent)
344 self.dedent()
345 self.dedent()
346 self.help_position = min(max_len + 2, self.max_help_position)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200347 self.help_width = max(self.width - self.help_position, 11)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000348
Greg Wardeba20e62004-07-31 16:15:44 +0000349 def format_option_strings(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000350 """Return a comma-separated list of option strings & metavariables."""
Greg Ward2492fcf2003-04-21 02:40:34 +0000351 if option.takes_value():
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000352 metavar = option.metavar or option.dest.upper()
Greg Wardeba20e62004-07-31 16:15:44 +0000353 short_opts = [self._short_opt_fmt % (sopt, metavar)
354 for sopt in option._short_opts]
355 long_opts = [self._long_opt_fmt % (lopt, metavar)
356 for lopt in option._long_opts]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000357 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000358 short_opts = option._short_opts
359 long_opts = option._long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000360
Greg Ward2492fcf2003-04-21 02:40:34 +0000361 if self.short_first:
362 opts = short_opts + long_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000363 else:
Greg Ward2492fcf2003-04-21 02:40:34 +0000364 opts = long_opts + short_opts
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000365
Greg Ward2492fcf2003-04-21 02:40:34 +0000366 return ", ".join(opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000367
368class IndentedHelpFormatter (HelpFormatter):
369 """Format help with indented section bodies.
370 """
371
Greg Wardeba20e62004-07-31 16:15:44 +0000372 def __init__(self,
373 indent_increment=2,
374 max_help_position=24,
375 width=None,
376 short_first=1):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000377 HelpFormatter.__init__(
378 self, indent_increment, max_help_position, width, short_first)
379
Greg Wardeba20e62004-07-31 16:15:44 +0000380 def format_usage(self, usage):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000381 return _("Usage: %s\n") % usage
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000382
Greg Wardeba20e62004-07-31 16:15:44 +0000383 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000384 return "%*s%s:\n" % (self.current_indent, "", heading)
385
386
387class TitledHelpFormatter (HelpFormatter):
388 """Format help with underlined section headers.
389 """
390
Greg Wardeba20e62004-07-31 16:15:44 +0000391 def __init__(self,
392 indent_increment=0,
393 max_help_position=24,
394 width=None,
395 short_first=0):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000396 HelpFormatter.__init__ (
397 self, indent_increment, max_help_position, width, short_first)
398
Greg Wardeba20e62004-07-31 16:15:44 +0000399 def format_usage(self, usage):
400 return "%s %s\n" % (self.format_heading(_("Usage")), usage)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000401
Greg Wardeba20e62004-07-31 16:15:44 +0000402 def format_heading(self, heading):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000403 return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
Greg Ward2492fcf2003-04-21 02:40:34 +0000404
405
Thomas Wouters477c8d52006-05-27 19:21:47 +0000406def _parse_num(val, type):
407 if val[:2].lower() == "0x": # hexadecimal
408 radix = 16
409 elif val[:2].lower() == "0b": # binary
410 radix = 2
411 val = val[2:] or "0" # have to remove "0b" prefix
412 elif val[:1] == "0": # octal
413 radix = 8
414 else: # decimal
415 radix = 10
416
417 return type(val, radix)
418
419def _parse_int(val):
420 return _parse_num(val, int)
421
Thomas Wouters477c8d52006-05-27 19:21:47 +0000422_builtin_cvt = { "int" : (_parse_int, _("integer")),
Florent Xicluna2bb96f52011-10-23 22:11:00 +0200423 "long" : (_parse_int, _("integer")),
Greg Wardeba20e62004-07-31 16:15:44 +0000424 "float" : (float, _("floating-point")),
425 "complex" : (complex, _("complex")) }
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000426
Greg Wardeba20e62004-07-31 16:15:44 +0000427def check_builtin(option, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000428 (cvt, what) = _builtin_cvt[option.type]
429 try:
430 return cvt(value)
431 except ValueError:
432 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000433 _("option %s: invalid %s value: %r") % (opt, what, value))
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000434
435def check_choice(option, opt, value):
436 if value in option.choices:
437 return value
438 else:
439 choices = ", ".join(map(repr, option.choices))
440 raise OptionValueError(
Greg Wardeba20e62004-07-31 16:15:44 +0000441 _("option %s: invalid choice: %r (choose from %s)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000442 % (opt, value, choices))
443
444# Not supplying a default is different from a default of None,
445# so we need an explicit "not supplied" value.
Greg Wardeba20e62004-07-31 16:15:44 +0000446NO_DEFAULT = ("NO", "DEFAULT")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000447
448
449class Option:
450 """
451 Instance attributes:
452 _short_opts : [string]
453 _long_opts : [string]
454
455 action : string
456 type : string
457 dest : string
458 default : any
459 nargs : int
460 const : any
461 choices : [string]
462 callback : function
463 callback_args : (any*)
464 callback_kwargs : { string : any }
465 help : string
466 metavar : string
467 """
468
469 # The list of instance attributes that may be set through
470 # keyword args to the constructor.
471 ATTRS = ['action',
472 'type',
473 'dest',
474 'default',
475 'nargs',
476 'const',
477 'choices',
478 'callback',
479 'callback_args',
480 'callback_kwargs',
481 'help',
482 'metavar']
483
484 # The set of actions allowed by option parsers. Explicitly listed
485 # here so the constructor can validate its arguments.
486 ACTIONS = ("store",
487 "store_const",
488 "store_true",
489 "store_false",
490 "append",
Thomas Wouters477c8d52006-05-27 19:21:47 +0000491 "append_const",
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000492 "count",
493 "callback",
494 "help",
495 "version")
496
497 # The set of actions that involve storing a value somewhere;
498 # also listed just for constructor argument validation. (If
499 # the action is one of these, there must be a destination.)
500 STORE_ACTIONS = ("store",
501 "store_const",
502 "store_true",
503 "store_false",
504 "append",
Thomas Wouters477c8d52006-05-27 19:21:47 +0000505 "append_const",
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000506 "count")
507
508 # The set of actions for which it makes sense to supply a value
Greg Ward48aa84b2004-10-27 02:20:04 +0000509 # type, ie. which may consume an argument from the command line.
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000510 TYPED_ACTIONS = ("store",
511 "append",
512 "callback")
513
Greg Ward48aa84b2004-10-27 02:20:04 +0000514 # The set of actions which *require* a value type, ie. that
515 # always consume an argument from the command line.
516 ALWAYS_TYPED_ACTIONS = ("store",
517 "append")
518
Thomas Wouters477c8d52006-05-27 19:21:47 +0000519 # The set of actions which take a 'const' attribute.
520 CONST_ACTIONS = ("store_const",
521 "append_const")
522
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000523 # The set of known types for option parsers. Again, listed here for
524 # constructor argument validation.
525 TYPES = ("string", "int", "long", "float", "complex", "choice")
526
527 # Dictionary of argument checking functions, which convert and
528 # validate option arguments according to the option type.
529 #
530 # Signature of checking functions is:
531 # check(option : Option, opt : string, value : string) -> any
532 # where
533 # option is the Option instance calling the checker
534 # opt is the actual option seen on the command-line
535 # (eg. "-a", "--file")
536 # value is the option argument seen on the command-line
537 #
538 # The return value should be in the appropriate Python type
539 # for option.type -- eg. an integer if option.type == "int".
540 #
541 # If no checker is defined for a type, arguments will be
542 # unchecked and remain strings.
543 TYPE_CHECKER = { "int" : check_builtin,
544 "long" : check_builtin,
545 "float" : check_builtin,
Greg Wardeba20e62004-07-31 16:15:44 +0000546 "complex": check_builtin,
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000547 "choice" : check_choice,
548 }
549
550
551 # CHECK_METHODS is a list of unbound method objects; they are called
552 # by the constructor, in order, after all attributes are
553 # initialized. The list is created and filled in later, after all
554 # the methods are actually defined. (I just put it here because I
555 # like to define and document all class attributes in the same
556 # place.) Subclasses that add another _check_*() method should
557 # define their own CHECK_METHODS list that adds their check method
558 # to those from this class.
559 CHECK_METHODS = None
560
561
562 # -- Constructor/initialization methods ----------------------------
563
Greg Wardeba20e62004-07-31 16:15:44 +0000564 def __init__(self, *opts, **attrs):
Greg Ward2492fcf2003-04-21 02:40:34 +0000565 # Set _short_opts, _long_opts attrs from 'opts' tuple.
566 # Have to be set now, in case no option strings are supplied.
567 self._short_opts = []
568 self._long_opts = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000569 opts = self._check_opt_strings(opts)
570 self._set_opt_strings(opts)
571
572 # Set all other attrs (action, type, etc.) from 'attrs' dict
573 self._set_attrs(attrs)
574
575 # Check all the attributes we just set. There are lots of
576 # complicated interdependencies, but luckily they can be farmed
577 # out to the _check_*() methods listed in CHECK_METHODS -- which
578 # could be handy for subclasses! The one thing these all share
579 # is that they raise OptionError if they discover a problem.
580 for checker in self.CHECK_METHODS:
581 checker(self)
582
Greg Wardeba20e62004-07-31 16:15:44 +0000583 def _check_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000584 # Filter out None because early versions of Optik had exactly
585 # one short option and one long option, either of which
586 # could be None.
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000587 opts = [opt for opt in opts if opt]
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000588 if not opts:
Greg Ward2492fcf2003-04-21 02:40:34 +0000589 raise TypeError("at least one option string must be supplied")
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000590 return opts
591
Greg Wardeba20e62004-07-31 16:15:44 +0000592 def _set_opt_strings(self, opts):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000593 for opt in opts:
594 if len(opt) < 2:
595 raise OptionError(
596 "invalid option string %r: "
597 "must be at least two characters long" % opt, self)
598 elif len(opt) == 2:
599 if not (opt[0] == "-" and opt[1] != "-"):
600 raise OptionError(
601 "invalid short option string %r: "
602 "must be of the form -x, (x any non-dash char)" % opt,
603 self)
604 self._short_opts.append(opt)
605 else:
606 if not (opt[0:2] == "--" and opt[2] != "-"):
607 raise OptionError(
608 "invalid long option string %r: "
609 "must start with --, followed by non-dash" % opt,
610 self)
611 self._long_opts.append(opt)
612
Greg Wardeba20e62004-07-31 16:15:44 +0000613 def _set_attrs(self, attrs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000614 for attr in self.ATTRS:
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000615 if attr in attrs:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000616 setattr(self, attr, attrs[attr])
617 del attrs[attr]
618 else:
619 if attr == 'default':
620 setattr(self, attr, NO_DEFAULT)
621 else:
622 setattr(self, attr, None)
623 if attrs:
Georg Brandlc2d9d7f2007-02-11 23:06:17 +0000624 attrs = sorted(attrs.keys())
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000625 raise OptionError(
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000626 "invalid keyword arguments: %s" % ", ".join(attrs),
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000627 self)
628
629
630 # -- Constructor validation methods --------------------------------
631
Greg Wardeba20e62004-07-31 16:15:44 +0000632 def _check_action(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000633 if self.action is None:
634 self.action = "store"
635 elif self.action not in self.ACTIONS:
636 raise OptionError("invalid action: %r" % self.action, self)
637
Greg Wardeba20e62004-07-31 16:15:44 +0000638 def _check_type(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000639 if self.type is None:
Greg Ward48aa84b2004-10-27 02:20:04 +0000640 if self.action in self.ALWAYS_TYPED_ACTIONS:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000641 if self.choices is not None:
642 # The "choices" attribute implies "choice" type.
643 self.type = "choice"
644 else:
645 # No type given? "string" is the most sensible default.
646 self.type = "string"
647 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000648 # Allow type objects or builtin type conversion functions
Serhiy Storchaka7e527052014-01-20 21:29:31 +0200649 # (int, str, etc.) as an alternative to their names.
650 if isinstance(self.type, type):
Greg Wardeba20e62004-07-31 16:15:44 +0000651 self.type = self.type.__name__
Thomas Wouters477c8d52006-05-27 19:21:47 +0000652
Greg Wardeba20e62004-07-31 16:15:44 +0000653 if self.type == "str":
654 self.type = "string"
655
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000656 if self.type not in self.TYPES:
657 raise OptionError("invalid option type: %r" % self.type, self)
658 if self.action not in self.TYPED_ACTIONS:
659 raise OptionError(
660 "must not supply a type for action %r" % self.action, self)
661
662 def _check_choice(self):
663 if self.type == "choice":
664 if self.choices is None:
665 raise OptionError(
666 "must supply a list of choices for type 'choice'", self)
Guido van Rossum13257902007-06-07 23:15:56 +0000667 elif not isinstance(self.choices, (tuple, list)):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000668 raise OptionError(
669 "choices must be a list of strings ('%s' supplied)"
670 % str(type(self.choices)).split("'")[1], self)
671 elif self.choices is not None:
672 raise OptionError(
673 "must not supply choices for type %r" % self.type, self)
674
Greg Wardeba20e62004-07-31 16:15:44 +0000675 def _check_dest(self):
676 # No destination given, and we need one for this action. The
677 # self.type check is for callbacks that take a value.
678 takes_value = (self.action in self.STORE_ACTIONS or
679 self.type is not None)
680 if self.dest is None and takes_value:
681
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000682 # Glean a destination from the first long option string,
683 # or from the first short option string if no long options.
684 if self._long_opts:
685 # eg. "--foo-bar" -> "foo_bar"
686 self.dest = self._long_opts[0][2:].replace('-', '_')
687 else:
688 self.dest = self._short_opts[0][1]
689
Greg Wardeba20e62004-07-31 16:15:44 +0000690 def _check_const(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000691 if self.action not in self.CONST_ACTIONS and self.const is not None:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000692 raise OptionError(
693 "'const' must not be supplied for action %r" % self.action,
694 self)
695
Greg Wardeba20e62004-07-31 16:15:44 +0000696 def _check_nargs(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000697 if self.action in self.TYPED_ACTIONS:
698 if self.nargs is None:
699 self.nargs = 1
700 elif self.nargs is not None:
701 raise OptionError(
702 "'nargs' must not be supplied for action %r" % self.action,
703 self)
704
Greg Wardeba20e62004-07-31 16:15:44 +0000705 def _check_callback(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000706 if self.action == "callback":
Florent Xicluna5d1155c2011-10-28 14:45:05 +0200707 if not callable(self.callback):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000708 raise OptionError(
709 "callback not callable: %r" % self.callback, self)
710 if (self.callback_args is not None and
Guido van Rossum13257902007-06-07 23:15:56 +0000711 not isinstance(self.callback_args, tuple)):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000712 raise OptionError(
713 "callback_args, if supplied, must be a tuple: not %r"
714 % self.callback_args, self)
715 if (self.callback_kwargs is not None and
Guido van Rossum13257902007-06-07 23:15:56 +0000716 not isinstance(self.callback_kwargs, dict)):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000717 raise OptionError(
718 "callback_kwargs, if supplied, must be a dict: not %r"
719 % self.callback_kwargs, self)
720 else:
721 if self.callback is not None:
722 raise OptionError(
723 "callback supplied (%r) for non-callback option"
724 % self.callback, self)
725 if self.callback_args is not None:
726 raise OptionError(
727 "callback_args supplied for non-callback option", self)
728 if self.callback_kwargs is not None:
729 raise OptionError(
730 "callback_kwargs supplied for non-callback option", self)
731
732
733 CHECK_METHODS = [_check_action,
734 _check_type,
735 _check_choice,
736 _check_dest,
737 _check_const,
738 _check_nargs,
739 _check_callback]
740
741
742 # -- Miscellaneous methods -----------------------------------------
743
Greg Wardeba20e62004-07-31 16:15:44 +0000744 def __str__(self):
Greg Ward2492fcf2003-04-21 02:40:34 +0000745 return "/".join(self._short_opts + self._long_opts)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000746
Greg Wardeba20e62004-07-31 16:15:44 +0000747 __repr__ = _repr
748
749 def takes_value(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000750 return self.type is not None
751
Greg Wardeba20e62004-07-31 16:15:44 +0000752 def get_opt_string(self):
753 if self._long_opts:
754 return self._long_opts[0]
755 else:
756 return self._short_opts[0]
757
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000758
759 # -- Processing methods --------------------------------------------
760
Greg Wardeba20e62004-07-31 16:15:44 +0000761 def check_value(self, opt, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000762 checker = self.TYPE_CHECKER.get(self.type)
763 if checker is None:
764 return value
765 else:
766 return checker(self, opt, value)
767
Greg Wardeba20e62004-07-31 16:15:44 +0000768 def convert_value(self, opt, value):
769 if value is not None:
770 if self.nargs == 1:
771 return self.check_value(opt, value)
772 else:
773 return tuple([self.check_value(opt, v) for v in value])
774
775 def process(self, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000776
777 # First, convert the value(s) to the right type. Howl if any
778 # value(s) are bogus.
Greg Wardeba20e62004-07-31 16:15:44 +0000779 value = self.convert_value(opt, value)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000780
781 # And then take whatever action is expected of us.
782 # This is a separate method to make life easier for
783 # subclasses to add new actions.
784 return self.take_action(
785 self.action, self.dest, opt, value, values, parser)
786
Greg Wardeba20e62004-07-31 16:15:44 +0000787 def take_action(self, action, dest, opt, value, values, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000788 if action == "store":
789 setattr(values, dest, value)
790 elif action == "store_const":
791 setattr(values, dest, self.const)
792 elif action == "store_true":
Greg Ward2492fcf2003-04-21 02:40:34 +0000793 setattr(values, dest, True)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000794 elif action == "store_false":
Greg Ward2492fcf2003-04-21 02:40:34 +0000795 setattr(values, dest, False)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000796 elif action == "append":
797 values.ensure_value(dest, []).append(value)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000798 elif action == "append_const":
799 values.ensure_value(dest, []).append(self.const)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000800 elif action == "count":
801 setattr(values, dest, values.ensure_value(dest, 0) + 1)
802 elif action == "callback":
803 args = self.callback_args or ()
804 kwargs = self.callback_kwargs or {}
805 self.callback(self, opt, value, parser, *args, **kwargs)
806 elif action == "help":
807 parser.print_help()
Greg Ward48aa84b2004-10-27 02:20:04 +0000808 parser.exit()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000809 elif action == "version":
810 parser.print_version()
Greg Ward48aa84b2004-10-27 02:20:04 +0000811 parser.exit()
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000812 else:
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000813 raise ValueError("unknown action %r" % self.action)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000814
815 return 1
816
817# class Option
Greg Ward2492fcf2003-04-21 02:40:34 +0000818
819
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000820SUPPRESS_HELP = "SUPPRESS"+"HELP"
821SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
822
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000823class Values:
824
Greg Wardeba20e62004-07-31 16:15:44 +0000825 def __init__(self, defaults=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000826 if defaults:
827 for (attr, val) in defaults.items():
828 setattr(self, attr, val)
829
Greg Wardeba20e62004-07-31 16:15:44 +0000830 def __str__(self):
831 return str(self.__dict__)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000832
Greg Wardeba20e62004-07-31 16:15:44 +0000833 __repr__ = _repr
834
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000835 def __eq__(self, other):
Greg Wardeba20e62004-07-31 16:15:44 +0000836 if isinstance(other, Values):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000837 return self.__dict__ == other.__dict__
Guido van Rossum13257902007-06-07 23:15:56 +0000838 elif isinstance(other, dict):
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000839 return self.__dict__ == other
Greg Wardeba20e62004-07-31 16:15:44 +0000840 else:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000841 return NotImplemented
Greg Wardeba20e62004-07-31 16:15:44 +0000842
843 def _update_careful(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000844 """
845 Update the option values from an arbitrary dictionary, but only
846 use keys from dict that already have a corresponding attribute
847 in self. Any keys in dict without a corresponding attribute
848 are silently ignored.
849 """
850 for attr in dir(self):
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000851 if attr in dict:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000852 dval = dict[attr]
853 if dval is not None:
854 setattr(self, attr, dval)
855
Greg Wardeba20e62004-07-31 16:15:44 +0000856 def _update_loose(self, dict):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000857 """
858 Update the option values from an arbitrary dictionary,
859 using all keys from the dictionary regardless of whether
860 they have a corresponding attribute in self or not.
861 """
862 self.__dict__.update(dict)
863
Greg Wardeba20e62004-07-31 16:15:44 +0000864 def _update(self, dict, mode):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000865 if mode == "careful":
866 self._update_careful(dict)
867 elif mode == "loose":
868 self._update_loose(dict)
869 else:
Collin Winterce36ad82007-08-30 01:19:48 +0000870 raise ValueError("invalid update mode: %r" % mode)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000871
Greg Wardeba20e62004-07-31 16:15:44 +0000872 def read_module(self, modname, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000873 __import__(modname)
874 mod = sys.modules[modname]
875 self._update(vars(mod), mode)
876
Greg Wardeba20e62004-07-31 16:15:44 +0000877 def read_file(self, filename, mode="careful"):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000878 vars = {}
Neal Norwitz01688022007-08-12 00:43:29 +0000879 exec(open(filename).read(), vars)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000880 self._update(vars, mode)
881
Greg Wardeba20e62004-07-31 16:15:44 +0000882 def ensure_value(self, attr, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000883 if not hasattr(self, attr) or getattr(self, attr) is None:
884 setattr(self, attr, value)
885 return getattr(self, attr)
886
887
888class OptionContainer:
889
890 """
891 Abstract base class.
892
893 Class attributes:
894 standard_option_list : [Option]
895 list of standard options that will be accepted by all instances
896 of this parser class (intended to be overridden by subclasses).
897
898 Instance attributes:
899 option_list : [Option]
900 the list of Option objects contained by this OptionContainer
901 _short_opt : { string : Option }
902 dictionary mapping short option strings, eg. "-f" or "-X",
903 to the Option instances that implement them. If an Option
Martin Panter8f265652016-04-19 04:03:41 +0000904 has multiple short option strings, it will appear in this
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000905 dictionary multiple times. [1]
906 _long_opt : { string : Option }
907 dictionary mapping long option strings, eg. "--file" or
908 "--exclude", to the Option instances that implement them.
909 Again, a given Option can occur multiple times in this
910 dictionary. [1]
911 defaults : { string : any }
912 dictionary mapping option destination names to default
913 values for each destination [1]
914
915 [1] These mappings are common to (shared by) all components of the
916 controlling OptionParser, where they are initially created.
917
918 """
919
Greg Wardeba20e62004-07-31 16:15:44 +0000920 def __init__(self, option_class, conflict_handler, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000921 # Initialize the option list and related data structures.
922 # This method must be provided by subclasses, and it must
923 # initialize at least the following instance attributes:
924 # option_list, _short_opt, _long_opt, defaults.
925 self._create_option_list()
926
927 self.option_class = option_class
928 self.set_conflict_handler(conflict_handler)
929 self.set_description(description)
930
Greg Wardeba20e62004-07-31 16:15:44 +0000931 def _create_option_mappings(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000932 # For use by OptionParser constructor -- create the master
933 # option mappings used by this OptionParser and all
934 # OptionGroups that it owns.
935 self._short_opt = {} # single letter -> Option instance
936 self._long_opt = {} # long option -> Option instance
937 self.defaults = {} # maps option dest -> default value
938
939
Greg Wardeba20e62004-07-31 16:15:44 +0000940 def _share_option_mappings(self, parser):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000941 # For use by OptionGroup constructor -- use shared option
942 # mappings from the OptionParser that owns this OptionGroup.
943 self._short_opt = parser._short_opt
944 self._long_opt = parser._long_opt
945 self.defaults = parser.defaults
946
Greg Wardeba20e62004-07-31 16:15:44 +0000947 def set_conflict_handler(self, handler):
Greg Ward48aa84b2004-10-27 02:20:04 +0000948 if handler not in ("error", "resolve"):
Collin Winterce36ad82007-08-30 01:19:48 +0000949 raise ValueError("invalid conflict_resolution value %r" % handler)
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000950 self.conflict_handler = handler
951
Greg Wardeba20e62004-07-31 16:15:44 +0000952 def set_description(self, description):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000953 self.description = description
954
Greg Wardeba20e62004-07-31 16:15:44 +0000955 def get_description(self):
956 return self.description
957
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000958
Thomas Wouters477c8d52006-05-27 19:21:47 +0000959 def destroy(self):
960 """see OptionParser.destroy()."""
961 del self._short_opt
962 del self._long_opt
963 del self.defaults
964
965
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000966 # -- Option-adding methods -----------------------------------------
967
Greg Wardeba20e62004-07-31 16:15:44 +0000968 def _check_conflict(self, option):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000969 conflict_opts = []
970 for opt in option._short_opts:
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000971 if opt in self._short_opt:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000972 conflict_opts.append((opt, self._short_opt[opt]))
973 for opt in option._long_opts:
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000974 if opt in self._long_opt:
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000975 conflict_opts.append((opt, self._long_opt[opt]))
976
977 if conflict_opts:
978 handler = self.conflict_handler
Greg Ward48aa84b2004-10-27 02:20:04 +0000979 if handler == "error":
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000980 raise OptionConflictError(
981 "conflicting option string(s): %s"
982 % ", ".join([co[0] for co in conflict_opts]),
983 option)
Greg Ward48aa84b2004-10-27 02:20:04 +0000984 elif handler == "resolve":
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000985 for (opt, c_option) in conflict_opts:
986 if opt.startswith("--"):
987 c_option._long_opts.remove(opt)
988 del self._long_opt[opt]
989 else:
990 c_option._short_opts.remove(opt)
991 del self._short_opt[opt]
992 if not (c_option._short_opts or c_option._long_opts):
993 c_option.container.option_list.remove(c_option)
994
Greg Wardeba20e62004-07-31 16:15:44 +0000995 def add_option(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +0000996 """add_option(Option)
997 add_option(opt_str, ..., kwarg=val, ...)
998 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000999 if isinstance(args[0], str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001000 option = self.option_class(*args, **kwargs)
1001 elif len(args) == 1 and not kwargs:
1002 option = args[0]
1003 if not isinstance(option, Option):
Collin Winterce36ad82007-08-30 01:19:48 +00001004 raise TypeError("not an Option instance: %r" % option)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001005 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001006 raise TypeError("invalid arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001007
1008 self._check_conflict(option)
1009
1010 self.option_list.append(option)
1011 option.container = self
1012 for opt in option._short_opts:
1013 self._short_opt[opt] = option
1014 for opt in option._long_opts:
1015 self._long_opt[opt] = option
1016
1017 if option.dest is not None: # option has a dest, we need a default
1018 if option.default is not NO_DEFAULT:
1019 self.defaults[option.dest] = option.default
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001020 elif option.dest not in self.defaults:
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001021 self.defaults[option.dest] = None
1022
1023 return option
1024
Greg Wardeba20e62004-07-31 16:15:44 +00001025 def add_options(self, option_list):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001026 for option in option_list:
1027 self.add_option(option)
1028
1029 # -- Option query/removal methods ----------------------------------
1030
Greg Wardeba20e62004-07-31 16:15:44 +00001031 def get_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001032 return (self._short_opt.get(opt_str) or
1033 self._long_opt.get(opt_str))
1034
Greg Wardeba20e62004-07-31 16:15:44 +00001035 def has_option(self, opt_str):
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001036 return (opt_str in self._short_opt or
Guido van Rossum93662412006-08-19 16:09:41 +00001037 opt_str in self._long_opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001038
Greg Wardeba20e62004-07-31 16:15:44 +00001039 def remove_option(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001040 option = self._short_opt.get(opt_str)
1041 if option is None:
1042 option = self._long_opt.get(opt_str)
1043 if option is None:
1044 raise ValueError("no such option %r" % opt_str)
1045
1046 for opt in option._short_opts:
1047 del self._short_opt[opt]
1048 for opt in option._long_opts:
1049 del self._long_opt[opt]
1050 option.container.option_list.remove(option)
1051
1052
1053 # -- Help-formatting methods ---------------------------------------
1054
Greg Wardeba20e62004-07-31 16:15:44 +00001055 def format_option_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001056 if not self.option_list:
1057 return ""
1058 result = []
1059 for option in self.option_list:
1060 if not option.help is SUPPRESS_HELP:
1061 result.append(formatter.format_option(option))
1062 return "".join(result)
1063
Greg Wardeba20e62004-07-31 16:15:44 +00001064 def format_description(self, formatter):
1065 return formatter.format_description(self.get_description())
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001066
Greg Wardeba20e62004-07-31 16:15:44 +00001067 def format_help(self, formatter):
1068 result = []
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001069 if self.description:
Greg Wardeba20e62004-07-31 16:15:44 +00001070 result.append(self.format_description(formatter))
1071 if self.option_list:
1072 result.append(self.format_option_help(formatter))
1073 return "\n".join(result)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001074
1075
1076class OptionGroup (OptionContainer):
1077
Greg Wardeba20e62004-07-31 16:15:44 +00001078 def __init__(self, parser, title, description=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001079 self.parser = parser
1080 OptionContainer.__init__(
1081 self, parser.option_class, parser.conflict_handler, description)
1082 self.title = title
1083
Greg Wardeba20e62004-07-31 16:15:44 +00001084 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001085 self.option_list = []
1086 self._share_option_mappings(self.parser)
1087
Greg Wardeba20e62004-07-31 16:15:44 +00001088 def set_title(self, title):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001089 self.title = title
1090
Thomas Wouters477c8d52006-05-27 19:21:47 +00001091 def destroy(self):
1092 """see OptionParser.destroy()."""
1093 OptionContainer.destroy(self)
1094 del self.option_list
1095
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001096 # -- Help-formatting methods ---------------------------------------
1097
Greg Wardeba20e62004-07-31 16:15:44 +00001098 def format_help(self, formatter):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001099 result = formatter.format_heading(self.title)
1100 formatter.indent()
1101 result += OptionContainer.format_help(self, formatter)
1102 formatter.dedent()
1103 return result
1104
1105
1106class OptionParser (OptionContainer):
1107
1108 """
1109 Class attributes:
1110 standard_option_list : [Option]
1111 list of standard options that will be accepted by all instances
1112 of this parser class (intended to be overridden by subclasses).
1113
1114 Instance attributes:
1115 usage : string
1116 a usage string for your program. Before it is displayed
1117 to the user, "%prog" will be expanded to the name of
Greg Ward2492fcf2003-04-21 02:40:34 +00001118 your program (self.prog or os.path.basename(sys.argv[0])).
1119 prog : string
1120 the name of the current program (to override
1121 os.path.basename(sys.argv[0])).
R David Murrayfc5ed802011-05-04 21:06:57 -04001122 description : string
1123 A paragraph of text giving a brief overview of your program.
1124 optparse reformats this paragraph to fit the current terminal
1125 width and prints it when the user requests help (after usage,
1126 but before the list of options).
Thomas Wouters477c8d52006-05-27 19:21:47 +00001127 epilog : string
1128 paragraph of help text to print after option help
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001129
Greg Wardeba20e62004-07-31 16:15:44 +00001130 option_groups : [OptionGroup]
1131 list of option groups in this parser (option groups are
1132 irrelevant for parsing the command-line, but very useful
1133 for generating help)
1134
1135 allow_interspersed_args : bool = true
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001136 if true, positional arguments may be interspersed with options.
1137 Assuming -a and -b each take a single argument, the command-line
1138 -ablah foo bar -bboo baz
1139 will be interpreted the same as
1140 -ablah -bboo -- foo bar baz
1141 If this flag were false, that command line would be interpreted as
1142 -ablah -- foo bar -bboo baz
1143 -- ie. we stop processing options as soon as we see the first
1144 non-option argument. (This is the tradition followed by
1145 Python's getopt module, Perl's Getopt::Std, and other argument-
1146 parsing libraries, but it is generally annoying to users.)
1147
Greg Wardeba20e62004-07-31 16:15:44 +00001148 process_default_values : bool = true
1149 if true, option default values are processed similarly to option
1150 values from the command line: that is, they are passed to the
1151 type-checking function for the option's type (as long as the
1152 default value is a string). (This really only matters if you
1153 have defined custom types; see SF bug #955889.) Set it to false
1154 to restore the behaviour of Optik 1.4.1 and earlier.
1155
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001156 rargs : [string]
1157 the argument list currently being parsed. Only set when
1158 parse_args() is active, and continually trimmed down as
1159 we consume arguments. Mainly there for the benefit of
1160 callback options.
1161 largs : [string]
1162 the list of leftover arguments that we have skipped while
1163 parsing options. If allow_interspersed_args is false, this
1164 list is always empty.
1165 values : Values
1166 the set of option values currently being accumulated. Only
1167 set when parse_args() is active. Also mainly for callbacks.
1168
1169 Because of the 'rargs', 'largs', and 'values' attributes,
1170 OptionParser is not thread-safe. If, for some perverse reason, you
1171 need to parse command-line arguments simultaneously in different
1172 threads, use different OptionParser instances.
1173
1174 """
1175
1176 standard_option_list = []
1177
Greg Wardeba20e62004-07-31 16:15:44 +00001178 def __init__(self,
1179 usage=None,
1180 option_list=None,
1181 option_class=Option,
1182 version=None,
1183 conflict_handler="error",
1184 description=None,
1185 formatter=None,
1186 add_help_option=True,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001187 prog=None,
1188 epilog=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001189 OptionContainer.__init__(
1190 self, option_class, conflict_handler, description)
1191 self.set_usage(usage)
Greg Ward2492fcf2003-04-21 02:40:34 +00001192 self.prog = prog
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001193 self.version = version
Greg Wardeba20e62004-07-31 16:15:44 +00001194 self.allow_interspersed_args = True
1195 self.process_default_values = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001196 if formatter is None:
1197 formatter = IndentedHelpFormatter()
1198 self.formatter = formatter
Greg Wardeba20e62004-07-31 16:15:44 +00001199 self.formatter.set_parser(self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001200 self.epilog = epilog
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001201
1202 # Populate the option list; initial sources are the
1203 # standard_option_list class attribute, the 'option_list'
Greg Wardeba20e62004-07-31 16:15:44 +00001204 # argument, and (if applicable) the _add_version_option() and
1205 # _add_help_option() methods.
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001206 self._populate_option_list(option_list,
1207 add_help=add_help_option)
1208
1209 self._init_parsing_state()
1210
Thomas Wouters477c8d52006-05-27 19:21:47 +00001211
1212 def destroy(self):
1213 """
1214 Declare that you are done with this OptionParser. This cleans up
1215 reference cycles so the OptionParser (and all objects referenced by
1216 it) can be garbage-collected promptly. After calling destroy(), the
1217 OptionParser is unusable.
1218 """
1219 OptionContainer.destroy(self)
1220 for group in self.option_groups:
1221 group.destroy()
1222 del self.option_list
1223 del self.option_groups
1224 del self.formatter
1225
1226
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001227 # -- Private methods -----------------------------------------------
1228 # (used by our or OptionContainer's constructor)
1229
Greg Wardeba20e62004-07-31 16:15:44 +00001230 def _create_option_list(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001231 self.option_list = []
1232 self.option_groups = []
1233 self._create_option_mappings()
1234
Greg Wardeba20e62004-07-31 16:15:44 +00001235 def _add_help_option(self):
1236 self.add_option("-h", "--help",
1237 action="help",
1238 help=_("show this help message and exit"))
1239
1240 def _add_version_option(self):
1241 self.add_option("--version",
1242 action="version",
1243 help=_("show program's version number and exit"))
1244
1245 def _populate_option_list(self, option_list, add_help=True):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001246 if self.standard_option_list:
1247 self.add_options(self.standard_option_list)
1248 if option_list:
1249 self.add_options(option_list)
1250 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001251 self._add_version_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001252 if add_help:
Greg Wardeba20e62004-07-31 16:15:44 +00001253 self._add_help_option()
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001254
Greg Wardeba20e62004-07-31 16:15:44 +00001255 def _init_parsing_state(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001256 # These are set in parse_args() for the convenience of callbacks.
1257 self.rargs = None
1258 self.largs = None
1259 self.values = None
1260
1261
1262 # -- Simple modifier methods ---------------------------------------
1263
Greg Wardeba20e62004-07-31 16:15:44 +00001264 def set_usage(self, usage):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001265 if usage is None:
Greg Wardeba20e62004-07-31 16:15:44 +00001266 self.usage = _("%prog [options]")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001267 elif usage is SUPPRESS_USAGE:
1268 self.usage = None
Greg Wardeba20e62004-07-31 16:15:44 +00001269 # For backwards compatibility with Optik 1.3 and earlier.
Thomas Wouters477c8d52006-05-27 19:21:47 +00001270 elif usage.lower().startswith("usage: "):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001271 self.usage = usage[7:]
1272 else:
1273 self.usage = usage
1274
Greg Wardeba20e62004-07-31 16:15:44 +00001275 def enable_interspersed_args(self):
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001276 """Set parsing to not stop on the first non-option, allowing
1277 interspersing switches with command arguments. This is the
1278 default behavior. See also disable_interspersed_args() and the
1279 class documentation description of the attribute
1280 allow_interspersed_args."""
Greg Wardeba20e62004-07-31 16:15:44 +00001281 self.allow_interspersed_args = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001282
Greg Wardeba20e62004-07-31 16:15:44 +00001283 def disable_interspersed_args(self):
Benjamin Petersonf10a79a2008-10-11 00:49:57 +00001284 """Set parsing to stop on the first non-option. Use this if
1285 you have a command processor which runs another command that
1286 has options of its own and you want to make sure these options
1287 don't get confused.
1288 """
Greg Wardeba20e62004-07-31 16:15:44 +00001289 self.allow_interspersed_args = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001290
Greg Wardeba20e62004-07-31 16:15:44 +00001291 def set_process_default_values(self, process):
1292 self.process_default_values = process
1293
1294 def set_default(self, dest, value):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001295 self.defaults[dest] = value
1296
Greg Wardeba20e62004-07-31 16:15:44 +00001297 def set_defaults(self, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001298 self.defaults.update(kwargs)
1299
Greg Wardeba20e62004-07-31 16:15:44 +00001300 def _get_all_options(self):
1301 options = self.option_list[:]
1302 for group in self.option_groups:
1303 options.extend(group.option_list)
1304 return options
1305
1306 def get_default_values(self):
1307 if not self.process_default_values:
1308 # Old, pre-Optik 1.5 behaviour.
1309 return Values(self.defaults)
1310
1311 defaults = self.defaults.copy()
1312 for option in self._get_all_options():
1313 default = defaults.get(option.dest)
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001314 if isinstance(default, str):
Greg Wardeba20e62004-07-31 16:15:44 +00001315 opt_str = option.get_opt_string()
1316 defaults[option.dest] = option.check_value(opt_str, default)
1317
1318 return Values(defaults)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001319
1320
1321 # -- OptionGroup methods -------------------------------------------
1322
Greg Wardeba20e62004-07-31 16:15:44 +00001323 def add_option_group(self, *args, **kwargs):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001324 # XXX lots of overlap with OptionContainer.add_option()
Guido van Rossum3172c5d2007-10-16 18:12:55 +00001325 if isinstance(args[0], str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001326 group = OptionGroup(self, *args, **kwargs)
1327 elif len(args) == 1 and not kwargs:
1328 group = args[0]
1329 if not isinstance(group, OptionGroup):
Collin Winterce36ad82007-08-30 01:19:48 +00001330 raise TypeError("not an OptionGroup instance: %r" % group)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001331 if group.parser is not self:
Collin Winterce36ad82007-08-30 01:19:48 +00001332 raise ValueError("invalid OptionGroup (wrong parser)")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001333 else:
Collin Winterce36ad82007-08-30 01:19:48 +00001334 raise TypeError("invalid arguments")
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001335
1336 self.option_groups.append(group)
1337 return group
1338
Greg Wardeba20e62004-07-31 16:15:44 +00001339 def get_option_group(self, opt_str):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001340 option = (self._short_opt.get(opt_str) or
1341 self._long_opt.get(opt_str))
1342 if option and option.container is not self:
1343 return option.container
1344 return None
1345
1346
1347 # -- Option-parsing methods ----------------------------------------
1348
Greg Wardeba20e62004-07-31 16:15:44 +00001349 def _get_args(self, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001350 if args is None:
1351 return sys.argv[1:]
1352 else:
1353 return args[:] # don't modify caller's list
1354
Greg Wardeba20e62004-07-31 16:15:44 +00001355 def parse_args(self, args=None, values=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001356 """
1357 parse_args(args : [string] = sys.argv[1:],
1358 values : Values = None)
1359 -> (values : Values, args : [string])
1360
1361 Parse the command-line options found in 'args' (default:
1362 sys.argv[1:]). Any errors result in a call to 'error()', which
1363 by default prints the usage message to stderr and calls
1364 sys.exit() with an error message. On success returns a pair
Serhiy Storchaka6a7b3a72016-04-17 08:32:47 +03001365 (values, args) where 'values' is a Values instance (with all
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001366 your option values) and 'args' is the list of arguments left
1367 over after parsing options.
1368 """
1369 rargs = self._get_args(args)
1370 if values is None:
1371 values = self.get_default_values()
1372
1373 # Store the halves of the argument list as attributes for the
1374 # convenience of callbacks:
1375 # rargs
1376 # the rest of the command-line (the "r" stands for
1377 # "remaining" or "right-hand")
1378 # largs
1379 # the leftover arguments -- ie. what's left after removing
1380 # options and their arguments (the "l" stands for "leftover"
1381 # or "left-hand")
1382 self.rargs = rargs
1383 self.largs = largs = []
1384 self.values = values
1385
1386 try:
1387 stop = self._process_args(largs, rargs, values)
Guido van Rossumb940e112007-01-10 16:19:56 +00001388 except (BadOptionError, OptionValueError) as err:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001389 self.error(str(err))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001390
1391 args = largs + rargs
1392 return self.check_values(values, args)
1393
Greg Wardeba20e62004-07-31 16:15:44 +00001394 def check_values(self, values, args):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001395 """
1396 check_values(values : Values, args : [string])
1397 -> (values : Values, args : [string])
1398
1399 Check that the supplied option values and leftover arguments are
1400 valid. Returns the option values and leftover arguments
1401 (possibly adjusted, possibly completely new -- whatever you
1402 like). Default implementation just returns the passed-in
1403 values; subclasses may override as desired.
1404 """
1405 return (values, args)
1406
Greg Wardeba20e62004-07-31 16:15:44 +00001407 def _process_args(self, largs, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001408 """_process_args(largs : [string],
1409 rargs : [string],
1410 values : Values)
1411
1412 Process command-line arguments and populate 'values', consuming
1413 options and arguments from 'rargs'. If 'allow_interspersed_args' is
1414 false, stop at the first non-option argument. If true, accumulate any
1415 interspersed non-option arguments in 'largs'.
1416 """
1417 while rargs:
1418 arg = rargs[0]
1419 # We handle bare "--" explicitly, and bare "-" is handled by the
1420 # standard arg handler since the short arg case ensures that the
1421 # len of the opt string is greater than 1.
1422 if arg == "--":
1423 del rargs[0]
1424 return
1425 elif arg[0:2] == "--":
1426 # process a single long option (possibly with value(s))
1427 self._process_long_opt(rargs, values)
1428 elif arg[:1] == "-" and len(arg) > 1:
1429 # process a cluster of short options (possibly with
1430 # value(s) for the last one only)
1431 self._process_short_opts(rargs, values)
1432 elif self.allow_interspersed_args:
1433 largs.append(arg)
1434 del rargs[0]
1435 else:
1436 return # stop now, leave this arg in rargs
1437
1438 # Say this is the original argument list:
1439 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1440 # ^
1441 # (we are about to process arg(i)).
1442 #
1443 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1444 # [arg0, ..., arg(i-1)] (any options and their arguments will have
1445 # been removed from largs).
1446 #
1447 # The while loop will usually consume 1 or more arguments per pass.
1448 # If it consumes 1 (eg. arg is an option that takes no arguments),
1449 # then after _process_arg() is done the situation is:
1450 #
1451 # largs = subset of [arg0, ..., arg(i)]
1452 # rargs = [arg(i+1), ..., arg(N-1)]
1453 #
1454 # If allow_interspersed_args is false, largs will always be
1455 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1456 # not a very interesting subset!
1457
Greg Wardeba20e62004-07-31 16:15:44 +00001458 def _match_long_opt(self, opt):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001459 """_match_long_opt(opt : string) -> string
1460
1461 Determine which long option string 'opt' matches, ie. which one
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001462 it is an unambiguous abbreviation for. Raises BadOptionError if
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001463 'opt' doesn't unambiguously match any long option string.
1464 """
1465 return _match_abbrev(opt, self._long_opt)
1466
Greg Wardeba20e62004-07-31 16:15:44 +00001467 def _process_long_opt(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001468 arg = rargs.pop(0)
1469
1470 # Value explicitly attached to arg? Pretend it's the next
1471 # argument.
1472 if "=" in arg:
1473 (opt, next_arg) = arg.split("=", 1)
1474 rargs.insert(0, next_arg)
Greg Wardeba20e62004-07-31 16:15:44 +00001475 had_explicit_value = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001476 else:
1477 opt = arg
Greg Wardeba20e62004-07-31 16:15:44 +00001478 had_explicit_value = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001479
1480 opt = self._match_long_opt(opt)
1481 option = self._long_opt[opt]
1482 if option.takes_value():
1483 nargs = option.nargs
1484 if len(rargs) < nargs:
Éric Araujo6a1454f2011-03-20 19:59:25 +01001485 self.error(ngettext(
1486 "%(option)s option requires %(number)d argument",
1487 "%(option)s option requires %(number)d arguments",
1488 nargs) % {"option": opt, "number": nargs})
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001489 elif nargs == 1:
1490 value = rargs.pop(0)
1491 else:
1492 value = tuple(rargs[0:nargs])
1493 del rargs[0:nargs]
1494
1495 elif had_explicit_value:
Greg Wardeba20e62004-07-31 16:15:44 +00001496 self.error(_("%s option does not take a value") % opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001497
1498 else:
1499 value = None
1500
1501 option.process(opt, value, values, self)
1502
Greg Wardeba20e62004-07-31 16:15:44 +00001503 def _process_short_opts(self, rargs, values):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001504 arg = rargs.pop(0)
Greg Wardeba20e62004-07-31 16:15:44 +00001505 stop = False
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001506 i = 1
1507 for ch in arg[1:]:
1508 opt = "-" + ch
1509 option = self._short_opt.get(opt)
1510 i += 1 # we have consumed a character
1511
1512 if not option:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001513 raise BadOptionError(opt)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001514 if option.takes_value():
1515 # Any characters left in arg? Pretend they're the
1516 # next arg, and stop consuming characters of arg.
1517 if i < len(arg):
1518 rargs.insert(0, arg[i:])
Greg Wardeba20e62004-07-31 16:15:44 +00001519 stop = True
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001520
1521 nargs = option.nargs
1522 if len(rargs) < nargs:
Éric Araujo6a1454f2011-03-20 19:59:25 +01001523 self.error(ngettext(
1524 "%(option)s option requires %(number)d argument",
1525 "%(option)s option requires %(number)d arguments",
1526 nargs) % {"option": opt, "number": nargs})
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001527 elif nargs == 1:
1528 value = rargs.pop(0)
1529 else:
1530 value = tuple(rargs[0:nargs])
1531 del rargs[0:nargs]
1532
1533 else: # option doesn't take a value
1534 value = None
1535
1536 option.process(opt, value, values, self)
1537
1538 if stop:
1539 break
1540
1541
1542 # -- Feedback methods ----------------------------------------------
1543
Greg Wardeba20e62004-07-31 16:15:44 +00001544 def get_prog_name(self):
1545 if self.prog is None:
1546 return os.path.basename(sys.argv[0])
1547 else:
1548 return self.prog
1549
1550 def expand_prog_name(self, s):
1551 return s.replace("%prog", self.get_prog_name())
1552
1553 def get_description(self):
1554 return self.expand_prog_name(self.description)
1555
Greg Ward48aa84b2004-10-27 02:20:04 +00001556 def exit(self, status=0, msg=None):
1557 if msg:
1558 sys.stderr.write(msg)
1559 sys.exit(status)
1560
Greg Wardeba20e62004-07-31 16:15:44 +00001561 def error(self, msg):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001562 """error(msg : string)
1563
1564 Print a usage message incorporating 'msg' to stderr and exit.
1565 If you override this in a subclass, it should not return -- it
1566 should either exit or raise an exception.
1567 """
1568 self.print_usage(sys.stderr)
Greg Ward48aa84b2004-10-27 02:20:04 +00001569 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001570
Greg Wardeba20e62004-07-31 16:15:44 +00001571 def get_usage(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001572 if self.usage:
1573 return self.formatter.format_usage(
Greg Wardeba20e62004-07-31 16:15:44 +00001574 self.expand_prog_name(self.usage))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001575 else:
1576 return ""
1577
Greg Wardeba20e62004-07-31 16:15:44 +00001578 def print_usage(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001579 """print_usage(file : file = stdout)
1580
1581 Print the usage message for the current program (self.usage) to
Mark Dickinson934896d2009-02-21 20:59:32 +00001582 'file' (default stdout). Any occurrence of the string "%prog" in
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001583 self.usage is replaced with the name of the current program
1584 (basename of sys.argv[0]). Does nothing if self.usage is empty
1585 or not defined.
1586 """
1587 if self.usage:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001588 print(self.get_usage(), file=file)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001589
Greg Wardeba20e62004-07-31 16:15:44 +00001590 def get_version(self):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001591 if self.version:
Greg Wardeba20e62004-07-31 16:15:44 +00001592 return self.expand_prog_name(self.version)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001593 else:
1594 return ""
1595
Greg Wardeba20e62004-07-31 16:15:44 +00001596 def print_version(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001597 """print_version(file : file = stdout)
1598
1599 Print the version message for this program (self.version) to
Mark Dickinson934896d2009-02-21 20:59:32 +00001600 'file' (default stdout). As with print_usage(), any occurrence
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001601 of "%prog" in self.version is replaced by the current program's
1602 name. Does nothing if self.version is empty or undefined.
1603 """
1604 if self.version:
Guido van Rossumbe19ed72007-02-09 05:37:30 +00001605 print(self.get_version(), file=file)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001606
Greg Wardeba20e62004-07-31 16:15:44 +00001607 def format_option_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001608 if formatter is None:
1609 formatter = self.formatter
1610 formatter.store_option_strings(self)
1611 result = []
Thomas Wouters477c8d52006-05-27 19:21:47 +00001612 result.append(formatter.format_heading(_("Options")))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001613 formatter.indent()
1614 if self.option_list:
1615 result.append(OptionContainer.format_option_help(self, formatter))
1616 result.append("\n")
1617 for group in self.option_groups:
1618 result.append(group.format_help(formatter))
1619 result.append("\n")
1620 formatter.dedent()
1621 # Drop the last "\n", or the header if no options or option groups:
1622 return "".join(result[:-1])
1623
Thomas Wouters477c8d52006-05-27 19:21:47 +00001624 def format_epilog(self, formatter):
1625 return formatter.format_epilog(self.epilog)
1626
Greg Wardeba20e62004-07-31 16:15:44 +00001627 def format_help(self, formatter=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001628 if formatter is None:
1629 formatter = self.formatter
1630 result = []
1631 if self.usage:
1632 result.append(self.get_usage() + "\n")
1633 if self.description:
1634 result.append(self.format_description(formatter) + "\n")
1635 result.append(self.format_option_help(formatter))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001636 result.append(self.format_epilog(formatter))
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001637 return "".join(result)
1638
Greg Wardeba20e62004-07-31 16:15:44 +00001639 def print_help(self, file=None):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001640 """print_help(file : file = stdout)
1641
1642 Print an extended help message, listing all options and any
1643 help text provided with them, to 'file' (default stdout).
1644 """
1645 if file is None:
1646 file = sys.stdout
Guido van Rossum34d19282007-08-09 01:03:29 +00001647 file.write(self.format_help())
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001648
1649# class OptionParser
1650
1651
Greg Wardeba20e62004-07-31 16:15:44 +00001652def _match_abbrev(s, wordmap):
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001653 """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1654
1655 Return the string key in 'wordmap' for which 's' is an unambiguous
1656 abbreviation. If 's' is found to be ambiguous or doesn't match any of
1657 'words', raise BadOptionError.
1658 """
1659 # Is there an exact match?
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001660 if s in wordmap:
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001661 return s
1662 else:
1663 # Isolate all words with s as a prefix.
1664 possibilities = [word for word in wordmap.keys()
1665 if word.startswith(s)]
1666 # No exact match, so there had better be just one possibility.
1667 if len(possibilities) == 1:
1668 return possibilities[0]
1669 elif not possibilities:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001670 raise BadOptionError(s)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001671 else:
1672 # More than one possible completion: ambiguous prefix.
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001673 possibilities.sort()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001674 raise AmbiguousOptionError(s, possibilities)
Guido van Rossumb9ba4582002-11-14 22:00:19 +00001675
1676
1677# Some day, there might be many Option classes. As of Optik 1.3, the
1678# preferred way to instantiate Options is indirectly, via make_option(),
1679# which will become a factory function when there are many Option
1680# classes.
1681make_option = Option