1 | n/a | """A powerful, extensible, and easy-to-use option parser. |
---|
2 | n/a | |
---|
3 | n/a | By Greg Ward <gward@python.net> |
---|
4 | n/a | |
---|
5 | n/a | Originally distributed as Optik. |
---|
6 | n/a | |
---|
7 | n/a | For support, use the optik-users@lists.sourceforge.net mailing list |
---|
8 | n/a | (http://lists.sourceforge.net/lists/listinfo/optik-users). |
---|
9 | n/a | |
---|
10 | n/a | Simple usage example: |
---|
11 | n/a | |
---|
12 | n/a | from optparse import OptionParser |
---|
13 | n/a | |
---|
14 | n/a | parser = OptionParser() |
---|
15 | n/a | parser.add_option("-f", "--file", dest="filename", |
---|
16 | n/a | help="write report to FILE", metavar="FILE") |
---|
17 | n/a | parser.add_option("-q", "--quiet", |
---|
18 | n/a | action="store_false", dest="verbose", default=True, |
---|
19 | n/a | help="don't print status messages to stdout") |
---|
20 | n/a | |
---|
21 | n/a | (options, args) = parser.parse_args() |
---|
22 | n/a | """ |
---|
23 | n/a | |
---|
24 | n/a | __version__ = "1.5.3" |
---|
25 | n/a | |
---|
26 | n/a | __all__ = ['Option', |
---|
27 | n/a | 'make_option', |
---|
28 | n/a | 'SUPPRESS_HELP', |
---|
29 | n/a | 'SUPPRESS_USAGE', |
---|
30 | n/a | 'Values', |
---|
31 | n/a | 'OptionContainer', |
---|
32 | n/a | 'OptionGroup', |
---|
33 | n/a | 'OptionParser', |
---|
34 | n/a | 'HelpFormatter', |
---|
35 | n/a | 'IndentedHelpFormatter', |
---|
36 | n/a | 'TitledHelpFormatter', |
---|
37 | n/a | 'OptParseError', |
---|
38 | n/a | 'OptionError', |
---|
39 | n/a | 'OptionConflictError', |
---|
40 | n/a | 'OptionValueError', |
---|
41 | n/a | 'BadOptionError', |
---|
42 | n/a | 'check_choice'] |
---|
43 | n/a | |
---|
44 | n/a | __copyright__ = """ |
---|
45 | n/a | Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved. |
---|
46 | n/a | Copyright (c) 2002-2006 Python Software Foundation. All rights reserved. |
---|
47 | n/a | |
---|
48 | n/a | Redistribution and use in source and binary forms, with or without |
---|
49 | n/a | modification, are permitted provided that the following conditions are |
---|
50 | n/a | met: |
---|
51 | n/a | |
---|
52 | n/a | * Redistributions of source code must retain the above copyright |
---|
53 | n/a | notice, this list of conditions and the following disclaimer. |
---|
54 | n/a | |
---|
55 | n/a | * Redistributions in binary form must reproduce the above copyright |
---|
56 | n/a | notice, this list of conditions and the following disclaimer in the |
---|
57 | n/a | documentation and/or other materials provided with the distribution. |
---|
58 | n/a | |
---|
59 | n/a | * Neither the name of the author nor the names of its |
---|
60 | n/a | contributors may be used to endorse or promote products derived from |
---|
61 | n/a | this software without specific prior written permission. |
---|
62 | n/a | |
---|
63 | n/a | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS |
---|
64 | n/a | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED |
---|
65 | n/a | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
---|
66 | n/a | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR |
---|
67 | n/a | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, |
---|
68 | n/a | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
---|
69 | n/a | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR |
---|
70 | n/a | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF |
---|
71 | n/a | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING |
---|
72 | n/a | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
---|
73 | n/a | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
---|
74 | n/a | """ |
---|
75 | n/a | |
---|
76 | n/a | import sys, os |
---|
77 | n/a | import textwrap |
---|
78 | n/a | |
---|
79 | n/a | def _repr(self): |
---|
80 | n/a | return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self) |
---|
81 | n/a | |
---|
82 | n/a | |
---|
83 | n/a | # This file was generated from: |
---|
84 | n/a | # Id: option_parser.py 527 2006-07-23 15:21:30Z greg |
---|
85 | n/a | # Id: option.py 522 2006-06-11 16:22:03Z gward |
---|
86 | n/a | # Id: help.py 527 2006-07-23 15:21:30Z greg |
---|
87 | n/a | # Id: errors.py 509 2006-04-20 00:58:24Z gward |
---|
88 | n/a | |
---|
89 | n/a | try: |
---|
90 | n/a | from gettext import gettext, ngettext |
---|
91 | n/a | except ImportError: |
---|
92 | n/a | def gettext(message): |
---|
93 | n/a | return message |
---|
94 | n/a | |
---|
95 | n/a | def ngettext(singular, plural, n): |
---|
96 | n/a | if n == 1: |
---|
97 | n/a | return singular |
---|
98 | n/a | return plural |
---|
99 | n/a | |
---|
100 | n/a | _ = gettext |
---|
101 | n/a | |
---|
102 | n/a | |
---|
103 | n/a | class OptParseError (Exception): |
---|
104 | n/a | def __init__(self, msg): |
---|
105 | n/a | self.msg = msg |
---|
106 | n/a | |
---|
107 | n/a | def __str__(self): |
---|
108 | n/a | return self.msg |
---|
109 | n/a | |
---|
110 | n/a | |
---|
111 | n/a | class OptionError (OptParseError): |
---|
112 | n/a | """ |
---|
113 | n/a | Raised if an Option instance is created with invalid or |
---|
114 | n/a | inconsistent arguments. |
---|
115 | n/a | """ |
---|
116 | n/a | |
---|
117 | n/a | def __init__(self, msg, option): |
---|
118 | n/a | self.msg = msg |
---|
119 | n/a | self.option_id = str(option) |
---|
120 | n/a | |
---|
121 | n/a | def __str__(self): |
---|
122 | n/a | if self.option_id: |
---|
123 | n/a | return "option %s: %s" % (self.option_id, self.msg) |
---|
124 | n/a | else: |
---|
125 | n/a | return self.msg |
---|
126 | n/a | |
---|
127 | n/a | class OptionConflictError (OptionError): |
---|
128 | n/a | """ |
---|
129 | n/a | Raised if conflicting options are added to an OptionParser. |
---|
130 | n/a | """ |
---|
131 | n/a | |
---|
132 | n/a | class OptionValueError (OptParseError): |
---|
133 | n/a | """ |
---|
134 | n/a | Raised if an invalid option value is encountered on the command |
---|
135 | n/a | line. |
---|
136 | n/a | """ |
---|
137 | n/a | |
---|
138 | n/a | class BadOptionError (OptParseError): |
---|
139 | n/a | """ |
---|
140 | n/a | Raised if an invalid option is seen on the command line. |
---|
141 | n/a | """ |
---|
142 | n/a | def __init__(self, opt_str): |
---|
143 | n/a | self.opt_str = opt_str |
---|
144 | n/a | |
---|
145 | n/a | def __str__(self): |
---|
146 | n/a | return _("no such option: %s") % self.opt_str |
---|
147 | n/a | |
---|
148 | n/a | class AmbiguousOptionError (BadOptionError): |
---|
149 | n/a | """ |
---|
150 | n/a | Raised if an ambiguous option is seen on the command line. |
---|
151 | n/a | """ |
---|
152 | n/a | def __init__(self, opt_str, possibilities): |
---|
153 | n/a | BadOptionError.__init__(self, opt_str) |
---|
154 | n/a | self.possibilities = possibilities |
---|
155 | n/a | |
---|
156 | n/a | def __str__(self): |
---|
157 | n/a | return (_("ambiguous option: %s (%s?)") |
---|
158 | n/a | % (self.opt_str, ", ".join(self.possibilities))) |
---|
159 | n/a | |
---|
160 | n/a | |
---|
161 | n/a | class HelpFormatter: |
---|
162 | n/a | |
---|
163 | n/a | """ |
---|
164 | n/a | Abstract base class for formatting option help. OptionParser |
---|
165 | n/a | instances should use one of the HelpFormatter subclasses for |
---|
166 | n/a | formatting help; by default IndentedHelpFormatter is used. |
---|
167 | n/a | |
---|
168 | n/a | Instance attributes: |
---|
169 | n/a | parser : OptionParser |
---|
170 | n/a | the controlling OptionParser instance |
---|
171 | n/a | indent_increment : int |
---|
172 | n/a | the number of columns to indent per nesting level |
---|
173 | n/a | max_help_position : int |
---|
174 | n/a | the maximum starting column for option help text |
---|
175 | n/a | help_position : int |
---|
176 | n/a | the calculated starting column for option help text; |
---|
177 | n/a | initially the same as the maximum |
---|
178 | n/a | width : int |
---|
179 | n/a | total number of columns for output (pass None to constructor for |
---|
180 | n/a | this value to be taken from the $COLUMNS environment variable) |
---|
181 | n/a | level : int |
---|
182 | n/a | current indentation level |
---|
183 | n/a | current_indent : int |
---|
184 | n/a | current indentation level (in columns) |
---|
185 | n/a | help_width : int |
---|
186 | n/a | number of columns available for option help text (calculated) |
---|
187 | n/a | default_tag : str |
---|
188 | n/a | text to replace with each option's default value, "%default" |
---|
189 | n/a | by default. Set to false value to disable default value expansion. |
---|
190 | n/a | option_strings : { Option : str } |
---|
191 | n/a | maps Option instances to the snippet of help text explaining |
---|
192 | n/a | the syntax of that option, e.g. "-h, --help" or |
---|
193 | n/a | "-fFILE, --file=FILE" |
---|
194 | n/a | _short_opt_fmt : str |
---|
195 | n/a | format string controlling how short options with values are |
---|
196 | n/a | printed in help text. Must be either "%s%s" ("-fFILE") or |
---|
197 | n/a | "%s %s" ("-f FILE"), because those are the two syntaxes that |
---|
198 | n/a | Optik supports. |
---|
199 | n/a | _long_opt_fmt : str |
---|
200 | n/a | similar but for long options; must be either "%s %s" ("--file FILE") |
---|
201 | n/a | or "%s=%s" ("--file=FILE"). |
---|
202 | n/a | """ |
---|
203 | n/a | |
---|
204 | n/a | NO_DEFAULT_VALUE = "none" |
---|
205 | n/a | |
---|
206 | n/a | def __init__(self, |
---|
207 | n/a | indent_increment, |
---|
208 | n/a | max_help_position, |
---|
209 | n/a | width, |
---|
210 | n/a | short_first): |
---|
211 | n/a | self.parser = None |
---|
212 | n/a | self.indent_increment = indent_increment |
---|
213 | n/a | if width is None: |
---|
214 | n/a | try: |
---|
215 | n/a | width = int(os.environ['COLUMNS']) |
---|
216 | n/a | except (KeyError, ValueError): |
---|
217 | n/a | width = 80 |
---|
218 | n/a | width -= 2 |
---|
219 | n/a | self.width = width |
---|
220 | n/a | self.help_position = self.max_help_position = \ |
---|
221 | n/a | min(max_help_position, max(width - 20, indent_increment * 2)) |
---|
222 | n/a | self.current_indent = 0 |
---|
223 | n/a | self.level = 0 |
---|
224 | n/a | self.help_width = None # computed later |
---|
225 | n/a | self.short_first = short_first |
---|
226 | n/a | self.default_tag = "%default" |
---|
227 | n/a | self.option_strings = {} |
---|
228 | n/a | self._short_opt_fmt = "%s %s" |
---|
229 | n/a | self._long_opt_fmt = "%s=%s" |
---|
230 | n/a | |
---|
231 | n/a | def set_parser(self, parser): |
---|
232 | n/a | self.parser = parser |
---|
233 | n/a | |
---|
234 | n/a | def set_short_opt_delimiter(self, delim): |
---|
235 | n/a | if delim not in ("", " "): |
---|
236 | n/a | raise ValueError( |
---|
237 | n/a | "invalid metavar delimiter for short options: %r" % delim) |
---|
238 | n/a | self._short_opt_fmt = "%s" + delim + "%s" |
---|
239 | n/a | |
---|
240 | n/a | def set_long_opt_delimiter(self, delim): |
---|
241 | n/a | if delim not in ("=", " "): |
---|
242 | n/a | raise ValueError( |
---|
243 | n/a | "invalid metavar delimiter for long options: %r" % delim) |
---|
244 | n/a | self._long_opt_fmt = "%s" + delim + "%s" |
---|
245 | n/a | |
---|
246 | n/a | def indent(self): |
---|
247 | n/a | self.current_indent += self.indent_increment |
---|
248 | n/a | self.level += 1 |
---|
249 | n/a | |
---|
250 | n/a | def dedent(self): |
---|
251 | n/a | self.current_indent -= self.indent_increment |
---|
252 | n/a | assert self.current_indent >= 0, "Indent decreased below 0." |
---|
253 | n/a | self.level -= 1 |
---|
254 | n/a | |
---|
255 | n/a | def format_usage(self, usage): |
---|
256 | n/a | raise NotImplementedError("subclasses must implement") |
---|
257 | n/a | |
---|
258 | n/a | def format_heading(self, heading): |
---|
259 | n/a | raise NotImplementedError("subclasses must implement") |
---|
260 | n/a | |
---|
261 | n/a | def _format_text(self, text): |
---|
262 | n/a | """ |
---|
263 | n/a | Format a paragraph of free-form text for inclusion in the |
---|
264 | n/a | help output at the current indentation level. |
---|
265 | n/a | """ |
---|
266 | n/a | text_width = max(self.width - self.current_indent, 11) |
---|
267 | n/a | indent = " "*self.current_indent |
---|
268 | n/a | return textwrap.fill(text, |
---|
269 | n/a | text_width, |
---|
270 | n/a | initial_indent=indent, |
---|
271 | n/a | subsequent_indent=indent) |
---|
272 | n/a | |
---|
273 | n/a | def format_description(self, description): |
---|
274 | n/a | if description: |
---|
275 | n/a | return self._format_text(description) + "\n" |
---|
276 | n/a | else: |
---|
277 | n/a | return "" |
---|
278 | n/a | |
---|
279 | n/a | def format_epilog(self, epilog): |
---|
280 | n/a | if epilog: |
---|
281 | n/a | return "\n" + self._format_text(epilog) + "\n" |
---|
282 | n/a | else: |
---|
283 | n/a | return "" |
---|
284 | n/a | |
---|
285 | n/a | |
---|
286 | n/a | def expand_default(self, option): |
---|
287 | n/a | if self.parser is None or not self.default_tag: |
---|
288 | n/a | return option.help |
---|
289 | n/a | |
---|
290 | n/a | default_value = self.parser.defaults.get(option.dest) |
---|
291 | n/a | if default_value is NO_DEFAULT or default_value is None: |
---|
292 | n/a | default_value = self.NO_DEFAULT_VALUE |
---|
293 | n/a | |
---|
294 | n/a | return option.help.replace(self.default_tag, str(default_value)) |
---|
295 | n/a | |
---|
296 | n/a | def format_option(self, option): |
---|
297 | n/a | # The help for each option consists of two parts: |
---|
298 | n/a | # * the opt strings and metavars |
---|
299 | n/a | # eg. ("-x", or "-fFILENAME, --file=FILENAME") |
---|
300 | n/a | # * the user-supplied help string |
---|
301 | n/a | # eg. ("turn on expert mode", "read data from FILENAME") |
---|
302 | n/a | # |
---|
303 | n/a | # If possible, we write both of these on the same line: |
---|
304 | n/a | # -x turn on expert mode |
---|
305 | n/a | # |
---|
306 | n/a | # But if the opt string list is too long, we put the help |
---|
307 | n/a | # string on a second line, indented to the same column it would |
---|
308 | n/a | # start in if it fit on the first line. |
---|
309 | n/a | # -fFILENAME, --file=FILENAME |
---|
310 | n/a | # read data from FILENAME |
---|
311 | n/a | result = [] |
---|
312 | n/a | opts = self.option_strings[option] |
---|
313 | n/a | opt_width = self.help_position - self.current_indent - 2 |
---|
314 | n/a | if len(opts) > opt_width: |
---|
315 | n/a | opts = "%*s%s\n" % (self.current_indent, "", opts) |
---|
316 | n/a | indent_first = self.help_position |
---|
317 | n/a | else: # start help on same line as opts |
---|
318 | n/a | opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts) |
---|
319 | n/a | indent_first = 0 |
---|
320 | n/a | result.append(opts) |
---|
321 | n/a | if option.help: |
---|
322 | n/a | help_text = self.expand_default(option) |
---|
323 | n/a | help_lines = textwrap.wrap(help_text, self.help_width) |
---|
324 | n/a | result.append("%*s%s\n" % (indent_first, "", help_lines[0])) |
---|
325 | n/a | result.extend(["%*s%s\n" % (self.help_position, "", line) |
---|
326 | n/a | for line in help_lines[1:]]) |
---|
327 | n/a | elif opts[-1] != "\n": |
---|
328 | n/a | result.append("\n") |
---|
329 | n/a | return "".join(result) |
---|
330 | n/a | |
---|
331 | n/a | def store_option_strings(self, parser): |
---|
332 | n/a | self.indent() |
---|
333 | n/a | max_len = 0 |
---|
334 | n/a | for opt in parser.option_list: |
---|
335 | n/a | strings = self.format_option_strings(opt) |
---|
336 | n/a | self.option_strings[opt] = strings |
---|
337 | n/a | max_len = max(max_len, len(strings) + self.current_indent) |
---|
338 | n/a | self.indent() |
---|
339 | n/a | for group in parser.option_groups: |
---|
340 | n/a | for opt in group.option_list: |
---|
341 | n/a | strings = self.format_option_strings(opt) |
---|
342 | n/a | self.option_strings[opt] = strings |
---|
343 | n/a | max_len = max(max_len, len(strings) + self.current_indent) |
---|
344 | n/a | self.dedent() |
---|
345 | n/a | self.dedent() |
---|
346 | n/a | self.help_position = min(max_len + 2, self.max_help_position) |
---|
347 | n/a | self.help_width = max(self.width - self.help_position, 11) |
---|
348 | n/a | |
---|
349 | n/a | def format_option_strings(self, option): |
---|
350 | n/a | """Return a comma-separated list of option strings & metavariables.""" |
---|
351 | n/a | if option.takes_value(): |
---|
352 | n/a | metavar = option.metavar or option.dest.upper() |
---|
353 | n/a | short_opts = [self._short_opt_fmt % (sopt, metavar) |
---|
354 | n/a | for sopt in option._short_opts] |
---|
355 | n/a | long_opts = [self._long_opt_fmt % (lopt, metavar) |
---|
356 | n/a | for lopt in option._long_opts] |
---|
357 | n/a | else: |
---|
358 | n/a | short_opts = option._short_opts |
---|
359 | n/a | long_opts = option._long_opts |
---|
360 | n/a | |
---|
361 | n/a | if self.short_first: |
---|
362 | n/a | opts = short_opts + long_opts |
---|
363 | n/a | else: |
---|
364 | n/a | opts = long_opts + short_opts |
---|
365 | n/a | |
---|
366 | n/a | return ", ".join(opts) |
---|
367 | n/a | |
---|
368 | n/a | class IndentedHelpFormatter (HelpFormatter): |
---|
369 | n/a | """Format help with indented section bodies. |
---|
370 | n/a | """ |
---|
371 | n/a | |
---|
372 | n/a | def __init__(self, |
---|
373 | n/a | indent_increment=2, |
---|
374 | n/a | max_help_position=24, |
---|
375 | n/a | width=None, |
---|
376 | n/a | short_first=1): |
---|
377 | n/a | HelpFormatter.__init__( |
---|
378 | n/a | self, indent_increment, max_help_position, width, short_first) |
---|
379 | n/a | |
---|
380 | n/a | def format_usage(self, usage): |
---|
381 | n/a | return _("Usage: %s\n") % usage |
---|
382 | n/a | |
---|
383 | n/a | def format_heading(self, heading): |
---|
384 | n/a | return "%*s%s:\n" % (self.current_indent, "", heading) |
---|
385 | n/a | |
---|
386 | n/a | |
---|
387 | n/a | class TitledHelpFormatter (HelpFormatter): |
---|
388 | n/a | """Format help with underlined section headers. |
---|
389 | n/a | """ |
---|
390 | n/a | |
---|
391 | n/a | def __init__(self, |
---|
392 | n/a | indent_increment=0, |
---|
393 | n/a | max_help_position=24, |
---|
394 | n/a | width=None, |
---|
395 | n/a | short_first=0): |
---|
396 | n/a | HelpFormatter.__init__ ( |
---|
397 | n/a | self, indent_increment, max_help_position, width, short_first) |
---|
398 | n/a | |
---|
399 | n/a | def format_usage(self, usage): |
---|
400 | n/a | return "%s %s\n" % (self.format_heading(_("Usage")), usage) |
---|
401 | n/a | |
---|
402 | n/a | def format_heading(self, heading): |
---|
403 | n/a | return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading)) |
---|
404 | n/a | |
---|
405 | n/a | |
---|
406 | n/a | def _parse_num(val, type): |
---|
407 | n/a | if val[:2].lower() == "0x": # hexadecimal |
---|
408 | n/a | radix = 16 |
---|
409 | n/a | elif val[:2].lower() == "0b": # binary |
---|
410 | n/a | radix = 2 |
---|
411 | n/a | val = val[2:] or "0" # have to remove "0b" prefix |
---|
412 | n/a | elif val[:1] == "0": # octal |
---|
413 | n/a | radix = 8 |
---|
414 | n/a | else: # decimal |
---|
415 | n/a | radix = 10 |
---|
416 | n/a | |
---|
417 | n/a | return type(val, radix) |
---|
418 | n/a | |
---|
419 | n/a | def _parse_int(val): |
---|
420 | n/a | return _parse_num(val, int) |
---|
421 | n/a | |
---|
422 | n/a | _builtin_cvt = { "int" : (_parse_int, _("integer")), |
---|
423 | n/a | "long" : (_parse_int, _("integer")), |
---|
424 | n/a | "float" : (float, _("floating-point")), |
---|
425 | n/a | "complex" : (complex, _("complex")) } |
---|
426 | n/a | |
---|
427 | n/a | def check_builtin(option, opt, value): |
---|
428 | n/a | (cvt, what) = _builtin_cvt[option.type] |
---|
429 | n/a | try: |
---|
430 | n/a | return cvt(value) |
---|
431 | n/a | except ValueError: |
---|
432 | n/a | raise OptionValueError( |
---|
433 | n/a | _("option %s: invalid %s value: %r") % (opt, what, value)) |
---|
434 | n/a | |
---|
435 | n/a | def check_choice(option, opt, value): |
---|
436 | n/a | if value in option.choices: |
---|
437 | n/a | return value |
---|
438 | n/a | else: |
---|
439 | n/a | choices = ", ".join(map(repr, option.choices)) |
---|
440 | n/a | raise OptionValueError( |
---|
441 | n/a | _("option %s: invalid choice: %r (choose from %s)") |
---|
442 | n/a | % (opt, value, choices)) |
---|
443 | n/a | |
---|
444 | n/a | # Not supplying a default is different from a default of None, |
---|
445 | n/a | # so we need an explicit "not supplied" value. |
---|
446 | n/a | NO_DEFAULT = ("NO", "DEFAULT") |
---|
447 | n/a | |
---|
448 | n/a | |
---|
449 | n/a | class Option: |
---|
450 | n/a | """ |
---|
451 | n/a | Instance attributes: |
---|
452 | n/a | _short_opts : [string] |
---|
453 | n/a | _long_opts : [string] |
---|
454 | n/a | |
---|
455 | n/a | action : string |
---|
456 | n/a | type : string |
---|
457 | n/a | dest : string |
---|
458 | n/a | default : any |
---|
459 | n/a | nargs : int |
---|
460 | n/a | const : any |
---|
461 | n/a | choices : [string] |
---|
462 | n/a | callback : function |
---|
463 | n/a | callback_args : (any*) |
---|
464 | n/a | callback_kwargs : { string : any } |
---|
465 | n/a | help : string |
---|
466 | n/a | metavar : string |
---|
467 | n/a | """ |
---|
468 | n/a | |
---|
469 | n/a | # The list of instance attributes that may be set through |
---|
470 | n/a | # keyword args to the constructor. |
---|
471 | n/a | ATTRS = ['action', |
---|
472 | n/a | 'type', |
---|
473 | n/a | 'dest', |
---|
474 | n/a | 'default', |
---|
475 | n/a | 'nargs', |
---|
476 | n/a | 'const', |
---|
477 | n/a | 'choices', |
---|
478 | n/a | 'callback', |
---|
479 | n/a | 'callback_args', |
---|
480 | n/a | 'callback_kwargs', |
---|
481 | n/a | 'help', |
---|
482 | n/a | 'metavar'] |
---|
483 | n/a | |
---|
484 | n/a | # The set of actions allowed by option parsers. Explicitly listed |
---|
485 | n/a | # here so the constructor can validate its arguments. |
---|
486 | n/a | ACTIONS = ("store", |
---|
487 | n/a | "store_const", |
---|
488 | n/a | "store_true", |
---|
489 | n/a | "store_false", |
---|
490 | n/a | "append", |
---|
491 | n/a | "append_const", |
---|
492 | n/a | "count", |
---|
493 | n/a | "callback", |
---|
494 | n/a | "help", |
---|
495 | n/a | "version") |
---|
496 | n/a | |
---|
497 | n/a | # The set of actions that involve storing a value somewhere; |
---|
498 | n/a | # also listed just for constructor argument validation. (If |
---|
499 | n/a | # the action is one of these, there must be a destination.) |
---|
500 | n/a | STORE_ACTIONS = ("store", |
---|
501 | n/a | "store_const", |
---|
502 | n/a | "store_true", |
---|
503 | n/a | "store_false", |
---|
504 | n/a | "append", |
---|
505 | n/a | "append_const", |
---|
506 | n/a | "count") |
---|
507 | n/a | |
---|
508 | n/a | # The set of actions for which it makes sense to supply a value |
---|
509 | n/a | # type, ie. which may consume an argument from the command line. |
---|
510 | n/a | TYPED_ACTIONS = ("store", |
---|
511 | n/a | "append", |
---|
512 | n/a | "callback") |
---|
513 | n/a | |
---|
514 | n/a | # The set of actions which *require* a value type, ie. that |
---|
515 | n/a | # always consume an argument from the command line. |
---|
516 | n/a | ALWAYS_TYPED_ACTIONS = ("store", |
---|
517 | n/a | "append") |
---|
518 | n/a | |
---|
519 | n/a | # The set of actions which take a 'const' attribute. |
---|
520 | n/a | CONST_ACTIONS = ("store_const", |
---|
521 | n/a | "append_const") |
---|
522 | n/a | |
---|
523 | n/a | # The set of known types for option parsers. Again, listed here for |
---|
524 | n/a | # constructor argument validation. |
---|
525 | n/a | TYPES = ("string", "int", "long", "float", "complex", "choice") |
---|
526 | n/a | |
---|
527 | n/a | # Dictionary of argument checking functions, which convert and |
---|
528 | n/a | # validate option arguments according to the option type. |
---|
529 | n/a | # |
---|
530 | n/a | # Signature of checking functions is: |
---|
531 | n/a | # check(option : Option, opt : string, value : string) -> any |
---|
532 | n/a | # where |
---|
533 | n/a | # option is the Option instance calling the checker |
---|
534 | n/a | # opt is the actual option seen on the command-line |
---|
535 | n/a | # (eg. "-a", "--file") |
---|
536 | n/a | # value is the option argument seen on the command-line |
---|
537 | n/a | # |
---|
538 | n/a | # The return value should be in the appropriate Python type |
---|
539 | n/a | # for option.type -- eg. an integer if option.type == "int". |
---|
540 | n/a | # |
---|
541 | n/a | # If no checker is defined for a type, arguments will be |
---|
542 | n/a | # unchecked and remain strings. |
---|
543 | n/a | TYPE_CHECKER = { "int" : check_builtin, |
---|
544 | n/a | "long" : check_builtin, |
---|
545 | n/a | "float" : check_builtin, |
---|
546 | n/a | "complex": check_builtin, |
---|
547 | n/a | "choice" : check_choice, |
---|
548 | n/a | } |
---|
549 | n/a | |
---|
550 | n/a | |
---|
551 | n/a | # CHECK_METHODS is a list of unbound method objects; they are called |
---|
552 | n/a | # by the constructor, in order, after all attributes are |
---|
553 | n/a | # initialized. The list is created and filled in later, after all |
---|
554 | n/a | # the methods are actually defined. (I just put it here because I |
---|
555 | n/a | # like to define and document all class attributes in the same |
---|
556 | n/a | # place.) Subclasses that add another _check_*() method should |
---|
557 | n/a | # define their own CHECK_METHODS list that adds their check method |
---|
558 | n/a | # to those from this class. |
---|
559 | n/a | CHECK_METHODS = None |
---|
560 | n/a | |
---|
561 | n/a | |
---|
562 | n/a | # -- Constructor/initialization methods ---------------------------- |
---|
563 | n/a | |
---|
564 | n/a | def __init__(self, *opts, **attrs): |
---|
565 | n/a | # Set _short_opts, _long_opts attrs from 'opts' tuple. |
---|
566 | n/a | # Have to be set now, in case no option strings are supplied. |
---|
567 | n/a | self._short_opts = [] |
---|
568 | n/a | self._long_opts = [] |
---|
569 | n/a | opts = self._check_opt_strings(opts) |
---|
570 | n/a | self._set_opt_strings(opts) |
---|
571 | n/a | |
---|
572 | n/a | # Set all other attrs (action, type, etc.) from 'attrs' dict |
---|
573 | n/a | self._set_attrs(attrs) |
---|
574 | n/a | |
---|
575 | n/a | # Check all the attributes we just set. There are lots of |
---|
576 | n/a | # complicated interdependencies, but luckily they can be farmed |
---|
577 | n/a | # out to the _check_*() methods listed in CHECK_METHODS -- which |
---|
578 | n/a | # could be handy for subclasses! The one thing these all share |
---|
579 | n/a | # is that they raise OptionError if they discover a problem. |
---|
580 | n/a | for checker in self.CHECK_METHODS: |
---|
581 | n/a | checker(self) |
---|
582 | n/a | |
---|
583 | n/a | def _check_opt_strings(self, opts): |
---|
584 | n/a | # Filter out None because early versions of Optik had exactly |
---|
585 | n/a | # one short option and one long option, either of which |
---|
586 | n/a | # could be None. |
---|
587 | n/a | opts = [opt for opt in opts if opt] |
---|
588 | n/a | if not opts: |
---|
589 | n/a | raise TypeError("at least one option string must be supplied") |
---|
590 | n/a | return opts |
---|
591 | n/a | |
---|
592 | n/a | def _set_opt_strings(self, opts): |
---|
593 | n/a | for opt in opts: |
---|
594 | n/a | if len(opt) < 2: |
---|
595 | n/a | raise OptionError( |
---|
596 | n/a | "invalid option string %r: " |
---|
597 | n/a | "must be at least two characters long" % opt, self) |
---|
598 | n/a | elif len(opt) == 2: |
---|
599 | n/a | if not (opt[0] == "-" and opt[1] != "-"): |
---|
600 | n/a | raise OptionError( |
---|
601 | n/a | "invalid short option string %r: " |
---|
602 | n/a | "must be of the form -x, (x any non-dash char)" % opt, |
---|
603 | n/a | self) |
---|
604 | n/a | self._short_opts.append(opt) |
---|
605 | n/a | else: |
---|
606 | n/a | if not (opt[0:2] == "--" and opt[2] != "-"): |
---|
607 | n/a | raise OptionError( |
---|
608 | n/a | "invalid long option string %r: " |
---|
609 | n/a | "must start with --, followed by non-dash" % opt, |
---|
610 | n/a | self) |
---|
611 | n/a | self._long_opts.append(opt) |
---|
612 | n/a | |
---|
613 | n/a | def _set_attrs(self, attrs): |
---|
614 | n/a | for attr in self.ATTRS: |
---|
615 | n/a | if attr in attrs: |
---|
616 | n/a | setattr(self, attr, attrs[attr]) |
---|
617 | n/a | del attrs[attr] |
---|
618 | n/a | else: |
---|
619 | n/a | if attr == 'default': |
---|
620 | n/a | setattr(self, attr, NO_DEFAULT) |
---|
621 | n/a | else: |
---|
622 | n/a | setattr(self, attr, None) |
---|
623 | n/a | if attrs: |
---|
624 | n/a | attrs = sorted(attrs.keys()) |
---|
625 | n/a | raise OptionError( |
---|
626 | n/a | "invalid keyword arguments: %s" % ", ".join(attrs), |
---|
627 | n/a | self) |
---|
628 | n/a | |
---|
629 | n/a | |
---|
630 | n/a | # -- Constructor validation methods -------------------------------- |
---|
631 | n/a | |
---|
632 | n/a | def _check_action(self): |
---|
633 | n/a | if self.action is None: |
---|
634 | n/a | self.action = "store" |
---|
635 | n/a | elif self.action not in self.ACTIONS: |
---|
636 | n/a | raise OptionError("invalid action: %r" % self.action, self) |
---|
637 | n/a | |
---|
638 | n/a | def _check_type(self): |
---|
639 | n/a | if self.type is None: |
---|
640 | n/a | if self.action in self.ALWAYS_TYPED_ACTIONS: |
---|
641 | n/a | if self.choices is not None: |
---|
642 | n/a | # The "choices" attribute implies "choice" type. |
---|
643 | n/a | self.type = "choice" |
---|
644 | n/a | else: |
---|
645 | n/a | # No type given? "string" is the most sensible default. |
---|
646 | n/a | self.type = "string" |
---|
647 | n/a | else: |
---|
648 | n/a | # Allow type objects or builtin type conversion functions |
---|
649 | n/a | # (int, str, etc.) as an alternative to their names. |
---|
650 | n/a | if isinstance(self.type, type): |
---|
651 | n/a | self.type = self.type.__name__ |
---|
652 | n/a | |
---|
653 | n/a | if self.type == "str": |
---|
654 | n/a | self.type = "string" |
---|
655 | n/a | |
---|
656 | n/a | if self.type not in self.TYPES: |
---|
657 | n/a | raise OptionError("invalid option type: %r" % self.type, self) |
---|
658 | n/a | if self.action not in self.TYPED_ACTIONS: |
---|
659 | n/a | raise OptionError( |
---|
660 | n/a | "must not supply a type for action %r" % self.action, self) |
---|
661 | n/a | |
---|
662 | n/a | def _check_choice(self): |
---|
663 | n/a | if self.type == "choice": |
---|
664 | n/a | if self.choices is None: |
---|
665 | n/a | raise OptionError( |
---|
666 | n/a | "must supply a list of choices for type 'choice'", self) |
---|
667 | n/a | elif not isinstance(self.choices, (tuple, list)): |
---|
668 | n/a | raise OptionError( |
---|
669 | n/a | "choices must be a list of strings ('%s' supplied)" |
---|
670 | n/a | % str(type(self.choices)).split("'")[1], self) |
---|
671 | n/a | elif self.choices is not None: |
---|
672 | n/a | raise OptionError( |
---|
673 | n/a | "must not supply choices for type %r" % self.type, self) |
---|
674 | n/a | |
---|
675 | n/a | def _check_dest(self): |
---|
676 | n/a | # No destination given, and we need one for this action. The |
---|
677 | n/a | # self.type check is for callbacks that take a value. |
---|
678 | n/a | takes_value = (self.action in self.STORE_ACTIONS or |
---|
679 | n/a | self.type is not None) |
---|
680 | n/a | if self.dest is None and takes_value: |
---|
681 | n/a | |
---|
682 | n/a | # Glean a destination from the first long option string, |
---|
683 | n/a | # or from the first short option string if no long options. |
---|
684 | n/a | if self._long_opts: |
---|
685 | n/a | # eg. "--foo-bar" -> "foo_bar" |
---|
686 | n/a | self.dest = self._long_opts[0][2:].replace('-', '_') |
---|
687 | n/a | else: |
---|
688 | n/a | self.dest = self._short_opts[0][1] |
---|
689 | n/a | |
---|
690 | n/a | def _check_const(self): |
---|
691 | n/a | if self.action not in self.CONST_ACTIONS and self.const is not None: |
---|
692 | n/a | raise OptionError( |
---|
693 | n/a | "'const' must not be supplied for action %r" % self.action, |
---|
694 | n/a | self) |
---|
695 | n/a | |
---|
696 | n/a | def _check_nargs(self): |
---|
697 | n/a | if self.action in self.TYPED_ACTIONS: |
---|
698 | n/a | if self.nargs is None: |
---|
699 | n/a | self.nargs = 1 |
---|
700 | n/a | elif self.nargs is not None: |
---|
701 | n/a | raise OptionError( |
---|
702 | n/a | "'nargs' must not be supplied for action %r" % self.action, |
---|
703 | n/a | self) |
---|
704 | n/a | |
---|
705 | n/a | def _check_callback(self): |
---|
706 | n/a | if self.action == "callback": |
---|
707 | n/a | if not callable(self.callback): |
---|
708 | n/a | raise OptionError( |
---|
709 | n/a | "callback not callable: %r" % self.callback, self) |
---|
710 | n/a | if (self.callback_args is not None and |
---|
711 | n/a | not isinstance(self.callback_args, tuple)): |
---|
712 | n/a | raise OptionError( |
---|
713 | n/a | "callback_args, if supplied, must be a tuple: not %r" |
---|
714 | n/a | % self.callback_args, self) |
---|
715 | n/a | if (self.callback_kwargs is not None and |
---|
716 | n/a | not isinstance(self.callback_kwargs, dict)): |
---|
717 | n/a | raise OptionError( |
---|
718 | n/a | "callback_kwargs, if supplied, must be a dict: not %r" |
---|
719 | n/a | % self.callback_kwargs, self) |
---|
720 | n/a | else: |
---|
721 | n/a | if self.callback is not None: |
---|
722 | n/a | raise OptionError( |
---|
723 | n/a | "callback supplied (%r) for non-callback option" |
---|
724 | n/a | % self.callback, self) |
---|
725 | n/a | if self.callback_args is not None: |
---|
726 | n/a | raise OptionError( |
---|
727 | n/a | "callback_args supplied for non-callback option", self) |
---|
728 | n/a | if self.callback_kwargs is not None: |
---|
729 | n/a | raise OptionError( |
---|
730 | n/a | "callback_kwargs supplied for non-callback option", self) |
---|
731 | n/a | |
---|
732 | n/a | |
---|
733 | n/a | CHECK_METHODS = [_check_action, |
---|
734 | n/a | _check_type, |
---|
735 | n/a | _check_choice, |
---|
736 | n/a | _check_dest, |
---|
737 | n/a | _check_const, |
---|
738 | n/a | _check_nargs, |
---|
739 | n/a | _check_callback] |
---|
740 | n/a | |
---|
741 | n/a | |
---|
742 | n/a | # -- Miscellaneous methods ----------------------------------------- |
---|
743 | n/a | |
---|
744 | n/a | def __str__(self): |
---|
745 | n/a | return "/".join(self._short_opts + self._long_opts) |
---|
746 | n/a | |
---|
747 | n/a | __repr__ = _repr |
---|
748 | n/a | |
---|
749 | n/a | def takes_value(self): |
---|
750 | n/a | return self.type is not None |
---|
751 | n/a | |
---|
752 | n/a | def get_opt_string(self): |
---|
753 | n/a | if self._long_opts: |
---|
754 | n/a | return self._long_opts[0] |
---|
755 | n/a | else: |
---|
756 | n/a | return self._short_opts[0] |
---|
757 | n/a | |
---|
758 | n/a | |
---|
759 | n/a | # -- Processing methods -------------------------------------------- |
---|
760 | n/a | |
---|
761 | n/a | def check_value(self, opt, value): |
---|
762 | n/a | checker = self.TYPE_CHECKER.get(self.type) |
---|
763 | n/a | if checker is None: |
---|
764 | n/a | return value |
---|
765 | n/a | else: |
---|
766 | n/a | return checker(self, opt, value) |
---|
767 | n/a | |
---|
768 | n/a | def convert_value(self, opt, value): |
---|
769 | n/a | if value is not None: |
---|
770 | n/a | if self.nargs == 1: |
---|
771 | n/a | return self.check_value(opt, value) |
---|
772 | n/a | else: |
---|
773 | n/a | return tuple([self.check_value(opt, v) for v in value]) |
---|
774 | n/a | |
---|
775 | n/a | def process(self, opt, value, values, parser): |
---|
776 | n/a | |
---|
777 | n/a | # First, convert the value(s) to the right type. Howl if any |
---|
778 | n/a | # value(s) are bogus. |
---|
779 | n/a | value = self.convert_value(opt, value) |
---|
780 | n/a | |
---|
781 | n/a | # And then take whatever action is expected of us. |
---|
782 | n/a | # This is a separate method to make life easier for |
---|
783 | n/a | # subclasses to add new actions. |
---|
784 | n/a | return self.take_action( |
---|
785 | n/a | self.action, self.dest, opt, value, values, parser) |
---|
786 | n/a | |
---|
787 | n/a | def take_action(self, action, dest, opt, value, values, parser): |
---|
788 | n/a | if action == "store": |
---|
789 | n/a | setattr(values, dest, value) |
---|
790 | n/a | elif action == "store_const": |
---|
791 | n/a | setattr(values, dest, self.const) |
---|
792 | n/a | elif action == "store_true": |
---|
793 | n/a | setattr(values, dest, True) |
---|
794 | n/a | elif action == "store_false": |
---|
795 | n/a | setattr(values, dest, False) |
---|
796 | n/a | elif action == "append": |
---|
797 | n/a | values.ensure_value(dest, []).append(value) |
---|
798 | n/a | elif action == "append_const": |
---|
799 | n/a | values.ensure_value(dest, []).append(self.const) |
---|
800 | n/a | elif action == "count": |
---|
801 | n/a | setattr(values, dest, values.ensure_value(dest, 0) + 1) |
---|
802 | n/a | elif action == "callback": |
---|
803 | n/a | args = self.callback_args or () |
---|
804 | n/a | kwargs = self.callback_kwargs or {} |
---|
805 | n/a | self.callback(self, opt, value, parser, *args, **kwargs) |
---|
806 | n/a | elif action == "help": |
---|
807 | n/a | parser.print_help() |
---|
808 | n/a | parser.exit() |
---|
809 | n/a | elif action == "version": |
---|
810 | n/a | parser.print_version() |
---|
811 | n/a | parser.exit() |
---|
812 | n/a | else: |
---|
813 | n/a | raise ValueError("unknown action %r" % self.action) |
---|
814 | n/a | |
---|
815 | n/a | return 1 |
---|
816 | n/a | |
---|
817 | n/a | # class Option |
---|
818 | n/a | |
---|
819 | n/a | |
---|
820 | n/a | SUPPRESS_HELP = "SUPPRESS"+"HELP" |
---|
821 | n/a | SUPPRESS_USAGE = "SUPPRESS"+"USAGE" |
---|
822 | n/a | |
---|
823 | n/a | class Values: |
---|
824 | n/a | |
---|
825 | n/a | def __init__(self, defaults=None): |
---|
826 | n/a | if defaults: |
---|
827 | n/a | for (attr, val) in defaults.items(): |
---|
828 | n/a | setattr(self, attr, val) |
---|
829 | n/a | |
---|
830 | n/a | def __str__(self): |
---|
831 | n/a | return str(self.__dict__) |
---|
832 | n/a | |
---|
833 | n/a | __repr__ = _repr |
---|
834 | n/a | |
---|
835 | n/a | def __eq__(self, other): |
---|
836 | n/a | if isinstance(other, Values): |
---|
837 | n/a | return self.__dict__ == other.__dict__ |
---|
838 | n/a | elif isinstance(other, dict): |
---|
839 | n/a | return self.__dict__ == other |
---|
840 | n/a | else: |
---|
841 | n/a | return NotImplemented |
---|
842 | n/a | |
---|
843 | n/a | def _update_careful(self, dict): |
---|
844 | n/a | """ |
---|
845 | n/a | Update the option values from an arbitrary dictionary, but only |
---|
846 | n/a | use keys from dict that already have a corresponding attribute |
---|
847 | n/a | in self. Any keys in dict without a corresponding attribute |
---|
848 | n/a | are silently ignored. |
---|
849 | n/a | """ |
---|
850 | n/a | for attr in dir(self): |
---|
851 | n/a | if attr in dict: |
---|
852 | n/a | dval = dict[attr] |
---|
853 | n/a | if dval is not None: |
---|
854 | n/a | setattr(self, attr, dval) |
---|
855 | n/a | |
---|
856 | n/a | def _update_loose(self, dict): |
---|
857 | n/a | """ |
---|
858 | n/a | Update the option values from an arbitrary dictionary, |
---|
859 | n/a | using all keys from the dictionary regardless of whether |
---|
860 | n/a | they have a corresponding attribute in self or not. |
---|
861 | n/a | """ |
---|
862 | n/a | self.__dict__.update(dict) |
---|
863 | n/a | |
---|
864 | n/a | def _update(self, dict, mode): |
---|
865 | n/a | if mode == "careful": |
---|
866 | n/a | self._update_careful(dict) |
---|
867 | n/a | elif mode == "loose": |
---|
868 | n/a | self._update_loose(dict) |
---|
869 | n/a | else: |
---|
870 | n/a | raise ValueError("invalid update mode: %r" % mode) |
---|
871 | n/a | |
---|
872 | n/a | def read_module(self, modname, mode="careful"): |
---|
873 | n/a | __import__(modname) |
---|
874 | n/a | mod = sys.modules[modname] |
---|
875 | n/a | self._update(vars(mod), mode) |
---|
876 | n/a | |
---|
877 | n/a | def read_file(self, filename, mode="careful"): |
---|
878 | n/a | vars = {} |
---|
879 | n/a | exec(open(filename).read(), vars) |
---|
880 | n/a | self._update(vars, mode) |
---|
881 | n/a | |
---|
882 | n/a | def ensure_value(self, attr, value): |
---|
883 | n/a | if not hasattr(self, attr) or getattr(self, attr) is None: |
---|
884 | n/a | setattr(self, attr, value) |
---|
885 | n/a | return getattr(self, attr) |
---|
886 | n/a | |
---|
887 | n/a | |
---|
888 | n/a | class OptionContainer: |
---|
889 | n/a | |
---|
890 | n/a | """ |
---|
891 | n/a | Abstract base class. |
---|
892 | n/a | |
---|
893 | n/a | Class attributes: |
---|
894 | n/a | standard_option_list : [Option] |
---|
895 | n/a | list of standard options that will be accepted by all instances |
---|
896 | n/a | of this parser class (intended to be overridden by subclasses). |
---|
897 | n/a | |
---|
898 | n/a | Instance attributes: |
---|
899 | n/a | option_list : [Option] |
---|
900 | n/a | the list of Option objects contained by this OptionContainer |
---|
901 | n/a | _short_opt : { string : Option } |
---|
902 | n/a | dictionary mapping short option strings, eg. "-f" or "-X", |
---|
903 | n/a | to the Option instances that implement them. If an Option |
---|
904 | n/a | has multiple short option strings, it will appear in this |
---|
905 | n/a | dictionary multiple times. [1] |
---|
906 | n/a | _long_opt : { string : Option } |
---|
907 | n/a | dictionary mapping long option strings, eg. "--file" or |
---|
908 | n/a | "--exclude", to the Option instances that implement them. |
---|
909 | n/a | Again, a given Option can occur multiple times in this |
---|
910 | n/a | dictionary. [1] |
---|
911 | n/a | defaults : { string : any } |
---|
912 | n/a | dictionary mapping option destination names to default |
---|
913 | n/a | values for each destination [1] |
---|
914 | n/a | |
---|
915 | n/a | [1] These mappings are common to (shared by) all components of the |
---|
916 | n/a | controlling OptionParser, where they are initially created. |
---|
917 | n/a | |
---|
918 | n/a | """ |
---|
919 | n/a | |
---|
920 | n/a | def __init__(self, option_class, conflict_handler, description): |
---|
921 | n/a | # Initialize the option list and related data structures. |
---|
922 | n/a | # This method must be provided by subclasses, and it must |
---|
923 | n/a | # initialize at least the following instance attributes: |
---|
924 | n/a | # option_list, _short_opt, _long_opt, defaults. |
---|
925 | n/a | self._create_option_list() |
---|
926 | n/a | |
---|
927 | n/a | self.option_class = option_class |
---|
928 | n/a | self.set_conflict_handler(conflict_handler) |
---|
929 | n/a | self.set_description(description) |
---|
930 | n/a | |
---|
931 | n/a | def _create_option_mappings(self): |
---|
932 | n/a | # For use by OptionParser constructor -- create the master |
---|
933 | n/a | # option mappings used by this OptionParser and all |
---|
934 | n/a | # OptionGroups that it owns. |
---|
935 | n/a | self._short_opt = {} # single letter -> Option instance |
---|
936 | n/a | self._long_opt = {} # long option -> Option instance |
---|
937 | n/a | self.defaults = {} # maps option dest -> default value |
---|
938 | n/a | |
---|
939 | n/a | |
---|
940 | n/a | def _share_option_mappings(self, parser): |
---|
941 | n/a | # For use by OptionGroup constructor -- use shared option |
---|
942 | n/a | # mappings from the OptionParser that owns this OptionGroup. |
---|
943 | n/a | self._short_opt = parser._short_opt |
---|
944 | n/a | self._long_opt = parser._long_opt |
---|
945 | n/a | self.defaults = parser.defaults |
---|
946 | n/a | |
---|
947 | n/a | def set_conflict_handler(self, handler): |
---|
948 | n/a | if handler not in ("error", "resolve"): |
---|
949 | n/a | raise ValueError("invalid conflict_resolution value %r" % handler) |
---|
950 | n/a | self.conflict_handler = handler |
---|
951 | n/a | |
---|
952 | n/a | def set_description(self, description): |
---|
953 | n/a | self.description = description |
---|
954 | n/a | |
---|
955 | n/a | def get_description(self): |
---|
956 | n/a | return self.description |
---|
957 | n/a | |
---|
958 | n/a | |
---|
959 | n/a | def destroy(self): |
---|
960 | n/a | """see OptionParser.destroy().""" |
---|
961 | n/a | del self._short_opt |
---|
962 | n/a | del self._long_opt |
---|
963 | n/a | del self.defaults |
---|
964 | n/a | |
---|
965 | n/a | |
---|
966 | n/a | # -- Option-adding methods ----------------------------------------- |
---|
967 | n/a | |
---|
968 | n/a | def _check_conflict(self, option): |
---|
969 | n/a | conflict_opts = [] |
---|
970 | n/a | for opt in option._short_opts: |
---|
971 | n/a | if opt in self._short_opt: |
---|
972 | n/a | conflict_opts.append((opt, self._short_opt[opt])) |
---|
973 | n/a | for opt in option._long_opts: |
---|
974 | n/a | if opt in self._long_opt: |
---|
975 | n/a | conflict_opts.append((opt, self._long_opt[opt])) |
---|
976 | n/a | |
---|
977 | n/a | if conflict_opts: |
---|
978 | n/a | handler = self.conflict_handler |
---|
979 | n/a | if handler == "error": |
---|
980 | n/a | raise OptionConflictError( |
---|
981 | n/a | "conflicting option string(s): %s" |
---|
982 | n/a | % ", ".join([co[0] for co in conflict_opts]), |
---|
983 | n/a | option) |
---|
984 | n/a | elif handler == "resolve": |
---|
985 | n/a | for (opt, c_option) in conflict_opts: |
---|
986 | n/a | if opt.startswith("--"): |
---|
987 | n/a | c_option._long_opts.remove(opt) |
---|
988 | n/a | del self._long_opt[opt] |
---|
989 | n/a | else: |
---|
990 | n/a | c_option._short_opts.remove(opt) |
---|
991 | n/a | del self._short_opt[opt] |
---|
992 | n/a | if not (c_option._short_opts or c_option._long_opts): |
---|
993 | n/a | c_option.container.option_list.remove(c_option) |
---|
994 | n/a | |
---|
995 | n/a | def add_option(self, *args, **kwargs): |
---|
996 | n/a | """add_option(Option) |
---|
997 | n/a | add_option(opt_str, ..., kwarg=val, ...) |
---|
998 | n/a | """ |
---|
999 | n/a | if isinstance(args[0], str): |
---|
1000 | n/a | option = self.option_class(*args, **kwargs) |
---|
1001 | n/a | elif len(args) == 1 and not kwargs: |
---|
1002 | n/a | option = args[0] |
---|
1003 | n/a | if not isinstance(option, Option): |
---|
1004 | n/a | raise TypeError("not an Option instance: %r" % option) |
---|
1005 | n/a | else: |
---|
1006 | n/a | raise TypeError("invalid arguments") |
---|
1007 | n/a | |
---|
1008 | n/a | self._check_conflict(option) |
---|
1009 | n/a | |
---|
1010 | n/a | self.option_list.append(option) |
---|
1011 | n/a | option.container = self |
---|
1012 | n/a | for opt in option._short_opts: |
---|
1013 | n/a | self._short_opt[opt] = option |
---|
1014 | n/a | for opt in option._long_opts: |
---|
1015 | n/a | self._long_opt[opt] = option |
---|
1016 | n/a | |
---|
1017 | n/a | if option.dest is not None: # option has a dest, we need a default |
---|
1018 | n/a | if option.default is not NO_DEFAULT: |
---|
1019 | n/a | self.defaults[option.dest] = option.default |
---|
1020 | n/a | elif option.dest not in self.defaults: |
---|
1021 | n/a | self.defaults[option.dest] = None |
---|
1022 | n/a | |
---|
1023 | n/a | return option |
---|
1024 | n/a | |
---|
1025 | n/a | def add_options(self, option_list): |
---|
1026 | n/a | for option in option_list: |
---|
1027 | n/a | self.add_option(option) |
---|
1028 | n/a | |
---|
1029 | n/a | # -- Option query/removal methods ---------------------------------- |
---|
1030 | n/a | |
---|
1031 | n/a | def get_option(self, opt_str): |
---|
1032 | n/a | return (self._short_opt.get(opt_str) or |
---|
1033 | n/a | self._long_opt.get(opt_str)) |
---|
1034 | n/a | |
---|
1035 | n/a | def has_option(self, opt_str): |
---|
1036 | n/a | return (opt_str in self._short_opt or |
---|
1037 | n/a | opt_str in self._long_opt) |
---|
1038 | n/a | |
---|
1039 | n/a | def remove_option(self, opt_str): |
---|
1040 | n/a | option = self._short_opt.get(opt_str) |
---|
1041 | n/a | if option is None: |
---|
1042 | n/a | option = self._long_opt.get(opt_str) |
---|
1043 | n/a | if option is None: |
---|
1044 | n/a | raise ValueError("no such option %r" % opt_str) |
---|
1045 | n/a | |
---|
1046 | n/a | for opt in option._short_opts: |
---|
1047 | n/a | del self._short_opt[opt] |
---|
1048 | n/a | for opt in option._long_opts: |
---|
1049 | n/a | del self._long_opt[opt] |
---|
1050 | n/a | option.container.option_list.remove(option) |
---|
1051 | n/a | |
---|
1052 | n/a | |
---|
1053 | n/a | # -- Help-formatting methods --------------------------------------- |
---|
1054 | n/a | |
---|
1055 | n/a | def format_option_help(self, formatter): |
---|
1056 | n/a | if not self.option_list: |
---|
1057 | n/a | return "" |
---|
1058 | n/a | result = [] |
---|
1059 | n/a | for option in self.option_list: |
---|
1060 | n/a | if not option.help is SUPPRESS_HELP: |
---|
1061 | n/a | result.append(formatter.format_option(option)) |
---|
1062 | n/a | return "".join(result) |
---|
1063 | n/a | |
---|
1064 | n/a | def format_description(self, formatter): |
---|
1065 | n/a | return formatter.format_description(self.get_description()) |
---|
1066 | n/a | |
---|
1067 | n/a | def format_help(self, formatter): |
---|
1068 | n/a | result = [] |
---|
1069 | n/a | if self.description: |
---|
1070 | n/a | result.append(self.format_description(formatter)) |
---|
1071 | n/a | if self.option_list: |
---|
1072 | n/a | result.append(self.format_option_help(formatter)) |
---|
1073 | n/a | return "\n".join(result) |
---|
1074 | n/a | |
---|
1075 | n/a | |
---|
1076 | n/a | class OptionGroup (OptionContainer): |
---|
1077 | n/a | |
---|
1078 | n/a | def __init__(self, parser, title, description=None): |
---|
1079 | n/a | self.parser = parser |
---|
1080 | n/a | OptionContainer.__init__( |
---|
1081 | n/a | self, parser.option_class, parser.conflict_handler, description) |
---|
1082 | n/a | self.title = title |
---|
1083 | n/a | |
---|
1084 | n/a | def _create_option_list(self): |
---|
1085 | n/a | self.option_list = [] |
---|
1086 | n/a | self._share_option_mappings(self.parser) |
---|
1087 | n/a | |
---|
1088 | n/a | def set_title(self, title): |
---|
1089 | n/a | self.title = title |
---|
1090 | n/a | |
---|
1091 | n/a | def destroy(self): |
---|
1092 | n/a | """see OptionParser.destroy().""" |
---|
1093 | n/a | OptionContainer.destroy(self) |
---|
1094 | n/a | del self.option_list |
---|
1095 | n/a | |
---|
1096 | n/a | # -- Help-formatting methods --------------------------------------- |
---|
1097 | n/a | |
---|
1098 | n/a | def format_help(self, formatter): |
---|
1099 | n/a | result = formatter.format_heading(self.title) |
---|
1100 | n/a | formatter.indent() |
---|
1101 | n/a | result += OptionContainer.format_help(self, formatter) |
---|
1102 | n/a | formatter.dedent() |
---|
1103 | n/a | return result |
---|
1104 | n/a | |
---|
1105 | n/a | |
---|
1106 | n/a | class OptionParser (OptionContainer): |
---|
1107 | n/a | |
---|
1108 | n/a | """ |
---|
1109 | n/a | Class attributes: |
---|
1110 | n/a | standard_option_list : [Option] |
---|
1111 | n/a | list of standard options that will be accepted by all instances |
---|
1112 | n/a | of this parser class (intended to be overridden by subclasses). |
---|
1113 | n/a | |
---|
1114 | n/a | Instance attributes: |
---|
1115 | n/a | usage : string |
---|
1116 | n/a | a usage string for your program. Before it is displayed |
---|
1117 | n/a | to the user, "%prog" will be expanded to the name of |
---|
1118 | n/a | your program (self.prog or os.path.basename(sys.argv[0])). |
---|
1119 | n/a | prog : string |
---|
1120 | n/a | the name of the current program (to override |
---|
1121 | n/a | os.path.basename(sys.argv[0])). |
---|
1122 | n/a | description : string |
---|
1123 | n/a | A paragraph of text giving a brief overview of your program. |
---|
1124 | n/a | optparse reformats this paragraph to fit the current terminal |
---|
1125 | n/a | width and prints it when the user requests help (after usage, |
---|
1126 | n/a | but before the list of options). |
---|
1127 | n/a | epilog : string |
---|
1128 | n/a | paragraph of help text to print after option help |
---|
1129 | n/a | |
---|
1130 | n/a | option_groups : [OptionGroup] |
---|
1131 | n/a | list of option groups in this parser (option groups are |
---|
1132 | n/a | irrelevant for parsing the command-line, but very useful |
---|
1133 | n/a | for generating help) |
---|
1134 | n/a | |
---|
1135 | n/a | allow_interspersed_args : bool = true |
---|
1136 | n/a | if true, positional arguments may be interspersed with options. |
---|
1137 | n/a | Assuming -a and -b each take a single argument, the command-line |
---|
1138 | n/a | -ablah foo bar -bboo baz |
---|
1139 | n/a | will be interpreted the same as |
---|
1140 | n/a | -ablah -bboo -- foo bar baz |
---|
1141 | n/a | If this flag were false, that command line would be interpreted as |
---|
1142 | n/a | -ablah -- foo bar -bboo baz |
---|
1143 | n/a | -- ie. we stop processing options as soon as we see the first |
---|
1144 | n/a | non-option argument. (This is the tradition followed by |
---|
1145 | n/a | Python's getopt module, Perl's Getopt::Std, and other argument- |
---|
1146 | n/a | parsing libraries, but it is generally annoying to users.) |
---|
1147 | n/a | |
---|
1148 | n/a | process_default_values : bool = true |
---|
1149 | n/a | if true, option default values are processed similarly to option |
---|
1150 | n/a | values from the command line: that is, they are passed to the |
---|
1151 | n/a | type-checking function for the option's type (as long as the |
---|
1152 | n/a | default value is a string). (This really only matters if you |
---|
1153 | n/a | have defined custom types; see SF bug #955889.) Set it to false |
---|
1154 | n/a | to restore the behaviour of Optik 1.4.1 and earlier. |
---|
1155 | n/a | |
---|
1156 | n/a | rargs : [string] |
---|
1157 | n/a | the argument list currently being parsed. Only set when |
---|
1158 | n/a | parse_args() is active, and continually trimmed down as |
---|
1159 | n/a | we consume arguments. Mainly there for the benefit of |
---|
1160 | n/a | callback options. |
---|
1161 | n/a | largs : [string] |
---|
1162 | n/a | the list of leftover arguments that we have skipped while |
---|
1163 | n/a | parsing options. If allow_interspersed_args is false, this |
---|
1164 | n/a | list is always empty. |
---|
1165 | n/a | values : Values |
---|
1166 | n/a | the set of option values currently being accumulated. Only |
---|
1167 | n/a | set when parse_args() is active. Also mainly for callbacks. |
---|
1168 | n/a | |
---|
1169 | n/a | Because of the 'rargs', 'largs', and 'values' attributes, |
---|
1170 | n/a | OptionParser is not thread-safe. If, for some perverse reason, you |
---|
1171 | n/a | need to parse command-line arguments simultaneously in different |
---|
1172 | n/a | threads, use different OptionParser instances. |
---|
1173 | n/a | |
---|
1174 | n/a | """ |
---|
1175 | n/a | |
---|
1176 | n/a | standard_option_list = [] |
---|
1177 | n/a | |
---|
1178 | n/a | def __init__(self, |
---|
1179 | n/a | usage=None, |
---|
1180 | n/a | option_list=None, |
---|
1181 | n/a | option_class=Option, |
---|
1182 | n/a | version=None, |
---|
1183 | n/a | conflict_handler="error", |
---|
1184 | n/a | description=None, |
---|
1185 | n/a | formatter=None, |
---|
1186 | n/a | add_help_option=True, |
---|
1187 | n/a | prog=None, |
---|
1188 | n/a | epilog=None): |
---|
1189 | n/a | OptionContainer.__init__( |
---|
1190 | n/a | self, option_class, conflict_handler, description) |
---|
1191 | n/a | self.set_usage(usage) |
---|
1192 | n/a | self.prog = prog |
---|
1193 | n/a | self.version = version |
---|
1194 | n/a | self.allow_interspersed_args = True |
---|
1195 | n/a | self.process_default_values = True |
---|
1196 | n/a | if formatter is None: |
---|
1197 | n/a | formatter = IndentedHelpFormatter() |
---|
1198 | n/a | self.formatter = formatter |
---|
1199 | n/a | self.formatter.set_parser(self) |
---|
1200 | n/a | self.epilog = epilog |
---|
1201 | n/a | |
---|
1202 | n/a | # Populate the option list; initial sources are the |
---|
1203 | n/a | # standard_option_list class attribute, the 'option_list' |
---|
1204 | n/a | # argument, and (if applicable) the _add_version_option() and |
---|
1205 | n/a | # _add_help_option() methods. |
---|
1206 | n/a | self._populate_option_list(option_list, |
---|
1207 | n/a | add_help=add_help_option) |
---|
1208 | n/a | |
---|
1209 | n/a | self._init_parsing_state() |
---|
1210 | n/a | |
---|
1211 | n/a | |
---|
1212 | n/a | def destroy(self): |
---|
1213 | n/a | """ |
---|
1214 | n/a | Declare that you are done with this OptionParser. This cleans up |
---|
1215 | n/a | reference cycles so the OptionParser (and all objects referenced by |
---|
1216 | n/a | it) can be garbage-collected promptly. After calling destroy(), the |
---|
1217 | n/a | OptionParser is unusable. |
---|
1218 | n/a | """ |
---|
1219 | n/a | OptionContainer.destroy(self) |
---|
1220 | n/a | for group in self.option_groups: |
---|
1221 | n/a | group.destroy() |
---|
1222 | n/a | del self.option_list |
---|
1223 | n/a | del self.option_groups |
---|
1224 | n/a | del self.formatter |
---|
1225 | n/a | |
---|
1226 | n/a | |
---|
1227 | n/a | # -- Private methods ----------------------------------------------- |
---|
1228 | n/a | # (used by our or OptionContainer's constructor) |
---|
1229 | n/a | |
---|
1230 | n/a | def _create_option_list(self): |
---|
1231 | n/a | self.option_list = [] |
---|
1232 | n/a | self.option_groups = [] |
---|
1233 | n/a | self._create_option_mappings() |
---|
1234 | n/a | |
---|
1235 | n/a | def _add_help_option(self): |
---|
1236 | n/a | self.add_option("-h", "--help", |
---|
1237 | n/a | action="help", |
---|
1238 | n/a | help=_("show this help message and exit")) |
---|
1239 | n/a | |
---|
1240 | n/a | def _add_version_option(self): |
---|
1241 | n/a | self.add_option("--version", |
---|
1242 | n/a | action="version", |
---|
1243 | n/a | help=_("show program's version number and exit")) |
---|
1244 | n/a | |
---|
1245 | n/a | def _populate_option_list(self, option_list, add_help=True): |
---|
1246 | n/a | if self.standard_option_list: |
---|
1247 | n/a | self.add_options(self.standard_option_list) |
---|
1248 | n/a | if option_list: |
---|
1249 | n/a | self.add_options(option_list) |
---|
1250 | n/a | if self.version: |
---|
1251 | n/a | self._add_version_option() |
---|
1252 | n/a | if add_help: |
---|
1253 | n/a | self._add_help_option() |
---|
1254 | n/a | |
---|
1255 | n/a | def _init_parsing_state(self): |
---|
1256 | n/a | # These are set in parse_args() for the convenience of callbacks. |
---|
1257 | n/a | self.rargs = None |
---|
1258 | n/a | self.largs = None |
---|
1259 | n/a | self.values = None |
---|
1260 | n/a | |
---|
1261 | n/a | |
---|
1262 | n/a | # -- Simple modifier methods --------------------------------------- |
---|
1263 | n/a | |
---|
1264 | n/a | def set_usage(self, usage): |
---|
1265 | n/a | if usage is None: |
---|
1266 | n/a | self.usage = _("%prog [options]") |
---|
1267 | n/a | elif usage is SUPPRESS_USAGE: |
---|
1268 | n/a | self.usage = None |
---|
1269 | n/a | # For backwards compatibility with Optik 1.3 and earlier. |
---|
1270 | n/a | elif usage.lower().startswith("usage: "): |
---|
1271 | n/a | self.usage = usage[7:] |
---|
1272 | n/a | else: |
---|
1273 | n/a | self.usage = usage |
---|
1274 | n/a | |
---|
1275 | n/a | def enable_interspersed_args(self): |
---|
1276 | n/a | """Set parsing to not stop on the first non-option, allowing |
---|
1277 | n/a | interspersing switches with command arguments. This is the |
---|
1278 | n/a | default behavior. See also disable_interspersed_args() and the |
---|
1279 | n/a | class documentation description of the attribute |
---|
1280 | n/a | allow_interspersed_args.""" |
---|
1281 | n/a | self.allow_interspersed_args = True |
---|
1282 | n/a | |
---|
1283 | n/a | def disable_interspersed_args(self): |
---|
1284 | n/a | """Set parsing to stop on the first non-option. Use this if |
---|
1285 | n/a | you have a command processor which runs another command that |
---|
1286 | n/a | has options of its own and you want to make sure these options |
---|
1287 | n/a | don't get confused. |
---|
1288 | n/a | """ |
---|
1289 | n/a | self.allow_interspersed_args = False |
---|
1290 | n/a | |
---|
1291 | n/a | def set_process_default_values(self, process): |
---|
1292 | n/a | self.process_default_values = process |
---|
1293 | n/a | |
---|
1294 | n/a | def set_default(self, dest, value): |
---|
1295 | n/a | self.defaults[dest] = value |
---|
1296 | n/a | |
---|
1297 | n/a | def set_defaults(self, **kwargs): |
---|
1298 | n/a | self.defaults.update(kwargs) |
---|
1299 | n/a | |
---|
1300 | n/a | def _get_all_options(self): |
---|
1301 | n/a | options = self.option_list[:] |
---|
1302 | n/a | for group in self.option_groups: |
---|
1303 | n/a | options.extend(group.option_list) |
---|
1304 | n/a | return options |
---|
1305 | n/a | |
---|
1306 | n/a | def get_default_values(self): |
---|
1307 | n/a | if not self.process_default_values: |
---|
1308 | n/a | # Old, pre-Optik 1.5 behaviour. |
---|
1309 | n/a | return Values(self.defaults) |
---|
1310 | n/a | |
---|
1311 | n/a | defaults = self.defaults.copy() |
---|
1312 | n/a | for option in self._get_all_options(): |
---|
1313 | n/a | default = defaults.get(option.dest) |
---|
1314 | n/a | if isinstance(default, str): |
---|
1315 | n/a | opt_str = option.get_opt_string() |
---|
1316 | n/a | defaults[option.dest] = option.check_value(opt_str, default) |
---|
1317 | n/a | |
---|
1318 | n/a | return Values(defaults) |
---|
1319 | n/a | |
---|
1320 | n/a | |
---|
1321 | n/a | # -- OptionGroup methods ------------------------------------------- |
---|
1322 | n/a | |
---|
1323 | n/a | def add_option_group(self, *args, **kwargs): |
---|
1324 | n/a | # XXX lots of overlap with OptionContainer.add_option() |
---|
1325 | n/a | if isinstance(args[0], str): |
---|
1326 | n/a | group = OptionGroup(self, *args, **kwargs) |
---|
1327 | n/a | elif len(args) == 1 and not kwargs: |
---|
1328 | n/a | group = args[0] |
---|
1329 | n/a | if not isinstance(group, OptionGroup): |
---|
1330 | n/a | raise TypeError("not an OptionGroup instance: %r" % group) |
---|
1331 | n/a | if group.parser is not self: |
---|
1332 | n/a | raise ValueError("invalid OptionGroup (wrong parser)") |
---|
1333 | n/a | else: |
---|
1334 | n/a | raise TypeError("invalid arguments") |
---|
1335 | n/a | |
---|
1336 | n/a | self.option_groups.append(group) |
---|
1337 | n/a | return group |
---|
1338 | n/a | |
---|
1339 | n/a | def get_option_group(self, opt_str): |
---|
1340 | n/a | option = (self._short_opt.get(opt_str) or |
---|
1341 | n/a | self._long_opt.get(opt_str)) |
---|
1342 | n/a | if option and option.container is not self: |
---|
1343 | n/a | return option.container |
---|
1344 | n/a | return None |
---|
1345 | n/a | |
---|
1346 | n/a | |
---|
1347 | n/a | # -- Option-parsing methods ---------------------------------------- |
---|
1348 | n/a | |
---|
1349 | n/a | def _get_args(self, args): |
---|
1350 | n/a | if args is None: |
---|
1351 | n/a | return sys.argv[1:] |
---|
1352 | n/a | else: |
---|
1353 | n/a | return args[:] # don't modify caller's list |
---|
1354 | n/a | |
---|
1355 | n/a | def parse_args(self, args=None, values=None): |
---|
1356 | n/a | """ |
---|
1357 | n/a | parse_args(args : [string] = sys.argv[1:], |
---|
1358 | n/a | values : Values = None) |
---|
1359 | n/a | -> (values : Values, args : [string]) |
---|
1360 | n/a | |
---|
1361 | n/a | Parse the command-line options found in 'args' (default: |
---|
1362 | n/a | sys.argv[1:]). Any errors result in a call to 'error()', which |
---|
1363 | n/a | by default prints the usage message to stderr and calls |
---|
1364 | n/a | sys.exit() with an error message. On success returns a pair |
---|
1365 | n/a | (values, args) where 'values' is a Values instance (with all |
---|
1366 | n/a | your option values) and 'args' is the list of arguments left |
---|
1367 | n/a | over after parsing options. |
---|
1368 | n/a | """ |
---|
1369 | n/a | rargs = self._get_args(args) |
---|
1370 | n/a | if values is None: |
---|
1371 | n/a | values = self.get_default_values() |
---|
1372 | n/a | |
---|
1373 | n/a | # Store the halves of the argument list as attributes for the |
---|
1374 | n/a | # convenience of callbacks: |
---|
1375 | n/a | # rargs |
---|
1376 | n/a | # the rest of the command-line (the "r" stands for |
---|
1377 | n/a | # "remaining" or "right-hand") |
---|
1378 | n/a | # largs |
---|
1379 | n/a | # the leftover arguments -- ie. what's left after removing |
---|
1380 | n/a | # options and their arguments (the "l" stands for "leftover" |
---|
1381 | n/a | # or "left-hand") |
---|
1382 | n/a | self.rargs = rargs |
---|
1383 | n/a | self.largs = largs = [] |
---|
1384 | n/a | self.values = values |
---|
1385 | n/a | |
---|
1386 | n/a | try: |
---|
1387 | n/a | stop = self._process_args(largs, rargs, values) |
---|
1388 | n/a | except (BadOptionError, OptionValueError) as err: |
---|
1389 | n/a | self.error(str(err)) |
---|
1390 | n/a | |
---|
1391 | n/a | args = largs + rargs |
---|
1392 | n/a | return self.check_values(values, args) |
---|
1393 | n/a | |
---|
1394 | n/a | def check_values(self, values, args): |
---|
1395 | n/a | """ |
---|
1396 | n/a | check_values(values : Values, args : [string]) |
---|
1397 | n/a | -> (values : Values, args : [string]) |
---|
1398 | n/a | |
---|
1399 | n/a | Check that the supplied option values and leftover arguments are |
---|
1400 | n/a | valid. Returns the option values and leftover arguments |
---|
1401 | n/a | (possibly adjusted, possibly completely new -- whatever you |
---|
1402 | n/a | like). Default implementation just returns the passed-in |
---|
1403 | n/a | values; subclasses may override as desired. |
---|
1404 | n/a | """ |
---|
1405 | n/a | return (values, args) |
---|
1406 | n/a | |
---|
1407 | n/a | def _process_args(self, largs, rargs, values): |
---|
1408 | n/a | """_process_args(largs : [string], |
---|
1409 | n/a | rargs : [string], |
---|
1410 | n/a | values : Values) |
---|
1411 | n/a | |
---|
1412 | n/a | Process command-line arguments and populate 'values', consuming |
---|
1413 | n/a | options and arguments from 'rargs'. If 'allow_interspersed_args' is |
---|
1414 | n/a | false, stop at the first non-option argument. If true, accumulate any |
---|
1415 | n/a | interspersed non-option arguments in 'largs'. |
---|
1416 | n/a | """ |
---|
1417 | n/a | while rargs: |
---|
1418 | n/a | arg = rargs[0] |
---|
1419 | n/a | # We handle bare "--" explicitly, and bare "-" is handled by the |
---|
1420 | n/a | # standard arg handler since the short arg case ensures that the |
---|
1421 | n/a | # len of the opt string is greater than 1. |
---|
1422 | n/a | if arg == "--": |
---|
1423 | n/a | del rargs[0] |
---|
1424 | n/a | return |
---|
1425 | n/a | elif arg[0:2] == "--": |
---|
1426 | n/a | # process a single long option (possibly with value(s)) |
---|
1427 | n/a | self._process_long_opt(rargs, values) |
---|
1428 | n/a | elif arg[:1] == "-" and len(arg) > 1: |
---|
1429 | n/a | # process a cluster of short options (possibly with |
---|
1430 | n/a | # value(s) for the last one only) |
---|
1431 | n/a | self._process_short_opts(rargs, values) |
---|
1432 | n/a | elif self.allow_interspersed_args: |
---|
1433 | n/a | largs.append(arg) |
---|
1434 | n/a | del rargs[0] |
---|
1435 | n/a | else: |
---|
1436 | n/a | return # stop now, leave this arg in rargs |
---|
1437 | n/a | |
---|
1438 | n/a | # Say this is the original argument list: |
---|
1439 | n/a | # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] |
---|
1440 | n/a | # ^ |
---|
1441 | n/a | # (we are about to process arg(i)). |
---|
1442 | n/a | # |
---|
1443 | n/a | # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of |
---|
1444 | n/a | # [arg0, ..., arg(i-1)] (any options and their arguments will have |
---|
1445 | n/a | # been removed from largs). |
---|
1446 | n/a | # |
---|
1447 | n/a | # The while loop will usually consume 1 or more arguments per pass. |
---|
1448 | n/a | # If it consumes 1 (eg. arg is an option that takes no arguments), |
---|
1449 | n/a | # then after _process_arg() is done the situation is: |
---|
1450 | n/a | # |
---|
1451 | n/a | # largs = subset of [arg0, ..., arg(i)] |
---|
1452 | n/a | # rargs = [arg(i+1), ..., arg(N-1)] |
---|
1453 | n/a | # |
---|
1454 | n/a | # If allow_interspersed_args is false, largs will always be |
---|
1455 | n/a | # *empty* -- still a subset of [arg0, ..., arg(i-1)], but |
---|
1456 | n/a | # not a very interesting subset! |
---|
1457 | n/a | |
---|
1458 | n/a | def _match_long_opt(self, opt): |
---|
1459 | n/a | """_match_long_opt(opt : string) -> string |
---|
1460 | n/a | |
---|
1461 | n/a | Determine which long option string 'opt' matches, ie. which one |
---|
1462 | n/a | it is an unambiguous abbreviation for. Raises BadOptionError if |
---|
1463 | n/a | 'opt' doesn't unambiguously match any long option string. |
---|
1464 | n/a | """ |
---|
1465 | n/a | return _match_abbrev(opt, self._long_opt) |
---|
1466 | n/a | |
---|
1467 | n/a | def _process_long_opt(self, rargs, values): |
---|
1468 | n/a | arg = rargs.pop(0) |
---|
1469 | n/a | |
---|
1470 | n/a | # Value explicitly attached to arg? Pretend it's the next |
---|
1471 | n/a | # argument. |
---|
1472 | n/a | if "=" in arg: |
---|
1473 | n/a | (opt, next_arg) = arg.split("=", 1) |
---|
1474 | n/a | rargs.insert(0, next_arg) |
---|
1475 | n/a | had_explicit_value = True |
---|
1476 | n/a | else: |
---|
1477 | n/a | opt = arg |
---|
1478 | n/a | had_explicit_value = False |
---|
1479 | n/a | |
---|
1480 | n/a | opt = self._match_long_opt(opt) |
---|
1481 | n/a | option = self._long_opt[opt] |
---|
1482 | n/a | if option.takes_value(): |
---|
1483 | n/a | nargs = option.nargs |
---|
1484 | n/a | if len(rargs) < nargs: |
---|
1485 | n/a | self.error(ngettext( |
---|
1486 | n/a | "%(option)s option requires %(number)d argument", |
---|
1487 | n/a | "%(option)s option requires %(number)d arguments", |
---|
1488 | n/a | nargs) % {"option": opt, "number": nargs}) |
---|
1489 | n/a | elif nargs == 1: |
---|
1490 | n/a | value = rargs.pop(0) |
---|
1491 | n/a | else: |
---|
1492 | n/a | value = tuple(rargs[0:nargs]) |
---|
1493 | n/a | del rargs[0:nargs] |
---|
1494 | n/a | |
---|
1495 | n/a | elif had_explicit_value: |
---|
1496 | n/a | self.error(_("%s option does not take a value") % opt) |
---|
1497 | n/a | |
---|
1498 | n/a | else: |
---|
1499 | n/a | value = None |
---|
1500 | n/a | |
---|
1501 | n/a | option.process(opt, value, values, self) |
---|
1502 | n/a | |
---|
1503 | n/a | def _process_short_opts(self, rargs, values): |
---|
1504 | n/a | arg = rargs.pop(0) |
---|
1505 | n/a | stop = False |
---|
1506 | n/a | i = 1 |
---|
1507 | n/a | for ch in arg[1:]: |
---|
1508 | n/a | opt = "-" + ch |
---|
1509 | n/a | option = self._short_opt.get(opt) |
---|
1510 | n/a | i += 1 # we have consumed a character |
---|
1511 | n/a | |
---|
1512 | n/a | if not option: |
---|
1513 | n/a | raise BadOptionError(opt) |
---|
1514 | n/a | if option.takes_value(): |
---|
1515 | n/a | # Any characters left in arg? Pretend they're the |
---|
1516 | n/a | # next arg, and stop consuming characters of arg. |
---|
1517 | n/a | if i < len(arg): |
---|
1518 | n/a | rargs.insert(0, arg[i:]) |
---|
1519 | n/a | stop = True |
---|
1520 | n/a | |
---|
1521 | n/a | nargs = option.nargs |
---|
1522 | n/a | if len(rargs) < nargs: |
---|
1523 | n/a | self.error(ngettext( |
---|
1524 | n/a | "%(option)s option requires %(number)d argument", |
---|
1525 | n/a | "%(option)s option requires %(number)d arguments", |
---|
1526 | n/a | nargs) % {"option": opt, "number": nargs}) |
---|
1527 | n/a | elif nargs == 1: |
---|
1528 | n/a | value = rargs.pop(0) |
---|
1529 | n/a | else: |
---|
1530 | n/a | value = tuple(rargs[0:nargs]) |
---|
1531 | n/a | del rargs[0:nargs] |
---|
1532 | n/a | |
---|
1533 | n/a | else: # option doesn't take a value |
---|
1534 | n/a | value = None |
---|
1535 | n/a | |
---|
1536 | n/a | option.process(opt, value, values, self) |
---|
1537 | n/a | |
---|
1538 | n/a | if stop: |
---|
1539 | n/a | break |
---|
1540 | n/a | |
---|
1541 | n/a | |
---|
1542 | n/a | # -- Feedback methods ---------------------------------------------- |
---|
1543 | n/a | |
---|
1544 | n/a | def get_prog_name(self): |
---|
1545 | n/a | if self.prog is None: |
---|
1546 | n/a | return os.path.basename(sys.argv[0]) |
---|
1547 | n/a | else: |
---|
1548 | n/a | return self.prog |
---|
1549 | n/a | |
---|
1550 | n/a | def expand_prog_name(self, s): |
---|
1551 | n/a | return s.replace("%prog", self.get_prog_name()) |
---|
1552 | n/a | |
---|
1553 | n/a | def get_description(self): |
---|
1554 | n/a | return self.expand_prog_name(self.description) |
---|
1555 | n/a | |
---|
1556 | n/a | def exit(self, status=0, msg=None): |
---|
1557 | n/a | if msg: |
---|
1558 | n/a | sys.stderr.write(msg) |
---|
1559 | n/a | sys.exit(status) |
---|
1560 | n/a | |
---|
1561 | n/a | def error(self, msg): |
---|
1562 | n/a | """error(msg : string) |
---|
1563 | n/a | |
---|
1564 | n/a | Print a usage message incorporating 'msg' to stderr and exit. |
---|
1565 | n/a | If you override this in a subclass, it should not return -- it |
---|
1566 | n/a | should either exit or raise an exception. |
---|
1567 | n/a | """ |
---|
1568 | n/a | self.print_usage(sys.stderr) |
---|
1569 | n/a | self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg)) |
---|
1570 | n/a | |
---|
1571 | n/a | def get_usage(self): |
---|
1572 | n/a | if self.usage: |
---|
1573 | n/a | return self.formatter.format_usage( |
---|
1574 | n/a | self.expand_prog_name(self.usage)) |
---|
1575 | n/a | else: |
---|
1576 | n/a | return "" |
---|
1577 | n/a | |
---|
1578 | n/a | def print_usage(self, file=None): |
---|
1579 | n/a | """print_usage(file : file = stdout) |
---|
1580 | n/a | |
---|
1581 | n/a | Print the usage message for the current program (self.usage) to |
---|
1582 | n/a | 'file' (default stdout). Any occurrence of the string "%prog" in |
---|
1583 | n/a | self.usage is replaced with the name of the current program |
---|
1584 | n/a | (basename of sys.argv[0]). Does nothing if self.usage is empty |
---|
1585 | n/a | or not defined. |
---|
1586 | n/a | """ |
---|
1587 | n/a | if self.usage: |
---|
1588 | n/a | print(self.get_usage(), file=file) |
---|
1589 | n/a | |
---|
1590 | n/a | def get_version(self): |
---|
1591 | n/a | if self.version: |
---|
1592 | n/a | return self.expand_prog_name(self.version) |
---|
1593 | n/a | else: |
---|
1594 | n/a | return "" |
---|
1595 | n/a | |
---|
1596 | n/a | def print_version(self, file=None): |
---|
1597 | n/a | """print_version(file : file = stdout) |
---|
1598 | n/a | |
---|
1599 | n/a | Print the version message for this program (self.version) to |
---|
1600 | n/a | 'file' (default stdout). As with print_usage(), any occurrence |
---|
1601 | n/a | of "%prog" in self.version is replaced by the current program's |
---|
1602 | n/a | name. Does nothing if self.version is empty or undefined. |
---|
1603 | n/a | """ |
---|
1604 | n/a | if self.version: |
---|
1605 | n/a | print(self.get_version(), file=file) |
---|
1606 | n/a | |
---|
1607 | n/a | def format_option_help(self, formatter=None): |
---|
1608 | n/a | if formatter is None: |
---|
1609 | n/a | formatter = self.formatter |
---|
1610 | n/a | formatter.store_option_strings(self) |
---|
1611 | n/a | result = [] |
---|
1612 | n/a | result.append(formatter.format_heading(_("Options"))) |
---|
1613 | n/a | formatter.indent() |
---|
1614 | n/a | if self.option_list: |
---|
1615 | n/a | result.append(OptionContainer.format_option_help(self, formatter)) |
---|
1616 | n/a | result.append("\n") |
---|
1617 | n/a | for group in self.option_groups: |
---|
1618 | n/a | result.append(group.format_help(formatter)) |
---|
1619 | n/a | result.append("\n") |
---|
1620 | n/a | formatter.dedent() |
---|
1621 | n/a | # Drop the last "\n", or the header if no options or option groups: |
---|
1622 | n/a | return "".join(result[:-1]) |
---|
1623 | n/a | |
---|
1624 | n/a | def format_epilog(self, formatter): |
---|
1625 | n/a | return formatter.format_epilog(self.epilog) |
---|
1626 | n/a | |
---|
1627 | n/a | def format_help(self, formatter=None): |
---|
1628 | n/a | if formatter is None: |
---|
1629 | n/a | formatter = self.formatter |
---|
1630 | n/a | result = [] |
---|
1631 | n/a | if self.usage: |
---|
1632 | n/a | result.append(self.get_usage() + "\n") |
---|
1633 | n/a | if self.description: |
---|
1634 | n/a | result.append(self.format_description(formatter) + "\n") |
---|
1635 | n/a | result.append(self.format_option_help(formatter)) |
---|
1636 | n/a | result.append(self.format_epilog(formatter)) |
---|
1637 | n/a | return "".join(result) |
---|
1638 | n/a | |
---|
1639 | n/a | def print_help(self, file=None): |
---|
1640 | n/a | """print_help(file : file = stdout) |
---|
1641 | n/a | |
---|
1642 | n/a | Print an extended help message, listing all options and any |
---|
1643 | n/a | help text provided with them, to 'file' (default stdout). |
---|
1644 | n/a | """ |
---|
1645 | n/a | if file is None: |
---|
1646 | n/a | file = sys.stdout |
---|
1647 | n/a | file.write(self.format_help()) |
---|
1648 | n/a | |
---|
1649 | n/a | # class OptionParser |
---|
1650 | n/a | |
---|
1651 | n/a | |
---|
1652 | n/a | def _match_abbrev(s, wordmap): |
---|
1653 | n/a | """_match_abbrev(s : string, wordmap : {string : Option}) -> string |
---|
1654 | n/a | |
---|
1655 | n/a | Return the string key in 'wordmap' for which 's' is an unambiguous |
---|
1656 | n/a | abbreviation. If 's' is found to be ambiguous or doesn't match any of |
---|
1657 | n/a | 'words', raise BadOptionError. |
---|
1658 | n/a | """ |
---|
1659 | n/a | # Is there an exact match? |
---|
1660 | n/a | if s in wordmap: |
---|
1661 | n/a | return s |
---|
1662 | n/a | else: |
---|
1663 | n/a | # Isolate all words with s as a prefix. |
---|
1664 | n/a | possibilities = [word for word in wordmap.keys() |
---|
1665 | n/a | if word.startswith(s)] |
---|
1666 | n/a | # No exact match, so there had better be just one possibility. |
---|
1667 | n/a | if len(possibilities) == 1: |
---|
1668 | n/a | return possibilities[0] |
---|
1669 | n/a | elif not possibilities: |
---|
1670 | n/a | raise BadOptionError(s) |
---|
1671 | n/a | else: |
---|
1672 | n/a | # More than one possible completion: ambiguous prefix. |
---|
1673 | n/a | possibilities.sort() |
---|
1674 | n/a | raise AmbiguousOptionError(s, possibilities) |
---|
1675 | n/a | |
---|
1676 | n/a | |
---|
1677 | n/a | # Some day, there might be many Option classes. As of Optik 1.3, the |
---|
1678 | n/a | # preferred way to instantiate Options is indirectly, via make_option(), |
---|
1679 | n/a | # which will become a factory function when there are many Option |
---|
1680 | n/a | # classes. |
---|
1681 | n/a | make_option = Option |
---|