1"""optik.option_parser 2 3Provides the OptionParser and Values classes. 4""" 5 6# Copyright (c) 2001-2006 Gregory P. Ward. All rights reserved. 7# See the README.txt distributed with Optik for licensing terms. 8 9import sys, os 10import types 11from optik.option import Option, NO_DEFAULT, _repr 12from optik.help import IndentedHelpFormatter 13from optik.errors import gettext as _, \ 14 OptionConflictError, BadOptionError, OptionValueError, \ 15 AmbiguousOptionError 16 17__revision__ = "$Id: option_parser.py 527 2006-07-23 15:21:30Z greg $" 18 19__all__ = ['SUPPRESS_HELP', 'SUPPRESS_USAGE', 20 'Values', 'OptionContainer', 'OptionGroup', 'OptionParser'] 21 22 23SUPPRESS_HELP = "SUPPRESS"+"HELP" 24SUPPRESS_USAGE = "SUPPRESS"+"USAGE" 25 26# For compatibility with Python 2.2 27try: 28 True, False 29except NameError: 30 (True, False) = (1, 0) 31 32def isbasestring(x): 33 return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType) 34 35class Values: 36 37 def __init__(self, defaults=None): 38 if defaults: 39 for (attr, val) in defaults.items(): 40 setattr(self, attr, val) 41 42 def __str__(self): 43 return str(self.__dict__) 44 45 __repr__ = _repr 46 47 def __cmp__(self, other): 48 if isinstance(other, Values): 49 return cmp(self.__dict__, other.__dict__) 50 elif isinstance(other, types.DictType): 51 return cmp(self.__dict__, other) 52 else: 53 return -1 54 55 def _update_careful(self, dict): 56 """ 57 Update the option values from an arbitrary dictionary, but only 58 use keys from dict that already have a corresponding attribute 59 in self. Any keys in dict without a corresponding attribute 60 are silently ignored. 61 """ 62 for attr in dir(self): 63 if dict.has_key(attr): 64 dval = dict[attr] 65 if dval is not None: 66 setattr(self, attr, dval) 67 68 def _update_loose(self, dict): 69 """ 70 Update the option values from an arbitrary dictionary, 71 using all keys from the dictionary regardless of whether 72 they have a corresponding attribute in self or not. 73 """ 74 self.__dict__.update(dict) 75 76 def _update(self, dict, mode): 77 if mode == "careful": 78 self._update_careful(dict) 79 elif mode == "loose": 80 self._update_loose(dict) 81 else: 82 raise ValueError, "invalid update mode: %r" % mode 83 84 def read_module(self, modname, mode="careful"): 85 __import__(modname) 86 mod = sys.modules[modname] 87 self._update(vars(mod), mode) 88 89 def read_file(self, filename, mode="careful"): 90 vars = {} 91 execfile(filename, vars) 92 self._update(vars, mode) 93 94 def ensure_value(self, attr, value): 95 if not hasattr(self, attr) or getattr(self, attr) is None: 96 setattr(self, attr, value) 97 return getattr(self, attr) 98 99 100class OptionContainer: 101 102 """ 103 Abstract base class. 104 105 Class attributes: 106 standard_option_list : [Option] 107 list of standard options that will be accepted by all instances 108 of this parser class (intended to be overridden by subclasses). 109 110 Instance attributes: 111 option_list : [Option] 112 the list of Option objects contained by this OptionContainer 113 _short_opt : { string : Option } 114 dictionary mapping short option strings, eg. "-f" or "-X", 115 to the Option instances that implement them. If an Option 116 has multiple short option strings, it will appears in this 117 dictionary multiple times. [1] 118 _long_opt : { string : Option } 119 dictionary mapping long option strings, eg. "--file" or 120 "--exclude", to the Option instances that implement them. 121 Again, a given Option can occur multiple times in this 122 dictionary. [1] 123 defaults : { string : any } 124 dictionary mapping option destination names to default 125 values for each destination [1] 126 127 [1] These mappings are common to (shared by) all components of the 128 controlling OptionParser, where they are initially created. 129 130 """ 131 132 def __init__(self, option_class, conflict_handler, description): 133 # Initialize the option list and related data structures. 134 # This method must be provided by subclasses, and it must 135 # initialize at least the following instance attributes: 136 # option_list, _short_opt, _long_opt, defaults. 137 self._create_option_list() 138 139 self.option_class = option_class 140 self.set_conflict_handler(conflict_handler) 141 self.set_description(description) 142 143 def _create_option_mappings(self): 144 # For use by OptionParser constructor -- create the master 145 # option mappings used by this OptionParser and all 146 # OptionGroups that it owns. 147 self._short_opt = {} # single letter -> Option instance 148 self._long_opt = {} # long option -> Option instance 149 self.defaults = {} # maps option dest -> default value 150 151 152 def _share_option_mappings(self, parser): 153 # For use by OptionGroup constructor -- use shared option 154 # mappings from the OptionParser that owns this OptionGroup. 155 self._short_opt = parser._short_opt 156 self._long_opt = parser._long_opt 157 self.defaults = parser.defaults 158 159 def set_conflict_handler(self, handler): 160 if handler not in ("error", "resolve"): 161 raise ValueError, "invalid conflict_resolution value %r" % handler 162 self.conflict_handler = handler 163 164 def set_description(self, description): 165 self.description = description 166 167 def get_description(self): 168 return self.description 169 170 171 def destroy(self): 172 """see OptionParser.destroy().""" 173 del self._short_opt 174 del self._long_opt 175 del self.defaults 176 177 178 # -- Option-adding methods ----------------------------------------- 179 180 def _check_conflict(self, option): 181 conflict_opts = [] 182 for opt in option._short_opts: 183 if self._short_opt.has_key(opt): 184 conflict_opts.append((opt, self._short_opt[opt])) 185 for opt in option._long_opts: 186 if self._long_opt.has_key(opt): 187 conflict_opts.append((opt, self._long_opt[opt])) 188 189 if conflict_opts: 190 handler = self.conflict_handler 191 if handler == "error": 192 raise OptionConflictError( 193 "conflicting option string(s): %s" 194 % ", ".join([co[0] for co in conflict_opts]), 195 option) 196 elif handler == "resolve": 197 for (opt, c_option) in conflict_opts: 198 if opt.startswith("--"): 199 c_option._long_opts.remove(opt) 200 del self._long_opt[opt] 201 else: 202 c_option._short_opts.remove(opt) 203 del self._short_opt[opt] 204 if not (c_option._short_opts or c_option._long_opts): 205 c_option.container.option_list.remove(c_option) 206 207 def add_option(self, *args, **kwargs): 208 """add_option(Option) 209 add_option(opt_str, ..., kwarg=val, ...) 210 """ 211 if type(args[0]) is types.StringType: 212 option = self.option_class(*args, **kwargs) 213 elif len(args) == 1 and not kwargs: 214 option = args[0] 215 if not isinstance(option, Option): 216 raise TypeError, "not an Option instance: %r" % option 217 else: 218 raise TypeError, "invalid arguments" 219 220 self._check_conflict(option) 221 222 self.option_list.append(option) 223 option.container = self 224 for opt in option._short_opts: 225 self._short_opt[opt] = option 226 for opt in option._long_opts: 227 self._long_opt[opt] = option 228 229 if option.dest is not None: # option has a dest, we need a default 230 if option.default is not NO_DEFAULT: 231 self.defaults[option.dest] = option.default 232 elif not self.defaults.has_key(option.dest): 233 self.defaults[option.dest] = None 234 235 return option 236 237 def add_options(self, option_list): 238 for option in option_list: 239 self.add_option(option) 240 241 # -- Option query/removal methods ---------------------------------- 242 243 def get_option(self, opt_str): 244 return (self._short_opt.get(opt_str) or 245 self._long_opt.get(opt_str)) 246 247 def has_option(self, opt_str): 248 return (self._short_opt.has_key(opt_str) or 249 self._long_opt.has_key(opt_str)) 250 251 def remove_option(self, opt_str): 252 option = self._short_opt.get(opt_str) 253 if option is None: 254 option = self._long_opt.get(opt_str) 255 if option is None: 256 raise ValueError("no such option %r" % opt_str) 257 258 for opt in option._short_opts: 259 del self._short_opt[opt] 260 for opt in option._long_opts: 261 del self._long_opt[opt] 262 option.container.option_list.remove(option) 263 264 265 # -- Help-formatting methods --------------------------------------- 266 267 def format_option_help(self, formatter): 268 if not self.option_list: 269 return "" 270 result = [] 271 for option in self.option_list: 272 if not option.help is SUPPRESS_HELP: 273 result.append(formatter.format_option(option)) 274 return "".join(result) 275 276 def format_description(self, formatter): 277 return formatter.format_description(self.get_description()) 278 279 def format_help(self, formatter): 280 result = [] 281 if self.description: 282 result.append(self.format_description(formatter)) 283 if self.option_list: 284 result.append(self.format_option_help(formatter)) 285 return "\n".join(result) 286 287 288class OptionGroup (OptionContainer): 289 290 def __init__(self, parser, title, description=None): 291 self.parser = parser 292 OptionContainer.__init__( 293 self, parser.option_class, parser.conflict_handler, description) 294 self.title = title 295 296 def _create_option_list(self): 297 self.option_list = [] 298 self._share_option_mappings(self.parser) 299 300 def set_title(self, title): 301 self.title = title 302 303 def destroy(self): 304 """see OptionParser.destroy().""" 305 OptionContainer.destroy(self) 306 del self.option_list 307 308 # -- Help-formatting methods --------------------------------------- 309 310 def format_help(self, formatter): 311 result = formatter.format_heading(self.title) 312 formatter.indent() 313 result += OptionContainer.format_help(self, formatter) 314 formatter.dedent() 315 return result 316 317 318class OptionParser (OptionContainer): 319 320 """ 321 Class attributes: 322 standard_option_list : [Option] 323 list of standard options that will be accepted by all instances 324 of this parser class (intended to be overridden by subclasses). 325 326 Instance attributes: 327 usage : string 328 a usage string for your program. Before it is displayed 329 to the user, "%prog" will be expanded to the name of 330 your program (self.prog or os.path.basename(sys.argv[0])). 331 prog : string 332 the name of the current program (to override 333 os.path.basename(sys.argv[0])). 334 epilog : string 335 paragraph of help text to print after option help 336 337 option_groups : [OptionGroup] 338 list of option groups in this parser (option groups are 339 irrelevant for parsing the command-line, but very useful 340 for generating help) 341 342 allow_interspersed_args : bool = true 343 if true, positional arguments may be interspersed with options. 344 Assuming -a and -b each take a single argument, the command-line 345 -ablah foo bar -bboo baz 346 will be interpreted the same as 347 -ablah -bboo -- foo bar baz 348 If this flag were false, that command line would be interpreted as 349 -ablah -- foo bar -bboo baz 350 -- ie. we stop processing options as soon as we see the first 351 non-option argument. (This is the tradition followed by 352 Python's getopt module, Perl's Getopt::Std, and other argument- 353 parsing libraries, but it is generally annoying to users.) 354 355 process_default_values : bool = true 356 if true, option default values are processed similarly to option 357 values from the command line: that is, they are passed to the 358 type-checking function for the option's type (as long as the 359 default value is a string). (This really only matters if you 360 have defined custom types; see SF bug #955889.) Set it to false 361 to restore the behaviour of Optik 1.4.1 and earlier. 362 363 rargs : [string] 364 the argument list currently being parsed. Only set when 365 parse_args() is active, and continually trimmed down as 366 we consume arguments. Mainly there for the benefit of 367 callback options. 368 largs : [string] 369 the list of leftover arguments that we have skipped while 370 parsing options. If allow_interspersed_args is false, this 371 list is always empty. 372 values : Values 373 the set of option values currently being accumulated. Only 374 set when parse_args() is active. Also mainly for callbacks. 375 376 Because of the 'rargs', 'largs', and 'values' attributes, 377 OptionParser is not thread-safe. If, for some perverse reason, you 378 need to parse command-line arguments simultaneously in different 379 threads, use different OptionParser instances. 380 381 """ 382 383 standard_option_list = [] 384 385 def __init__(self, 386 usage=None, 387 option_list=None, 388 option_class=Option, 389 version=None, 390 conflict_handler="error", 391 description=None, 392 formatter=None, 393 add_help_option=True, 394 prog=None, 395 epilog=None): 396 OptionContainer.__init__( 397 self, option_class, conflict_handler, description) 398 self.set_usage(usage) 399 self.prog = prog 400 self.version = version 401 self.allow_interspersed_args = True 402 self.process_default_values = True 403 if formatter is None: 404 formatter = IndentedHelpFormatter() 405 self.formatter = formatter 406 self.formatter.set_parser(self) 407 self.epilog = epilog 408 409 # Populate the option list; initial sources are the 410 # standard_option_list class attribute, the 'option_list' 411 # argument, and (if applicable) the _add_version_option() and 412 # _add_help_option() methods. 413 self._populate_option_list(option_list, 414 add_help=add_help_option) 415 416 self._init_parsing_state() 417 418 419 def destroy(self): 420 """ 421 Declare that you are done with this OptionParser. This cleans up 422 reference cycles so the OptionParser (and all objects referenced by 423 it) can be garbage-collected promptly. After calling destroy(), the 424 OptionParser is unusable. 425 """ 426 OptionContainer.destroy(self) 427 for group in self.option_groups: 428 group.destroy() 429 del self.option_list 430 del self.option_groups 431 del self.formatter 432 433 434 # -- Private methods ----------------------------------------------- 435 # (used by our or OptionContainer's constructor) 436 437 def _create_option_list(self): 438 self.option_list = [] 439 self.option_groups = [] 440 self._create_option_mappings() 441 442 def _add_help_option(self): 443 self.add_option("-h", "--help", 444 action="help", 445 help=_("show this help message and exit")) 446 447 def _add_version_option(self): 448 self.add_option("--version", 449 action="version", 450 help=_("show program's version number and exit")) 451 452 def _populate_option_list(self, option_list, add_help=True): 453 if self.standard_option_list: 454 self.add_options(self.standard_option_list) 455 if option_list: 456 self.add_options(option_list) 457 if self.version: 458 self._add_version_option() 459 if add_help: 460 self._add_help_option() 461 462 def _init_parsing_state(self): 463 # These are set in parse_args() for the convenience of callbacks. 464 self.rargs = None 465 self.largs = None 466 self.values = None 467 468 469 # -- Simple modifier methods --------------------------------------- 470 471 def set_usage(self, usage): 472 if usage is None: 473 self.usage = _("%prog [options]") 474 elif usage is SUPPRESS_USAGE: 475 self.usage = None 476 # For backwards compatibility with Optik 1.3 and earlier. 477 elif usage.lower().startswith("usage: "): 478 self.usage = usage[7:] 479 else: 480 self.usage = usage 481 482 def enable_interspersed_args(self): 483 self.allow_interspersed_args = True 484 485 def disable_interspersed_args(self): 486 self.allow_interspersed_args = False 487 488 def set_process_default_values(self, process): 489 self.process_default_values = process 490 491 def set_default(self, dest, value): 492 self.defaults[dest] = value 493 494 def set_defaults(self, **kwargs): 495 self.defaults.update(kwargs) 496 497 def _get_all_options(self): 498 options = self.option_list[:] 499 for group in self.option_groups: 500 options.extend(group.option_list) 501 return options 502 503 def get_default_values(self): 504 if not self.process_default_values: 505 # Old, pre-Optik 1.5 behaviour. 506 return Values(self.defaults) 507 508 defaults = self.defaults.copy() 509 for option in self._get_all_options(): 510 default = defaults.get(option.dest) 511 if isbasestring(default): 512 opt_str = option.get_opt_string() 513 defaults[option.dest] = option.check_value(opt_str, default) 514 515 return Values(defaults) 516 517 518 # -- OptionGroup methods ------------------------------------------- 519 520 def add_option_group(self, *args, **kwargs): 521 # XXX lots of overlap with OptionContainer.add_option() 522 if type(args[0]) is types.StringType: 523 group = OptionGroup(self, *args, **kwargs) 524 elif len(args) == 1 and not kwargs: 525 group = args[0] 526 if not isinstance(group, OptionGroup): 527 raise TypeError, "not an OptionGroup instance: %r" % group 528 if group.parser is not self: 529 raise ValueError, "invalid OptionGroup (wrong parser)" 530 else: 531 raise TypeError, "invalid arguments" 532 533 self.option_groups.append(group) 534 return group 535 536 def get_option_group(self, opt_str): 537 option = (self._short_opt.get(opt_str) or 538 self._long_opt.get(opt_str)) 539 if option and option.container is not self: 540 return option.container 541 return None 542 543 544 # -- Option-parsing methods ---------------------------------------- 545 546 def _get_args(self, args): 547 if args is None: 548 return sys.argv[1:] 549 else: 550 return args[:] # don't modify caller's list 551 552 def parse_args(self, args=None, values=None): 553 """ 554 parse_args(args : [string] = sys.argv[1:], 555 values : Values = None) 556 -> (values : Values, args : [string]) 557 558 Parse the command-line options found in 'args' (default: 559 sys.argv[1:]). Any errors result in a call to 'error()', which 560 by default prints the usage message to stderr and calls 561 sys.exit() with an error message. On success returns a pair 562 (values, args) where 'values' is an Values instance (with all 563 your option values) and 'args' is the list of arguments left 564 over after parsing options. 565 """ 566 rargs = self._get_args(args) 567 if values is None: 568 values = self.get_default_values() 569 570 # Store the halves of the argument list as attributes for the 571 # convenience of callbacks: 572 # rargs 573 # the rest of the command-line (the "r" stands for 574 # "remaining" or "right-hand") 575 # largs 576 # the leftover arguments -- ie. what's left after removing 577 # options and their arguments (the "l" stands for "leftover" 578 # or "left-hand") 579 self.rargs = rargs 580 self.largs = largs = [] 581 self.values = values 582 583 try: 584 stop = self._process_args(largs, rargs, values) 585 except (BadOptionError, OptionValueError), err: 586 self.error(str(err)) 587 588 args = largs + rargs 589 return self.check_values(values, args) 590 591 def check_values(self, values, args): 592 """ 593 check_values(values : Values, args : [string]) 594 -> (values : Values, args : [string]) 595 596 Check that the supplied option values and leftover arguments are 597 valid. Returns the option values and leftover arguments 598 (possibly adjusted, possibly completely new -- whatever you 599 like). Default implementation just returns the passed-in 600 values; subclasses may override as desired. 601 """ 602 return (values, args) 603 604 def _process_args(self, largs, rargs, values): 605 """_process_args(largs : [string], 606 rargs : [string], 607 values : Values) 608 609 Process command-line arguments and populate 'values', consuming 610 options and arguments from 'rargs'. If 'allow_interspersed_args' is 611 false, stop at the first non-option argument. If true, accumulate any 612 interspersed non-option arguments in 'largs'. 613 """ 614 while rargs: 615 arg = rargs[0] 616 # We handle bare "--" explicitly, and bare "-" is handled by the 617 # standard arg handler since the short arg case ensures that the 618 # len of the opt string is greater than 1. 619 if arg == "--": 620 del rargs[0] 621 return 622 elif arg[0:2] == "--": 623 # process a single long option (possibly with value(s)) 624 self._process_long_opt(rargs, values) 625 elif arg[:1] == "-" and len(arg) > 1: 626 # process a cluster of short options (possibly with 627 # value(s) for the last one only) 628 self._process_short_opts(rargs, values) 629 elif self.allow_interspersed_args: 630 largs.append(arg) 631 del rargs[0] 632 else: 633 return # stop now, leave this arg in rargs 634 635 # Say this is the original argument list: 636 # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)] 637 # ^ 638 # (we are about to process arg(i)). 639 # 640 # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of 641 # [arg0, ..., arg(i-1)] (any options and their arguments will have 642 # been removed from largs). 643 # 644 # The while loop will usually consume 1 or more arguments per pass. 645 # If it consumes 1 (eg. arg is an option that takes no arguments), 646 # then after _process_arg() is done the situation is: 647 # 648 # largs = subset of [arg0, ..., arg(i)] 649 # rargs = [arg(i+1), ..., arg(N-1)] 650 # 651 # If allow_interspersed_args is false, largs will always be 652 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but 653 # not a very interesting subset! 654 655 def _match_long_opt(self, opt): 656 """_match_long_opt(opt : string) -> string 657 658 Determine which long option string 'opt' matches, ie. which one 659 it is an unambiguous abbrevation for. Raises BadOptionError if 660 'opt' doesn't unambiguously match any long option string. 661 """ 662 return _match_abbrev(opt, self._long_opt) 663 664 def _process_long_opt(self, rargs, values): 665 arg = rargs.pop(0) 666 667 # Value explicitly attached to arg? Pretend it's the next 668 # argument. 669 if "=" in arg: 670 (opt, next_arg) = arg.split("=", 1) 671 rargs.insert(0, next_arg) 672 had_explicit_value = True 673 else: 674 opt = arg 675 had_explicit_value = False 676 677 opt = self._match_long_opt(opt) 678 option = self._long_opt[opt] 679 if option.takes_value(): 680 nargs = option.nargs 681 if len(rargs) < nargs: 682 if nargs == 1: 683 self.error(_("%s option requires an argument") % opt) 684 else: 685 self.error(_("%s option requires %d arguments") 686 % (opt, nargs)) 687 elif nargs == 1: 688 value = rargs.pop(0) 689 else: 690 value = tuple(rargs[0:nargs]) 691 del rargs[0:nargs] 692 693 elif had_explicit_value: 694 self.error(_("%s option does not take a value") % opt) 695 696 else: 697 value = None 698 699 option.process(opt, value, values, self) 700 701 def _process_short_opts(self, rargs, values): 702 arg = rargs.pop(0) 703 stop = False 704 i = 1 705 for ch in arg[1:]: 706 opt = "-" + ch 707 option = self._short_opt.get(opt) 708 i += 1 # we have consumed a character 709 710 if not option: 711 raise BadOptionError(opt) 712 if option.takes_value(): 713 # Any characters left in arg? Pretend they're the 714 # next arg, and stop consuming characters of arg. 715 if i < len(arg): 716 rargs.insert(0, arg[i:]) 717 stop = True 718 719 nargs = option.nargs 720 if len(rargs) < nargs: 721 if nargs == 1: 722 self.error(_("%s option requires an argument") % opt) 723 else: 724 self.error(_("%s option requires %d arguments") 725 % (opt, nargs)) 726 elif nargs == 1: 727 value = rargs.pop(0) 728 else: 729 value = tuple(rargs[0:nargs]) 730 del rargs[0:nargs] 731 732 else: # option doesn't take a value 733 value = None 734 735 option.process(opt, value, values, self) 736 737 if stop: 738 break 739 740 741 # -- Feedback methods ---------------------------------------------- 742 743 def get_prog_name(self): 744 if self.prog is None: 745 return os.path.basename(sys.argv[0]) 746 else: 747 return self.prog 748 749 def expand_prog_name(self, s): 750 return s.replace("%prog", self.get_prog_name()) 751 752 def get_description(self): 753 return self.expand_prog_name(self.description) 754 755 def exit(self, status=0, msg=None): 756 if msg: 757 sys.stderr.write(msg) 758 sys.exit(status) 759 760 def error(self, msg): 761 """error(msg : string) 762 763 Print a usage message incorporating 'msg' to stderr and exit. 764 If you override this in a subclass, it should not return -- it 765 should either exit or raise an exception. 766 """ 767 self.print_usage(sys.stderr) 768 self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg)) 769 770 def get_usage(self): 771 if self.usage: 772 return self.formatter.format_usage( 773 self.expand_prog_name(self.usage)) 774 else: 775 return "" 776 777 def print_usage(self, file=None): 778 """print_usage(file : file = stdout) 779 780 Print the usage message for the current program (self.usage) to 781 'file' (default stdout). Any occurence of the string "%prog" in 782 self.usage is replaced with the name of the current program 783 (basename of sys.argv[0]). Does nothing if self.usage is empty 784 or not defined. 785 """ 786 if self.usage: 787 print >>file, self.get_usage() 788 789 def get_version(self): 790 if self.version: 791 return self.expand_prog_name(self.version) 792 else: 793 return "" 794 795 def print_version(self, file=None): 796 """print_version(file : file = stdout) 797 798 Print the version message for this program (self.version) to 799 'file' (default stdout). As with print_usage(), any occurence 800 of "%prog" in self.version is replaced by the current program's 801 name. Does nothing if self.version is empty or undefined. 802 """ 803 if self.version: 804 print >>file, self.get_version() 805 806 def format_option_help(self, formatter=None): 807 if formatter is None: 808 formatter = self.formatter 809 formatter.store_option_strings(self) 810 result = [] 811 result.append(formatter.format_heading(_("Options"))) 812 formatter.indent() 813 if self.option_list: 814 result.append(OptionContainer.format_option_help(self, formatter)) 815 result.append("\n") 816 for group in self.option_groups: 817 result.append(group.format_help(formatter)) 818 result.append("\n") 819 formatter.dedent() 820 # Drop the last "\n", or the header if no options or option groups: 821 return "".join(result[:-1]) 822 823 def format_epilog(self, formatter): 824 return formatter.format_epilog(self.epilog) 825 826 def format_help(self, formatter=None): 827 if formatter is None: 828 formatter = self.formatter 829 result = [] 830 if self.usage: 831 result.append(self.get_usage() + "\n") 832 if self.description: 833 result.append(self.format_description(formatter) + "\n") 834 result.append(self.format_option_help(formatter)) 835 result.append(self.format_epilog(formatter)) 836 return "".join(result) 837 838 # used by test suite 839 def _get_encoding(self, file): 840 encoding = getattr(file, "encoding", None) 841 if not encoding: 842 encoding = sys.getdefaultencoding() 843 return encoding 844 845 def print_help(self, file=None): 846 """print_help(file : file = stdout) 847 848 Print an extended help message, listing all options and any 849 help text provided with them, to 'file' (default stdout). 850 """ 851 if file is None: 852 file = sys.stdout 853 encoding = self._get_encoding(file) 854 file.write(self.format_help().encode(encoding, "replace")) 855 856# class OptionParser 857 858 859def _match_abbrev(s, wordmap): 860 """_match_abbrev(s : string, wordmap : {string : Option}) -> string 861 862 Return the string key in 'wordmap' for which 's' is an unambiguous 863 abbreviation. If 's' is found to be ambiguous or doesn't match any of 864 'words', raise BadOptionError. 865 """ 866 # Is there an exact match? 867 if wordmap.has_key(s): 868 return s 869 else: 870 # Isolate all words with s as a prefix. 871 possibilities = [word for word in wordmap.keys() 872 if word.startswith(s)] 873 # No exact match, so there had better be just one possibility. 874 if len(possibilities) == 1: 875 return possibilities[0] 876 elif not possibilities: 877 raise BadOptionError(s) 878 else: 879 # More than one possible completion: ambiguous prefix. 880 possibilities.sort() 881 raise AmbiguousOptionError(s, possibilities) 882