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