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