1# Author: Steven J. Bethard <steven.bethard@gmail.com>. 2 3"""Command-line parsing library 4 5This module is an optparse-inspired command-line parsing library that: 6 7 - handles both optional and positional arguments 8 - produces highly informative usage messages 9 - supports parsers that dispatch to sub-parsers 10 11The following is a simple usage example that sums integers from the 12command-line and writes the result to a file:: 13 14 parser = argparse.ArgumentParser( 15 description='sum the integers at the command line') 16 parser.add_argument( 17 'integers', metavar='int', nargs='+', type=int, 18 help='an integer to be summed') 19 parser.add_argument( 20 '--log', default=sys.stdout, type=argparse.FileType('w'), 21 help='the file where the sum should be written') 22 args = parser.parse_args() 23 args.log.write('%s' % sum(args.integers)) 24 args.log.close() 25 26The module contains the following public classes: 27 28 - ArgumentParser -- The main entry point for command-line parsing. As the 29 example above shows, the add_argument() method is used to populate 30 the parser with actions for optional and positional arguments. Then 31 the parse_args() method is invoked to convert the args at the 32 command-line into an object with attributes. 33 34 - ArgumentError -- The exception raised by ArgumentParser objects when 35 there are errors with the parser's actions. Errors raised while 36 parsing the command-line are caught by ArgumentParser and emitted 37 as command-line messages. 38 39 - FileType -- A factory for defining types of files to be created. As the 40 example above shows, instances of FileType are typically passed as 41 the type= argument of add_argument() calls. 42 43 - Action -- The base class for parser actions. Typically actions are 44 selected by passing strings like 'store_true' or 'append_const' to 45 the action= argument of add_argument(). However, for greater 46 customization of ArgumentParser actions, subclasses of Action may 47 be defined and passed as the action= argument. 48 49 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, 50 ArgumentDefaultsHelpFormatter -- Formatter classes which 51 may be passed as the formatter_class= argument to the 52 ArgumentParser constructor. HelpFormatter is the default, 53 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser 54 not to change the formatting for help text, and 55 ArgumentDefaultsHelpFormatter adds information about argument defaults 56 to the help. 57 58All other classes in this module are considered implementation details. 59(Also note that HelpFormatter and RawDescriptionHelpFormatter are only 60considered public as object names -- the API of the formatter objects is 61still considered an implementation detail.) 62""" 63 64__version__ = '1.1' 65__all__ = [ 66 'ArgumentParser', 67 'ArgumentError', 68 'ArgumentTypeError', 69 'FileType', 70 'HelpFormatter', 71 'ArgumentDefaultsHelpFormatter', 72 'RawDescriptionHelpFormatter', 73 'RawTextHelpFormatter', 74 'Namespace', 75 'Action', 76 'ONE_OR_MORE', 77 'OPTIONAL', 78 'PARSER', 79 'REMAINDER', 80 'SUPPRESS', 81 'ZERO_OR_MORE', 82] 83 84 85import collections as _collections 86import copy as _copy 87import os as _os 88import re as _re 89import sys as _sys 90import textwrap as _textwrap 91 92from gettext import gettext as _ 93 94 95def _callable(obj): 96 return hasattr(obj, '__call__') or hasattr(obj, '__bases__') 97 98 99SUPPRESS = '==SUPPRESS==' 100 101OPTIONAL = '?' 102ZERO_OR_MORE = '*' 103ONE_OR_MORE = '+' 104PARSER = 'A...' 105REMAINDER = '...' 106_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' 107 108# ============================= 109# Utility functions and classes 110# ============================= 111 112class _AttributeHolder(object): 113 """Abstract base class that provides __repr__. 114 115 The __repr__ method returns a string in the format:: 116 ClassName(attr=name, attr=name, ...) 117 The attributes are determined either by a class-level attribute, 118 '_kwarg_names', or by inspecting the instance __dict__. 119 """ 120 121 def __repr__(self): 122 type_name = type(self).__name__ 123 arg_strings = [] 124 for arg in self._get_args(): 125 arg_strings.append(repr(arg)) 126 for name, value in self._get_kwargs(): 127 arg_strings.append('%s=%r' % (name, value)) 128 return '%s(%s)' % (type_name, ', '.join(arg_strings)) 129 130 def _get_kwargs(self): 131 return sorted(self.__dict__.items()) 132 133 def _get_args(self): 134 return [] 135 136 137def _ensure_value(namespace, name, value): 138 if getattr(namespace, name, None) is None: 139 setattr(namespace, name, value) 140 return getattr(namespace, name) 141 142 143# =============== 144# Formatting Help 145# =============== 146 147class HelpFormatter(object): 148 """Formatter for generating usage messages and argument help strings. 149 150 Only the name of this class is considered a public API. All the methods 151 provided by the class are considered an implementation detail. 152 """ 153 154 def __init__(self, 155 prog, 156 indent_increment=2, 157 max_help_position=24, 158 width=None): 159 160 # default setting for width 161 if width is None: 162 try: 163 width = int(_os.environ['COLUMNS']) 164 except (KeyError, ValueError): 165 width = 80 166 width -= 2 167 168 self._prog = prog 169 self._indent_increment = indent_increment 170 self._max_help_position = max_help_position 171 self._max_help_position = min(max_help_position, 172 max(width - 20, indent_increment * 2)) 173 self._width = width 174 175 self._current_indent = 0 176 self._level = 0 177 self._action_max_length = 0 178 179 self._root_section = self._Section(self, None) 180 self._current_section = self._root_section 181 182 self._whitespace_matcher = _re.compile(r'\s+') 183 self._long_break_matcher = _re.compile(r'\n\n\n+') 184 185 # =============================== 186 # Section and indentation methods 187 # =============================== 188 def _indent(self): 189 self._current_indent += self._indent_increment 190 self._level += 1 191 192 def _dedent(self): 193 self._current_indent -= self._indent_increment 194 assert self._current_indent >= 0, 'Indent decreased below 0.' 195 self._level -= 1 196 197 class _Section(object): 198 199 def __init__(self, formatter, parent, heading=None): 200 self.formatter = formatter 201 self.parent = parent 202 self.heading = heading 203 self.items = [] 204 205 def format_help(self): 206 # format the indented section 207 if self.parent is not None: 208 self.formatter._indent() 209 join = self.formatter._join_parts 210 for func, args in self.items: 211 func(*args) 212 item_help = join([func(*args) for func, args in self.items]) 213 if self.parent is not None: 214 self.formatter._dedent() 215 216 # return nothing if the section was empty 217 if not item_help: 218 return '' 219 220 # add the heading if the section was non-empty 221 if self.heading is not SUPPRESS and self.heading is not None: 222 current_indent = self.formatter._current_indent 223 heading = '%*s%s:\n' % (current_indent, '', self.heading) 224 else: 225 heading = '' 226 227 # join the section-initial newline, the heading and the help 228 return join(['\n', heading, item_help, '\n']) 229 230 def _add_item(self, func, args): 231 self._current_section.items.append((func, args)) 232 233 # ======================== 234 # Message building methods 235 # ======================== 236 def start_section(self, heading): 237 self._indent() 238 section = self._Section(self, self._current_section, heading) 239 self._add_item(section.format_help, []) 240 self._current_section = section 241 242 def end_section(self): 243 self._current_section = self._current_section.parent 244 self._dedent() 245 246 def add_text(self, text): 247 if text is not SUPPRESS and text is not None: 248 self._add_item(self._format_text, [text]) 249 250 def add_usage(self, usage, actions, groups, prefix=None): 251 if usage is not SUPPRESS: 252 args = usage, actions, groups, prefix 253 self._add_item(self._format_usage, args) 254 255 def add_argument(self, action): 256 if action.help is not SUPPRESS: 257 258 # find all invocations 259 get_invocation = self._format_action_invocation 260 invocations = [get_invocation(action)] 261 for subaction in self._iter_indented_subactions(action): 262 invocations.append(get_invocation(subaction)) 263 264 # update the maximum item length 265 invocation_length = max([len(s) for s in invocations]) 266 action_length = invocation_length + self._current_indent 267 self._action_max_length = max(self._action_max_length, 268 action_length) 269 270 # add the item to the list 271 self._add_item(self._format_action, [action]) 272 273 def add_arguments(self, actions): 274 for action in actions: 275 self.add_argument(action) 276 277 # ======================= 278 # Help-formatting methods 279 # ======================= 280 def format_help(self): 281 help = self._root_section.format_help() 282 if help: 283 help = self._long_break_matcher.sub('\n\n', help) 284 help = help.strip('\n') + '\n' 285 return help 286 287 def _join_parts(self, part_strings): 288 return ''.join([part 289 for part in part_strings 290 if part and part is not SUPPRESS]) 291 292 def _format_usage(self, usage, actions, groups, prefix): 293 if prefix is None: 294 prefix = _('usage: ') 295 296 # if usage is specified, use that 297 if usage is not None: 298 usage = usage % dict(prog=self._prog) 299 300 # if no optionals or positionals are available, usage is just prog 301 elif usage is None and not actions: 302 usage = '%(prog)s' % dict(prog=self._prog) 303 304 # if optionals and positionals are available, calculate usage 305 elif usage is None: 306 prog = '%(prog)s' % dict(prog=self._prog) 307 308 # split optionals from positionals 309 optionals = [] 310 positionals = [] 311 for action in actions: 312 if action.option_strings: 313 optionals.append(action) 314 else: 315 positionals.append(action) 316 317 # build full usage string 318 format = self._format_actions_usage 319 action_usage = format(optionals + positionals, groups) 320 usage = ' '.join([s for s in [prog, action_usage] if s]) 321 322 # wrap the usage parts if it's too long 323 text_width = self._width - self._current_indent 324 if len(prefix) + len(usage) > text_width: 325 326 # break usage into wrappable parts 327 part_regexp = ( 328 r'\(.*?\)+(?=\s|$)|' 329 r'\[.*?\]+(?=\s|$)|' 330 r'\S+' 331 ) 332 opt_usage = format(optionals, groups) 333 pos_usage = format(positionals, groups) 334 opt_parts = _re.findall(part_regexp, opt_usage) 335 pos_parts = _re.findall(part_regexp, pos_usage) 336 assert ' '.join(opt_parts) == opt_usage 337 assert ' '.join(pos_parts) == pos_usage 338 339 # helper for wrapping lines 340 def get_lines(parts, indent, prefix=None): 341 lines = [] 342 line = [] 343 if prefix is not None: 344 line_len = len(prefix) - 1 345 else: 346 line_len = len(indent) - 1 347 for part in parts: 348 if line_len + 1 + len(part) > text_width and line: 349 lines.append(indent + ' '.join(line)) 350 line = [] 351 line_len = len(indent) - 1 352 line.append(part) 353 line_len += len(part) + 1 354 if line: 355 lines.append(indent + ' '.join(line)) 356 if prefix is not None: 357 lines[0] = lines[0][len(indent):] 358 return lines 359 360 # if prog is short, follow it with optionals or positionals 361 if len(prefix) + len(prog) <= 0.75 * text_width: 362 indent = ' ' * (len(prefix) + len(prog) + 1) 363 if opt_parts: 364 lines = get_lines([prog] + opt_parts, indent, prefix) 365 lines.extend(get_lines(pos_parts, indent)) 366 elif pos_parts: 367 lines = get_lines([prog] + pos_parts, indent, prefix) 368 else: 369 lines = [prog] 370 371 # if prog is long, put it on its own line 372 else: 373 indent = ' ' * len(prefix) 374 parts = opt_parts + pos_parts 375 lines = get_lines(parts, indent) 376 if len(lines) > 1: 377 lines = [] 378 lines.extend(get_lines(opt_parts, indent)) 379 lines.extend(get_lines(pos_parts, indent)) 380 lines = [prog] + lines 381 382 # join lines into usage 383 usage = '\n'.join(lines) 384 385 # prefix with 'usage:' 386 return '%s%s\n\n' % (prefix, usage) 387 388 def _format_actions_usage(self, actions, groups): 389 # find group indices and identify actions in groups 390 group_actions = set() 391 inserts = {} 392 for group in groups: 393 try: 394 start = actions.index(group._group_actions[0]) 395 except ValueError: 396 continue 397 else: 398 end = start + len(group._group_actions) 399 if actions[start:end] == group._group_actions: 400 for action in group._group_actions: 401 group_actions.add(action) 402 if not group.required: 403 if start in inserts: 404 inserts[start] += ' [' 405 else: 406 inserts[start] = '[' 407 inserts[end] = ']' 408 else: 409 if start in inserts: 410 inserts[start] += ' (' 411 else: 412 inserts[start] = '(' 413 inserts[end] = ')' 414 for i in range(start + 1, end): 415 inserts[i] = '|' 416 417 # collect all actions format strings 418 parts = [] 419 for i, action in enumerate(actions): 420 421 # suppressed arguments are marked with None 422 # remove | separators for suppressed arguments 423 if action.help is SUPPRESS: 424 parts.append(None) 425 if inserts.get(i) == '|': 426 inserts.pop(i) 427 elif inserts.get(i + 1) == '|': 428 inserts.pop(i + 1) 429 430 # produce all arg strings 431 elif not action.option_strings: 432 part = self._format_args(action, action.dest) 433 434 # if it's in a group, strip the outer [] 435 if action in group_actions: 436 if part[0] == '[' and part[-1] == ']': 437 part = part[1:-1] 438 439 # add the action string to the list 440 parts.append(part) 441 442 # produce the first way to invoke the option in brackets 443 else: 444 option_string = action.option_strings[0] 445 446 # if the Optional doesn't take a value, format is: 447 # -s or --long 448 if action.nargs == 0: 449 part = '%s' % option_string 450 451 # if the Optional takes a value, format is: 452 # -s ARGS or --long ARGS 453 else: 454 default = action.dest.upper() 455 args_string = self._format_args(action, default) 456 part = '%s %s' % (option_string, args_string) 457 458 # make it look optional if it's not required or in a group 459 if not action.required and action not in group_actions: 460 part = '[%s]' % part 461 462 # add the action string to the list 463 parts.append(part) 464 465 # insert things at the necessary indices 466 for i in sorted(inserts, reverse=True): 467 parts[i:i] = [inserts[i]] 468 469 # join all the action items with spaces 470 text = ' '.join([item for item in parts if item is not None]) 471 472 # clean up separators for mutually exclusive groups 473 open = r'[\[(]' 474 close = r'[\])]' 475 text = _re.sub(r'(%s) ' % open, r'\1', text) 476 text = _re.sub(r' (%s)' % close, r'\1', text) 477 text = _re.sub(r'%s *%s' % (open, close), r'', text) 478 text = _re.sub(r'\(([^|]*)\)', r'\1', text) 479 text = text.strip() 480 481 # return the text 482 return text 483 484 def _format_text(self, text): 485 if '%(prog)' in text: 486 text = text % dict(prog=self._prog) 487 text_width = max(self._width - self._current_indent, 11) 488 indent = ' ' * self._current_indent 489 return self._fill_text(text, text_width, indent) + '\n\n' 490 491 def _format_action(self, action): 492 # determine the required width and the entry label 493 help_position = min(self._action_max_length + 2, 494 self._max_help_position) 495 help_width = max(self._width - help_position, 11) 496 action_width = help_position - self._current_indent - 2 497 action_header = self._format_action_invocation(action) 498 499 # ho nelp; start on same line and add a final newline 500 if not action.help: 501 tup = self._current_indent, '', action_header 502 action_header = '%*s%s\n' % tup 503 504 # short action name; start on the same line and pad two spaces 505 elif len(action_header) <= action_width: 506 tup = self._current_indent, '', action_width, action_header 507 action_header = '%*s%-*s ' % tup 508 indent_first = 0 509 510 # long action name; start on the next line 511 else: 512 tup = self._current_indent, '', action_header 513 action_header = '%*s%s\n' % tup 514 indent_first = help_position 515 516 # collect the pieces of the action help 517 parts = [action_header] 518 519 # if there was help for the action, add lines of help text 520 if action.help: 521 help_text = self._expand_help(action) 522 help_lines = self._split_lines(help_text, help_width) 523 parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) 524 for line in help_lines[1:]: 525 parts.append('%*s%s\n' % (help_position, '', line)) 526 527 # or add a newline if the description doesn't end with one 528 elif not action_header.endswith('\n'): 529 parts.append('\n') 530 531 # if there are any sub-actions, add their help as well 532 for subaction in self._iter_indented_subactions(action): 533 parts.append(self._format_action(subaction)) 534 535 # return a single string 536 return self._join_parts(parts) 537 538 def _format_action_invocation(self, action): 539 if not action.option_strings: 540 metavar, = self._metavar_formatter(action, action.dest)(1) 541 return metavar 542 543 else: 544 parts = [] 545 546 # if the Optional doesn't take a value, format is: 547 # -s, --long 548 if action.nargs == 0: 549 parts.extend(action.option_strings) 550 551 # if the Optional takes a value, format is: 552 # -s ARGS, --long ARGS 553 else: 554 default = action.dest.upper() 555 args_string = self._format_args(action, default) 556 for option_string in action.option_strings: 557 parts.append('%s %s' % (option_string, args_string)) 558 559 return ', '.join(parts) 560 561 def _metavar_formatter(self, action, default_metavar): 562 if action.metavar is not None: 563 result = action.metavar 564 elif action.choices is not None: 565 choice_strs = [str(choice) for choice in action.choices] 566 result = '{%s}' % ','.join(choice_strs) 567 else: 568 result = default_metavar 569 570 def format(tuple_size): 571 if isinstance(result, tuple): 572 return result 573 else: 574 return (result, ) * tuple_size 575 return format 576 577 def _format_args(self, action, default_metavar): 578 get_metavar = self._metavar_formatter(action, default_metavar) 579 if action.nargs is None: 580 result = '%s' % get_metavar(1) 581 elif action.nargs == OPTIONAL: 582 result = '[%s]' % get_metavar(1) 583 elif action.nargs == ZERO_OR_MORE: 584 result = '[%s [%s ...]]' % get_metavar(2) 585 elif action.nargs == ONE_OR_MORE: 586 result = '%s [%s ...]' % get_metavar(2) 587 elif action.nargs == REMAINDER: 588 result = '...' 589 elif action.nargs == PARSER: 590 result = '%s ...' % get_metavar(1) 591 else: 592 formats = ['%s' for _ in range(action.nargs)] 593 result = ' '.join(formats) % get_metavar(action.nargs) 594 return result 595 596 def _expand_help(self, action): 597 params = dict(vars(action), prog=self._prog) 598 for name in list(params): 599 if params[name] is SUPPRESS: 600 del params[name] 601 for name in list(params): 602 if hasattr(params[name], '__name__'): 603 params[name] = params[name].__name__ 604 if params.get('choices') is not None: 605 choices_str = ', '.join([str(c) for c in params['choices']]) 606 params['choices'] = choices_str 607 return self._get_help_string(action) % params 608 609 def _iter_indented_subactions(self, action): 610 try: 611 get_subactions = action._get_subactions 612 except AttributeError: 613 pass 614 else: 615 self._indent() 616 for subaction in get_subactions(): 617 yield subaction 618 self._dedent() 619 620 def _split_lines(self, text, width): 621 text = self._whitespace_matcher.sub(' ', text).strip() 622 return _textwrap.wrap(text, width) 623 624 def _fill_text(self, text, width, indent): 625 text = self._whitespace_matcher.sub(' ', text).strip() 626 return _textwrap.fill(text, width, initial_indent=indent, 627 subsequent_indent=indent) 628 629 def _get_help_string(self, action): 630 return action.help 631 632 633class RawDescriptionHelpFormatter(HelpFormatter): 634 """Help message formatter which retains any formatting in descriptions. 635 636 Only the name of this class is considered a public API. All the methods 637 provided by the class are considered an implementation detail. 638 """ 639 640 def _fill_text(self, text, width, indent): 641 return ''.join([indent + line for line in text.splitlines(True)]) 642 643 644class RawTextHelpFormatter(RawDescriptionHelpFormatter): 645 """Help message formatter which retains formatting of all help text. 646 647 Only the name of this class is considered a public API. All the methods 648 provided by the class are considered an implementation detail. 649 """ 650 651 def _split_lines(self, text, width): 652 return text.splitlines() 653 654 655class ArgumentDefaultsHelpFormatter(HelpFormatter): 656 """Help message formatter which adds default values to argument help. 657 658 Only the name of this class is considered a public API. All the methods 659 provided by the class are considered an implementation detail. 660 """ 661 662 def _get_help_string(self, action): 663 help = action.help 664 if '%(default)' not in action.help: 665 if action.default is not SUPPRESS: 666 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] 667 if action.option_strings or action.nargs in defaulting_nargs: 668 help += ' (default: %(default)s)' 669 return help 670 671 672# ===================== 673# Options and Arguments 674# ===================== 675 676def _get_action_name(argument): 677 if argument is None: 678 return None 679 elif argument.option_strings: 680 return '/'.join(argument.option_strings) 681 elif argument.metavar not in (None, SUPPRESS): 682 return argument.metavar 683 elif argument.dest not in (None, SUPPRESS): 684 return argument.dest 685 else: 686 return None 687 688 689class ArgumentError(Exception): 690 """An error from creating or using an argument (optional or positional). 691 692 The string value of this exception is the message, augmented with 693 information about the argument that caused it. 694 """ 695 696 def __init__(self, argument, message): 697 self.argument_name = _get_action_name(argument) 698 self.message = message 699 700 def __str__(self): 701 if self.argument_name is None: 702 format = '%(message)s' 703 else: 704 format = 'argument %(argument_name)s: %(message)s' 705 return format % dict(message=self.message, 706 argument_name=self.argument_name) 707 708 709class ArgumentTypeError(Exception): 710 """An error from trying to convert a command line string to a type.""" 711 pass 712 713 714# ============== 715# Action classes 716# ============== 717 718class Action(_AttributeHolder): 719 """Information about how to convert command line strings to Python objects. 720 721 Action objects are used by an ArgumentParser to represent the information 722 needed to parse a single argument from one or more strings from the 723 command line. The keyword arguments to the Action constructor are also 724 all attributes of Action instances. 725 726 Keyword Arguments: 727 728 - option_strings -- A list of command-line option strings which 729 should be associated with this action. 730 731 - dest -- The name of the attribute to hold the created object(s) 732 733 - nargs -- The number of command-line arguments that should be 734 consumed. By default, one argument will be consumed and a single 735 value will be produced. Other values include: 736 - N (an integer) consumes N arguments (and produces a list) 737 - '?' consumes zero or one arguments 738 - '*' consumes zero or more arguments (and produces a list) 739 - '+' consumes one or more arguments (and produces a list) 740 Note that the difference between the default and nargs=1 is that 741 with the default, a single value will be produced, while with 742 nargs=1, a list containing a single value will be produced. 743 744 - const -- The value to be produced if the option is specified and the 745 option uses an action that takes no values. 746 747 - default -- The value to be produced if the option is not specified. 748 749 - type -- A callable that accepts a single string argument, and 750 returns the converted value. The standard Python types str, int, 751 float, and complex are useful examples of such callables. If None, 752 str is used. 753 754 - choices -- A container of values that should be allowed. If not None, 755 after a command-line argument has been converted to the appropriate 756 type, an exception will be raised if it is not a member of this 757 collection. 758 759 - required -- True if the action must always be specified at the 760 command line. This is only meaningful for optional command-line 761 arguments. 762 763 - help -- The help string describing the argument. 764 765 - metavar -- The name to be used for the option's argument with the 766 help string. If None, the 'dest' value will be used as the name. 767 """ 768 769 def __init__(self, 770 option_strings, 771 dest, 772 nargs=None, 773 const=None, 774 default=None, 775 type=None, 776 choices=None, 777 required=False, 778 help=None, 779 metavar=None): 780 self.option_strings = option_strings 781 self.dest = dest 782 self.nargs = nargs 783 self.const = const 784 self.default = default 785 self.type = type 786 self.choices = choices 787 self.required = required 788 self.help = help 789 self.metavar = metavar 790 791 def _get_kwargs(self): 792 names = [ 793 'option_strings', 794 'dest', 795 'nargs', 796 'const', 797 'default', 798 'type', 799 'choices', 800 'help', 801 'metavar', 802 ] 803 return [(name, getattr(self, name)) for name in names] 804 805 def __call__(self, parser, namespace, values, option_string=None): 806 raise NotImplementedError(_('.__call__() not defined')) 807 808 809class _StoreAction(Action): 810 811 def __init__(self, 812 option_strings, 813 dest, 814 nargs=None, 815 const=None, 816 default=None, 817 type=None, 818 choices=None, 819 required=False, 820 help=None, 821 metavar=None): 822 if nargs == 0: 823 raise ValueError('nargs for store actions must be > 0; if you ' 824 'have nothing to store, actions such as store ' 825 'true or store const may be more appropriate') 826 if const is not None and nargs != OPTIONAL: 827 raise ValueError('nargs must be %r to supply const' % OPTIONAL) 828 super(_StoreAction, self).__init__( 829 option_strings=option_strings, 830 dest=dest, 831 nargs=nargs, 832 const=const, 833 default=default, 834 type=type, 835 choices=choices, 836 required=required, 837 help=help, 838 metavar=metavar) 839 840 def __call__(self, parser, namespace, values, option_string=None): 841 setattr(namespace, self.dest, values) 842 843 844class _StoreConstAction(Action): 845 846 def __init__(self, 847 option_strings, 848 dest, 849 const, 850 default=None, 851 required=False, 852 help=None, 853 metavar=None): 854 super(_StoreConstAction, self).__init__( 855 option_strings=option_strings, 856 dest=dest, 857 nargs=0, 858 const=const, 859 default=default, 860 required=required, 861 help=help) 862 863 def __call__(self, parser, namespace, values, option_string=None): 864 setattr(namespace, self.dest, self.const) 865 866 867class _StoreTrueAction(_StoreConstAction): 868 869 def __init__(self, 870 option_strings, 871 dest, 872 default=False, 873 required=False, 874 help=None): 875 super(_StoreTrueAction, self).__init__( 876 option_strings=option_strings, 877 dest=dest, 878 const=True, 879 default=default, 880 required=required, 881 help=help) 882 883 884class _StoreFalseAction(_StoreConstAction): 885 886 def __init__(self, 887 option_strings, 888 dest, 889 default=True, 890 required=False, 891 help=None): 892 super(_StoreFalseAction, self).__init__( 893 option_strings=option_strings, 894 dest=dest, 895 const=False, 896 default=default, 897 required=required, 898 help=help) 899 900 901class _AppendAction(Action): 902 903 def __init__(self, 904 option_strings, 905 dest, 906 nargs=None, 907 const=None, 908 default=None, 909 type=None, 910 choices=None, 911 required=False, 912 help=None, 913 metavar=None): 914 if nargs == 0: 915 raise ValueError('nargs for append actions must be > 0; if arg ' 916 'strings are not supplying the value to append, ' 917 'the append const action may be more appropriate') 918 if const is not None and nargs != OPTIONAL: 919 raise ValueError('nargs must be %r to supply const' % OPTIONAL) 920 super(_AppendAction, self).__init__( 921 option_strings=option_strings, 922 dest=dest, 923 nargs=nargs, 924 const=const, 925 default=default, 926 type=type, 927 choices=choices, 928 required=required, 929 help=help, 930 metavar=metavar) 931 932 def __call__(self, parser, namespace, values, option_string=None): 933 items = _copy.copy(_ensure_value(namespace, self.dest, [])) 934 items.append(values) 935 setattr(namespace, self.dest, items) 936 937 938class _AppendConstAction(Action): 939 940 def __init__(self, 941 option_strings, 942 dest, 943 const, 944 default=None, 945 required=False, 946 help=None, 947 metavar=None): 948 super(_AppendConstAction, self).__init__( 949 option_strings=option_strings, 950 dest=dest, 951 nargs=0, 952 const=const, 953 default=default, 954 required=required, 955 help=help, 956 metavar=metavar) 957 958 def __call__(self, parser, namespace, values, option_string=None): 959 items = _copy.copy(_ensure_value(namespace, self.dest, [])) 960 items.append(self.const) 961 setattr(namespace, self.dest, items) 962 963 964class _CountAction(Action): 965 966 def __init__(self, 967 option_strings, 968 dest, 969 default=None, 970 required=False, 971 help=None): 972 super(_CountAction, self).__init__( 973 option_strings=option_strings, 974 dest=dest, 975 nargs=0, 976 default=default, 977 required=required, 978 help=help) 979 980 def __call__(self, parser, namespace, values, option_string=None): 981 new_count = _ensure_value(namespace, self.dest, 0) + 1 982 setattr(namespace, self.dest, new_count) 983 984 985class _HelpAction(Action): 986 987 def __init__(self, 988 option_strings, 989 dest=SUPPRESS, 990 default=SUPPRESS, 991 help=None): 992 super(_HelpAction, self).__init__( 993 option_strings=option_strings, 994 dest=dest, 995 default=default, 996 nargs=0, 997 help=help) 998 999 def __call__(self, parser, namespace, values, option_string=None): 1000 parser.print_help() 1001 parser.exit() 1002 1003 1004class _VersionAction(Action): 1005 1006 def __init__(self, 1007 option_strings, 1008 version=None, 1009 dest=SUPPRESS, 1010 default=SUPPRESS, 1011 help="show program's version number and exit"): 1012 super(_VersionAction, self).__init__( 1013 option_strings=option_strings, 1014 dest=dest, 1015 default=default, 1016 nargs=0, 1017 help=help) 1018 self.version = version 1019 1020 def __call__(self, parser, namespace, values, option_string=None): 1021 version = self.version 1022 if version is None: 1023 version = parser.version 1024 formatter = parser._get_formatter() 1025 formatter.add_text(version) 1026 parser.exit(message=formatter.format_help()) 1027 1028 1029class _SubParsersAction(Action): 1030 1031 class _ChoicesPseudoAction(Action): 1032 1033 def __init__(self, name, help): 1034 sup = super(_SubParsersAction._ChoicesPseudoAction, self) 1035 sup.__init__(option_strings=[], dest=name, help=help) 1036 1037 def __init__(self, 1038 option_strings, 1039 prog, 1040 parser_class, 1041 dest=SUPPRESS, 1042 help=None, 1043 metavar=None): 1044 1045 self._prog_prefix = prog 1046 self._parser_class = parser_class 1047 self._name_parser_map = _collections.OrderedDict() 1048 self._choices_actions = [] 1049 1050 super(_SubParsersAction, self).__init__( 1051 option_strings=option_strings, 1052 dest=dest, 1053 nargs=PARSER, 1054 choices=self._name_parser_map, 1055 help=help, 1056 metavar=metavar) 1057 1058 def add_parser(self, name, **kwargs): 1059 # set prog from the existing prefix 1060 if kwargs.get('prog') is None: 1061 kwargs['prog'] = '%s %s' % (self._prog_prefix, name) 1062 1063 # create a pseudo-action to hold the choice help 1064 if 'help' in kwargs: 1065 help = kwargs.pop('help') 1066 choice_action = self._ChoicesPseudoAction(name, help) 1067 self._choices_actions.append(choice_action) 1068 1069 # create the parser and add it to the map 1070 parser = self._parser_class(**kwargs) 1071 self._name_parser_map[name] = parser 1072 return parser 1073 1074 def _get_subactions(self): 1075 return self._choices_actions 1076 1077 def __call__(self, parser, namespace, values, option_string=None): 1078 parser_name = values[0] 1079 arg_strings = values[1:] 1080 1081 # set the parser name if requested 1082 if self.dest is not SUPPRESS: 1083 setattr(namespace, self.dest, parser_name) 1084 1085 # select the parser 1086 try: 1087 parser = self._name_parser_map[parser_name] 1088 except KeyError: 1089 tup = parser_name, ', '.join(self._name_parser_map) 1090 msg = _('unknown parser %r (choices: %s)') % tup 1091 raise ArgumentError(self, msg) 1092 1093 # parse all the remaining options into the namespace 1094 # store any unrecognized options on the object, so that the top 1095 # level parser can decide what to do with them 1096 1097 # In case this subparser defines new defaults, we parse them 1098 # in a new namespace object and then update the original 1099 # namespace for the relevant parts. 1100 subnamespace, arg_strings = parser.parse_known_args(arg_strings, None) 1101 for key, value in vars(subnamespace).items(): 1102 setattr(namespace, key, value) 1103 1104 if arg_strings: 1105 vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, []) 1106 getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) 1107 1108 1109# ============== 1110# Type classes 1111# ============== 1112 1113class FileType(object): 1114 """Factory for creating file object types 1115 1116 Instances of FileType are typically passed as type= arguments to the 1117 ArgumentParser add_argument() method. 1118 1119 Keyword Arguments: 1120 - mode -- A string indicating how the file is to be opened. Accepts the 1121 same values as the builtin open() function. 1122 - bufsize -- The file's desired buffer size. Accepts the same values as 1123 the builtin open() function. 1124 """ 1125 1126 def __init__(self, mode='r', bufsize=-1): 1127 self._mode = mode 1128 self._bufsize = bufsize 1129 1130 def __call__(self, string): 1131 # the special argument "-" means sys.std{in,out} 1132 if string == '-': 1133 if 'r' in self._mode: 1134 return _sys.stdin 1135 elif 'w' in self._mode: 1136 return _sys.stdout 1137 else: 1138 msg = _('argument "-" with mode %r') % self._mode 1139 raise ValueError(msg) 1140 1141 # all other arguments are used as file names 1142 try: 1143 return open(string, self._mode, self._bufsize) 1144 except IOError as e: 1145 message = _("can't open '%s': %s") 1146 raise ArgumentTypeError(message % (string, e)) 1147 1148 def __repr__(self): 1149 args = self._mode, self._bufsize 1150 args_str = ', '.join(repr(arg) for arg in args if arg != -1) 1151 return '%s(%s)' % (type(self).__name__, args_str) 1152 1153# =========================== 1154# Optional and Positional Parsing 1155# =========================== 1156 1157class Namespace(_AttributeHolder): 1158 """Simple object for storing attributes. 1159 1160 Implements equality by attribute names and values, and provides a simple 1161 string representation. 1162 """ 1163 1164 def __init__(self, **kwargs): 1165 for name in kwargs: 1166 setattr(self, name, kwargs[name]) 1167 1168 __hash__ = None 1169 1170 def __eq__(self, other): 1171 if not isinstance(other, Namespace): 1172 return NotImplemented 1173 return vars(self) == vars(other) 1174 1175 def __ne__(self, other): 1176 if not isinstance(other, Namespace): 1177 return NotImplemented 1178 return not (self == other) 1179 1180 def __contains__(self, key): 1181 return key in self.__dict__ 1182 1183 1184class _ActionsContainer(object): 1185 1186 def __init__(self, 1187 description, 1188 prefix_chars, 1189 argument_default, 1190 conflict_handler): 1191 super(_ActionsContainer, self).__init__() 1192 1193 self.description = description 1194 self.argument_default = argument_default 1195 self.prefix_chars = prefix_chars 1196 self.conflict_handler = conflict_handler 1197 1198 # set up registries 1199 self._registries = {} 1200 1201 # register actions 1202 self.register('action', None, _StoreAction) 1203 self.register('action', 'store', _StoreAction) 1204 self.register('action', 'store_const', _StoreConstAction) 1205 self.register('action', 'store_true', _StoreTrueAction) 1206 self.register('action', 'store_false', _StoreFalseAction) 1207 self.register('action', 'append', _AppendAction) 1208 self.register('action', 'append_const', _AppendConstAction) 1209 self.register('action', 'count', _CountAction) 1210 self.register('action', 'help', _HelpAction) 1211 self.register('action', 'version', _VersionAction) 1212 self.register('action', 'parsers', _SubParsersAction) 1213 1214 # raise an exception if the conflict handler is invalid 1215 self._get_handler() 1216 1217 # action storage 1218 self._actions = [] 1219 self._option_string_actions = {} 1220 1221 # groups 1222 self._action_groups = [] 1223 self._mutually_exclusive_groups = [] 1224 1225 # defaults storage 1226 self._defaults = {} 1227 1228 # determines whether an "option" looks like a negative number 1229 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$') 1230 1231 # whether or not there are any optionals that look like negative 1232 # numbers -- uses a list so it can be shared and edited 1233 self._has_negative_number_optionals = [] 1234 1235 # ==================== 1236 # Registration methods 1237 # ==================== 1238 def register(self, registry_name, value, object): 1239 registry = self._registries.setdefault(registry_name, {}) 1240 registry[value] = object 1241 1242 def _registry_get(self, registry_name, value, default=None): 1243 return self._registries[registry_name].get(value, default) 1244 1245 # ================================== 1246 # Namespace default accessor methods 1247 # ================================== 1248 def set_defaults(self, **kwargs): 1249 self._defaults.update(kwargs) 1250 1251 # if these defaults match any existing arguments, replace 1252 # the previous default on the object with the new one 1253 for action in self._actions: 1254 if action.dest in kwargs: 1255 action.default = kwargs[action.dest] 1256 1257 def get_default(self, dest): 1258 for action in self._actions: 1259 if action.dest == dest and action.default is not None: 1260 return action.default 1261 return self._defaults.get(dest, None) 1262 1263 1264 # ======================= 1265 # Adding argument actions 1266 # ======================= 1267 def add_argument(self, *args, **kwargs): 1268 """ 1269 add_argument(dest, ..., name=value, ...) 1270 add_argument(option_string, option_string, ..., name=value, ...) 1271 """ 1272 1273 # if no positional args are supplied or only one is supplied and 1274 # it doesn't look like an option string, parse a positional 1275 # argument 1276 chars = self.prefix_chars 1277 if not args or len(args) == 1 and args[0][0] not in chars: 1278 if args and 'dest' in kwargs: 1279 raise ValueError('dest supplied twice for positional argument') 1280 kwargs = self._get_positional_kwargs(*args, **kwargs) 1281 1282 # otherwise, we're adding an optional argument 1283 else: 1284 kwargs = self._get_optional_kwargs(*args, **kwargs) 1285 1286 # if no default was supplied, use the parser-level default 1287 if 'default' not in kwargs: 1288 dest = kwargs['dest'] 1289 if dest in self._defaults: 1290 kwargs['default'] = self._defaults[dest] 1291 elif self.argument_default is not None: 1292 kwargs['default'] = self.argument_default 1293 1294 # create the action object, and add it to the parser 1295 action_class = self._pop_action_class(kwargs) 1296 if not _callable(action_class): 1297 raise ValueError('unknown action "%s"' % (action_class,)) 1298 action = action_class(**kwargs) 1299 1300 # raise an error if the action type is not callable 1301 type_func = self._registry_get('type', action.type, action.type) 1302 if not _callable(type_func): 1303 raise ValueError('%r is not callable' % (type_func,)) 1304 1305 # raise an error if the metavar does not match the type 1306 if hasattr(self, "_get_formatter"): 1307 try: 1308 self._get_formatter()._format_args(action, None) 1309 except TypeError: 1310 raise ValueError("length of metavar tuple does not match nargs") 1311 1312 return self._add_action(action) 1313 1314 def add_argument_group(self, *args, **kwargs): 1315 group = _ArgumentGroup(self, *args, **kwargs) 1316 self._action_groups.append(group) 1317 return group 1318 1319 def add_mutually_exclusive_group(self, **kwargs): 1320 group = _MutuallyExclusiveGroup(self, **kwargs) 1321 self._mutually_exclusive_groups.append(group) 1322 return group 1323 1324 def _add_action(self, action): 1325 # resolve any conflicts 1326 self._check_conflict(action) 1327 1328 # add to actions list 1329 self._actions.append(action) 1330 action.container = self 1331 1332 # index the action by any option strings it has 1333 for option_string in action.option_strings: 1334 self._option_string_actions[option_string] = action 1335 1336 # set the flag if any option strings look like negative numbers 1337 for option_string in action.option_strings: 1338 if self._negative_number_matcher.match(option_string): 1339 if not self._has_negative_number_optionals: 1340 self._has_negative_number_optionals.append(True) 1341 1342 # return the created action 1343 return action 1344 1345 def _remove_action(self, action): 1346 self._actions.remove(action) 1347 1348 def _add_container_actions(self, container): 1349 # collect groups by titles 1350 title_group_map = {} 1351 for group in self._action_groups: 1352 if group.title in title_group_map: 1353 msg = _('cannot merge actions - two groups are named %r') 1354 raise ValueError(msg % (group.title)) 1355 title_group_map[group.title] = group 1356 1357 # map each action to its group 1358 group_map = {} 1359 for group in container._action_groups: 1360 1361 # if a group with the title exists, use that, otherwise 1362 # create a new group matching the container's group 1363 if group.title not in title_group_map: 1364 title_group_map[group.title] = self.add_argument_group( 1365 title=group.title, 1366 description=group.description, 1367 conflict_handler=group.conflict_handler) 1368 1369 # map the actions to their new group 1370 for action in group._group_actions: 1371 group_map[action] = title_group_map[group.title] 1372 1373 # add container's mutually exclusive groups 1374 # NOTE: if add_mutually_exclusive_group ever gains title= and 1375 # description= then this code will need to be expanded as above 1376 for group in container._mutually_exclusive_groups: 1377 mutex_group = self.add_mutually_exclusive_group( 1378 required=group.required) 1379 1380 # map the actions to their new mutex group 1381 for action in group._group_actions: 1382 group_map[action] = mutex_group 1383 1384 # add all actions to this container or their group 1385 for action in container._actions: 1386 group_map.get(action, self)._add_action(action) 1387 1388 def _get_positional_kwargs(self, dest, **kwargs): 1389 # make sure required is not specified 1390 if 'required' in kwargs: 1391 msg = _("'required' is an invalid argument for positionals") 1392 raise TypeError(msg) 1393 1394 # mark positional arguments as required if at least one is 1395 # always required 1396 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]: 1397 kwargs['required'] = True 1398 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs: 1399 kwargs['required'] = True 1400 1401 # return the keyword arguments with no option strings 1402 return dict(kwargs, dest=dest, option_strings=[]) 1403 1404 def _get_optional_kwargs(self, *args, **kwargs): 1405 # determine short and long option strings 1406 option_strings = [] 1407 long_option_strings = [] 1408 for option_string in args: 1409 # error on strings that don't start with an appropriate prefix 1410 if not option_string[0] in self.prefix_chars: 1411 msg = _('invalid option string %r: ' 1412 'must start with a character %r') 1413 tup = option_string, self.prefix_chars 1414 raise ValueError(msg % tup) 1415 1416 # strings starting with two prefix characters are long options 1417 option_strings.append(option_string) 1418 if option_string[0] in self.prefix_chars: 1419 if len(option_string) > 1: 1420 if option_string[1] in self.prefix_chars: 1421 long_option_strings.append(option_string) 1422 1423 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' 1424 dest = kwargs.pop('dest', None) 1425 if dest is None: 1426 if long_option_strings: 1427 dest_option_string = long_option_strings[0] 1428 else: 1429 dest_option_string = option_strings[0] 1430 dest = dest_option_string.lstrip(self.prefix_chars) 1431 if not dest: 1432 msg = _('dest= is required for options like %r') 1433 raise ValueError(msg % option_string) 1434 dest = dest.replace('-', '_') 1435 1436 # return the updated keyword arguments 1437 return dict(kwargs, dest=dest, option_strings=option_strings) 1438 1439 def _pop_action_class(self, kwargs, default=None): 1440 action = kwargs.pop('action', default) 1441 return self._registry_get('action', action, action) 1442 1443 def _get_handler(self): 1444 # determine function from conflict handler string 1445 handler_func_name = '_handle_conflict_%s' % self.conflict_handler 1446 try: 1447 return getattr(self, handler_func_name) 1448 except AttributeError: 1449 msg = _('invalid conflict_resolution value: %r') 1450 raise ValueError(msg % self.conflict_handler) 1451 1452 def _check_conflict(self, action): 1453 1454 # find all options that conflict with this option 1455 confl_optionals = [] 1456 for option_string in action.option_strings: 1457 if option_string in self._option_string_actions: 1458 confl_optional = self._option_string_actions[option_string] 1459 confl_optionals.append((option_string, confl_optional)) 1460 1461 # resolve any conflicts 1462 if confl_optionals: 1463 conflict_handler = self._get_handler() 1464 conflict_handler(action, confl_optionals) 1465 1466 def _handle_conflict_error(self, action, conflicting_actions): 1467 message = _('conflicting option string(s): %s') 1468 conflict_string = ', '.join([option_string 1469 for option_string, action 1470 in conflicting_actions]) 1471 raise ArgumentError(action, message % conflict_string) 1472 1473 def _handle_conflict_resolve(self, action, conflicting_actions): 1474 1475 # remove all conflicting options 1476 for option_string, action in conflicting_actions: 1477 1478 # remove the conflicting option 1479 action.option_strings.remove(option_string) 1480 self._option_string_actions.pop(option_string, None) 1481 1482 # if the option now has no option string, remove it from the 1483 # container holding it 1484 if not action.option_strings: 1485 action.container._remove_action(action) 1486 1487 1488class _ArgumentGroup(_ActionsContainer): 1489 1490 def __init__(self, container, title=None, description=None, **kwargs): 1491 # add any missing keyword arguments by checking the container 1492 update = kwargs.setdefault 1493 update('conflict_handler', container.conflict_handler) 1494 update('prefix_chars', container.prefix_chars) 1495 update('argument_default', container.argument_default) 1496 super_init = super(_ArgumentGroup, self).__init__ 1497 super_init(description=description, **kwargs) 1498 1499 # group attributes 1500 self.title = title 1501 self._group_actions = [] 1502 1503 # share most attributes with the container 1504 self._registries = container._registries 1505 self._actions = container._actions 1506 self._option_string_actions = container._option_string_actions 1507 self._defaults = container._defaults 1508 self._has_negative_number_optionals = \ 1509 container._has_negative_number_optionals 1510 self._mutually_exclusive_groups = container._mutually_exclusive_groups 1511 1512 def _add_action(self, action): 1513 action = super(_ArgumentGroup, self)._add_action(action) 1514 self._group_actions.append(action) 1515 return action 1516 1517 def _remove_action(self, action): 1518 super(_ArgumentGroup, self)._remove_action(action) 1519 self._group_actions.remove(action) 1520 1521 1522class _MutuallyExclusiveGroup(_ArgumentGroup): 1523 1524 def __init__(self, container, required=False): 1525 super(_MutuallyExclusiveGroup, self).__init__(container) 1526 self.required = required 1527 self._container = container 1528 1529 def _add_action(self, action): 1530 if action.required: 1531 msg = _('mutually exclusive arguments must be optional') 1532 raise ValueError(msg) 1533 action = self._container._add_action(action) 1534 self._group_actions.append(action) 1535 return action 1536 1537 def _remove_action(self, action): 1538 self._container._remove_action(action) 1539 self._group_actions.remove(action) 1540 1541 1542class ArgumentParser(_AttributeHolder, _ActionsContainer): 1543 """Object for parsing command line strings into Python objects. 1544 1545 Keyword Arguments: 1546 - prog -- The name of the program (default: sys.argv[0]) 1547 - usage -- A usage message (default: auto-generated from arguments) 1548 - description -- A description of what the program does 1549 - epilog -- Text following the argument descriptions 1550 - parents -- Parsers whose arguments should be copied into this one 1551 - formatter_class -- HelpFormatter class for printing help messages 1552 - prefix_chars -- Characters that prefix optional arguments 1553 - fromfile_prefix_chars -- Characters that prefix files containing 1554 additional arguments 1555 - argument_default -- The default value for all arguments 1556 - conflict_handler -- String indicating how to handle conflicts 1557 - add_help -- Add a -h/-help option 1558 """ 1559 1560 def __init__(self, 1561 prog=None, 1562 usage=None, 1563 description=None, 1564 epilog=None, 1565 version=None, 1566 parents=[], 1567 formatter_class=HelpFormatter, 1568 prefix_chars='-', 1569 fromfile_prefix_chars=None, 1570 argument_default=None, 1571 conflict_handler='error', 1572 add_help=True): 1573 1574 if version is not None: 1575 import warnings 1576 warnings.warn( 1577 """The "version" argument to ArgumentParser is deprecated. """ 1578 """Please use """ 1579 """"add_argument(..., action='version', version="N", ...)" """ 1580 """instead""", DeprecationWarning) 1581 1582 superinit = super(ArgumentParser, self).__init__ 1583 superinit(description=description, 1584 prefix_chars=prefix_chars, 1585 argument_default=argument_default, 1586 conflict_handler=conflict_handler) 1587 1588 # default setting for prog 1589 if prog is None: 1590 prog = _os.path.basename(_sys.argv[0]) 1591 1592 self.prog = prog 1593 self.usage = usage 1594 self.epilog = epilog 1595 self.version = version 1596 self.formatter_class = formatter_class 1597 self.fromfile_prefix_chars = fromfile_prefix_chars 1598 self.add_help = add_help 1599 1600 add_group = self.add_argument_group 1601 self._positionals = add_group(_('positional arguments')) 1602 self._optionals = add_group(_('optional arguments')) 1603 self._subparsers = None 1604 1605 # register types 1606 def identity(string): 1607 return string 1608 self.register('type', None, identity) 1609 1610 # add help and version arguments if necessary 1611 # (using explicit default to override global argument_default) 1612 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0] 1613 if self.add_help: 1614 self.add_argument( 1615 default_prefix+'h', default_prefix*2+'help', 1616 action='help', default=SUPPRESS, 1617 help=_('show this help message and exit')) 1618 if self.version: 1619 self.add_argument( 1620 default_prefix+'v', default_prefix*2+'version', 1621 action='version', default=SUPPRESS, 1622 version=self.version, 1623 help=_("show program's version number and exit")) 1624 1625 # add parent arguments and defaults 1626 for parent in parents: 1627 self._add_container_actions(parent) 1628 try: 1629 defaults = parent._defaults 1630 except AttributeError: 1631 pass 1632 else: 1633 self._defaults.update(defaults) 1634 1635 # ======================= 1636 # Pretty __repr__ methods 1637 # ======================= 1638 def _get_kwargs(self): 1639 names = [ 1640 'prog', 1641 'usage', 1642 'description', 1643 'version', 1644 'formatter_class', 1645 'conflict_handler', 1646 'add_help', 1647 ] 1648 return [(name, getattr(self, name)) for name in names] 1649 1650 # ================================== 1651 # Optional/Positional adding methods 1652 # ================================== 1653 def add_subparsers(self, **kwargs): 1654 if self._subparsers is not None: 1655 self.error(_('cannot have multiple subparser arguments')) 1656 1657 # add the parser class to the arguments if it's not present 1658 kwargs.setdefault('parser_class', type(self)) 1659 1660 if 'title' in kwargs or 'description' in kwargs: 1661 title = _(kwargs.pop('title', 'subcommands')) 1662 description = _(kwargs.pop('description', None)) 1663 self._subparsers = self.add_argument_group(title, description) 1664 else: 1665 self._subparsers = self._positionals 1666 1667 # prog defaults to the usage message of this parser, skipping 1668 # optional arguments and with no "usage:" prefix 1669 if kwargs.get('prog') is None: 1670 formatter = self._get_formatter() 1671 positionals = self._get_positional_actions() 1672 groups = self._mutually_exclusive_groups 1673 formatter.add_usage(self.usage, positionals, groups, '') 1674 kwargs['prog'] = formatter.format_help().strip() 1675 1676 # create the parsers action and add it to the positionals list 1677 parsers_class = self._pop_action_class(kwargs, 'parsers') 1678 action = parsers_class(option_strings=[], **kwargs) 1679 self._subparsers._add_action(action) 1680 1681 # return the created parsers action 1682 return action 1683 1684 def _add_action(self, action): 1685 if action.option_strings: 1686 self._optionals._add_action(action) 1687 else: 1688 self._positionals._add_action(action) 1689 return action 1690 1691 def _get_optional_actions(self): 1692 return [action 1693 for action in self._actions 1694 if action.option_strings] 1695 1696 def _get_positional_actions(self): 1697 return [action 1698 for action in self._actions 1699 if not action.option_strings] 1700 1701 # ===================================== 1702 # Command line argument parsing methods 1703 # ===================================== 1704 def parse_args(self, args=None, namespace=None): 1705 args, argv = self.parse_known_args(args, namespace) 1706 if argv: 1707 msg = _('unrecognized arguments: %s') 1708 self.error(msg % ' '.join(argv)) 1709 return args 1710 1711 def parse_known_args(self, args=None, namespace=None): 1712 if args is None: 1713 # args default to the system args 1714 args = _sys.argv[1:] 1715 else: 1716 # make sure that args are mutable 1717 args = list(args) 1718 1719 # default Namespace built from parser defaults 1720 if namespace is None: 1721 namespace = Namespace() 1722 1723 # add any action defaults that aren't present 1724 for action in self._actions: 1725 if action.dest is not SUPPRESS: 1726 if not hasattr(namespace, action.dest): 1727 if action.default is not SUPPRESS: 1728 setattr(namespace, action.dest, action.default) 1729 1730 # add any parser defaults that aren't present 1731 for dest in self._defaults: 1732 if not hasattr(namespace, dest): 1733 setattr(namespace, dest, self._defaults[dest]) 1734 1735 # parse the arguments and exit if there are any errors 1736 try: 1737 namespace, args = self._parse_known_args(args, namespace) 1738 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR): 1739 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) 1740 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) 1741 return namespace, args 1742 except ArgumentError: 1743 err = _sys.exc_info()[1] 1744 self.error(str(err)) 1745 1746 def _parse_known_args(self, arg_strings, namespace): 1747 # replace arg strings that are file references 1748 if self.fromfile_prefix_chars is not None: 1749 arg_strings = self._read_args_from_files(arg_strings) 1750 1751 # map all mutually exclusive arguments to the other arguments 1752 # they can't occur with 1753 action_conflicts = {} 1754 for mutex_group in self._mutually_exclusive_groups: 1755 group_actions = mutex_group._group_actions 1756 for i, mutex_action in enumerate(mutex_group._group_actions): 1757 conflicts = action_conflicts.setdefault(mutex_action, []) 1758 conflicts.extend(group_actions[:i]) 1759 conflicts.extend(group_actions[i + 1:]) 1760 1761 # find all option indices, and determine the arg_string_pattern 1762 # which has an 'O' if there is an option at an index, 1763 # an 'A' if there is an argument, or a '-' if there is a '--' 1764 option_string_indices = {} 1765 arg_string_pattern_parts = [] 1766 arg_strings_iter = iter(arg_strings) 1767 for i, arg_string in enumerate(arg_strings_iter): 1768 1769 # all args after -- are non-options 1770 if arg_string == '--': 1771 arg_string_pattern_parts.append('-') 1772 for arg_string in arg_strings_iter: 1773 arg_string_pattern_parts.append('A') 1774 1775 # otherwise, add the arg to the arg strings 1776 # and note the index if it was an option 1777 else: 1778 option_tuple = self._parse_optional(arg_string) 1779 if option_tuple is None: 1780 pattern = 'A' 1781 else: 1782 option_string_indices[i] = option_tuple 1783 pattern = 'O' 1784 arg_string_pattern_parts.append(pattern) 1785 1786 # join the pieces together to form the pattern 1787 arg_strings_pattern = ''.join(arg_string_pattern_parts) 1788 1789 # converts arg strings to the appropriate and then takes the action 1790 seen_actions = set() 1791 seen_non_default_actions = set() 1792 1793 def take_action(action, argument_strings, option_string=None): 1794 seen_actions.add(action) 1795 argument_values = self._get_values(action, argument_strings) 1796 1797 # error if this argument is not allowed with other previously 1798 # seen arguments, assuming that actions that use the default 1799 # value don't really count as "present" 1800 if argument_values is not action.default: 1801 seen_non_default_actions.add(action) 1802 for conflict_action in action_conflicts.get(action, []): 1803 if conflict_action in seen_non_default_actions: 1804 msg = _('not allowed with argument %s') 1805 action_name = _get_action_name(conflict_action) 1806 raise ArgumentError(action, msg % action_name) 1807 1808 # take the action if we didn't receive a SUPPRESS value 1809 # (e.g. from a default) 1810 if argument_values is not SUPPRESS: 1811 action(self, namespace, argument_values, option_string) 1812 1813 # function to convert arg_strings into an optional action 1814 def consume_optional(start_index): 1815 1816 # get the optional identified at this index 1817 option_tuple = option_string_indices[start_index] 1818 action, option_string, explicit_arg = option_tuple 1819 1820 # identify additional optionals in the same arg string 1821 # (e.g. -xyz is the same as -x -y -z if no args are required) 1822 match_argument = self._match_argument 1823 action_tuples = [] 1824 while True: 1825 1826 # if we found no optional action, skip it 1827 if action is None: 1828 extras.append(arg_strings[start_index]) 1829 return start_index + 1 1830 1831 # if there is an explicit argument, try to match the 1832 # optional's string arguments to only this 1833 if explicit_arg is not None: 1834 arg_count = match_argument(action, 'A') 1835 1836 # if the action is a single-dash option and takes no 1837 # arguments, try to parse more single-dash options out 1838 # of the tail of the option string 1839 chars = self.prefix_chars 1840 if arg_count == 0 and option_string[1] not in chars: 1841 action_tuples.append((action, [], option_string)) 1842 char = option_string[0] 1843 option_string = char + explicit_arg[0] 1844 new_explicit_arg = explicit_arg[1:] or None 1845 optionals_map = self._option_string_actions 1846 if option_string in optionals_map: 1847 action = optionals_map[option_string] 1848 explicit_arg = new_explicit_arg 1849 else: 1850 msg = _('ignored explicit argument %r') 1851 raise ArgumentError(action, msg % explicit_arg) 1852 1853 # if the action expect exactly one argument, we've 1854 # successfully matched the option; exit the loop 1855 elif arg_count == 1: 1856 stop = start_index + 1 1857 args = [explicit_arg] 1858 action_tuples.append((action, args, option_string)) 1859 break 1860 1861 # error if a double-dash option did not use the 1862 # explicit argument 1863 else: 1864 msg = _('ignored explicit argument %r') 1865 raise ArgumentError(action, msg % explicit_arg) 1866 1867 # if there is no explicit argument, try to match the 1868 # optional's string arguments with the following strings 1869 # if successful, exit the loop 1870 else: 1871 start = start_index + 1 1872 selected_patterns = arg_strings_pattern[start:] 1873 arg_count = match_argument(action, selected_patterns) 1874 stop = start + arg_count 1875 args = arg_strings[start:stop] 1876 action_tuples.append((action, args, option_string)) 1877 break 1878 1879 # add the Optional to the list and return the index at which 1880 # the Optional's string args stopped 1881 assert action_tuples 1882 for action, args, option_string in action_tuples: 1883 take_action(action, args, option_string) 1884 return stop 1885 1886 # the list of Positionals left to be parsed; this is modified 1887 # by consume_positionals() 1888 positionals = self._get_positional_actions() 1889 1890 # function to convert arg_strings into positional actions 1891 def consume_positionals(start_index): 1892 # match as many Positionals as possible 1893 match_partial = self._match_arguments_partial 1894 selected_pattern = arg_strings_pattern[start_index:] 1895 arg_counts = match_partial(positionals, selected_pattern) 1896 1897 # slice off the appropriate arg strings for each Positional 1898 # and add the Positional and its args to the list 1899 for action, arg_count in zip(positionals, arg_counts): 1900 args = arg_strings[start_index: start_index + arg_count] 1901 start_index += arg_count 1902 take_action(action, args) 1903 1904 # slice off the Positionals that we just parsed and return the 1905 # index at which the Positionals' string args stopped 1906 positionals[:] = positionals[len(arg_counts):] 1907 return start_index 1908 1909 # consume Positionals and Optionals alternately, until we have 1910 # passed the last option string 1911 extras = [] 1912 start_index = 0 1913 if option_string_indices: 1914 max_option_string_index = max(option_string_indices) 1915 else: 1916 max_option_string_index = -1 1917 while start_index <= max_option_string_index: 1918 1919 # consume any Positionals preceding the next option 1920 next_option_string_index = min([ 1921 index 1922 for index in option_string_indices 1923 if index >= start_index]) 1924 if start_index != next_option_string_index: 1925 positionals_end_index = consume_positionals(start_index) 1926 1927 # only try to parse the next optional if we didn't consume 1928 # the option string during the positionals parsing 1929 if positionals_end_index > start_index: 1930 start_index = positionals_end_index 1931 continue 1932 else: 1933 start_index = positionals_end_index 1934 1935 # if we consumed all the positionals we could and we're not 1936 # at the index of an option string, there were extra arguments 1937 if start_index not in option_string_indices: 1938 strings = arg_strings[start_index:next_option_string_index] 1939 extras.extend(strings) 1940 start_index = next_option_string_index 1941 1942 # consume the next optional and any arguments for it 1943 start_index = consume_optional(start_index) 1944 1945 # consume any positionals following the last Optional 1946 stop_index = consume_positionals(start_index) 1947 1948 # if we didn't consume all the argument strings, there were extras 1949 extras.extend(arg_strings[stop_index:]) 1950 1951 # if we didn't use all the Positional objects, there were too few 1952 # arg strings supplied. 1953 if positionals: 1954 self.error(_('too few arguments')) 1955 1956 # make sure all required actions were present, and convert defaults. 1957 for action in self._actions: 1958 if action not in seen_actions: 1959 if action.required: 1960 name = _get_action_name(action) 1961 self.error(_('argument %s is required') % name) 1962 else: 1963 # Convert action default now instead of doing it before 1964 # parsing arguments to avoid calling convert functions 1965 # twice (which may fail) if the argument was given, but 1966 # only if it was defined already in the namespace 1967 if (action.default is not None and 1968 isinstance(action.default, basestring) and 1969 hasattr(namespace, action.dest) and 1970 action.default is getattr(namespace, action.dest)): 1971 setattr(namespace, action.dest, 1972 self._get_value(action, action.default)) 1973 1974 # make sure all required groups had one option present 1975 for group in self._mutually_exclusive_groups: 1976 if group.required: 1977 for action in group._group_actions: 1978 if action in seen_non_default_actions: 1979 break 1980 1981 # if no actions were used, report the error 1982 else: 1983 names = [_get_action_name(action) 1984 for action in group._group_actions 1985 if action.help is not SUPPRESS] 1986 msg = _('one of the arguments %s is required') 1987 self.error(msg % ' '.join(names)) 1988 1989 # return the updated namespace and the extra arguments 1990 return namespace, extras 1991 1992 def _read_args_from_files(self, arg_strings): 1993 # expand arguments referencing files 1994 new_arg_strings = [] 1995 for arg_string in arg_strings: 1996 1997 # for regular arguments, just add them back into the list 1998 if not arg_string or arg_string[0] not in self.fromfile_prefix_chars: 1999 new_arg_strings.append(arg_string) 2000 2001 # replace arguments referencing files with the file content 2002 else: 2003 try: 2004 args_file = open(arg_string[1:]) 2005 try: 2006 arg_strings = [] 2007 for arg_line in args_file.read().splitlines(): 2008 for arg in self.convert_arg_line_to_args(arg_line): 2009 arg_strings.append(arg) 2010 arg_strings = self._read_args_from_files(arg_strings) 2011 new_arg_strings.extend(arg_strings) 2012 finally: 2013 args_file.close() 2014 except IOError: 2015 err = _sys.exc_info()[1] 2016 self.error(str(err)) 2017 2018 # return the modified argument list 2019 return new_arg_strings 2020 2021 def convert_arg_line_to_args(self, arg_line): 2022 return [arg_line] 2023 2024 def _match_argument(self, action, arg_strings_pattern): 2025 # match the pattern for this action to the arg strings 2026 nargs_pattern = self._get_nargs_pattern(action) 2027 match = _re.match(nargs_pattern, arg_strings_pattern) 2028 2029 # raise an exception if we weren't able to find a match 2030 if match is None: 2031 nargs_errors = { 2032 None: _('expected one argument'), 2033 OPTIONAL: _('expected at most one argument'), 2034 ONE_OR_MORE: _('expected at least one argument'), 2035 } 2036 default = _('expected %s argument(s)') % action.nargs 2037 msg = nargs_errors.get(action.nargs, default) 2038 raise ArgumentError(action, msg) 2039 2040 # return the number of arguments matched 2041 return len(match.group(1)) 2042 2043 def _match_arguments_partial(self, actions, arg_strings_pattern): 2044 # progressively shorten the actions list by slicing off the 2045 # final actions until we find a match 2046 result = [] 2047 for i in range(len(actions), 0, -1): 2048 actions_slice = actions[:i] 2049 pattern = ''.join([self._get_nargs_pattern(action) 2050 for action in actions_slice]) 2051 match = _re.match(pattern, arg_strings_pattern) 2052 if match is not None: 2053 result.extend([len(string) for string in match.groups()]) 2054 break 2055 2056 # return the list of arg string counts 2057 return result 2058 2059 def _parse_optional(self, arg_string): 2060 # if it's an empty string, it was meant to be a positional 2061 if not arg_string: 2062 return None 2063 2064 # if it doesn't start with a prefix, it was meant to be positional 2065 if not arg_string[0] in self.prefix_chars: 2066 return None 2067 2068 # if the option string is present in the parser, return the action 2069 if arg_string in self._option_string_actions: 2070 action = self._option_string_actions[arg_string] 2071 return action, arg_string, None 2072 2073 # if it's just a single character, it was meant to be positional 2074 if len(arg_string) == 1: 2075 return None 2076 2077 # if the option string before the "=" is present, return the action 2078 if '=' in arg_string: 2079 option_string, explicit_arg = arg_string.split('=', 1) 2080 if option_string in self._option_string_actions: 2081 action = self._option_string_actions[option_string] 2082 return action, option_string, explicit_arg 2083 2084 # search through all possible prefixes of the option string 2085 # and all actions in the parser for possible interpretations 2086 option_tuples = self._get_option_tuples(arg_string) 2087 2088 # if multiple actions match, the option string was ambiguous 2089 if len(option_tuples) > 1: 2090 options = ', '.join([option_string 2091 for action, option_string, explicit_arg in option_tuples]) 2092 tup = arg_string, options 2093 self.error(_('ambiguous option: %s could match %s') % tup) 2094 2095 # if exactly one action matched, this segmentation is good, 2096 # so return the parsed action 2097 elif len(option_tuples) == 1: 2098 option_tuple, = option_tuples 2099 return option_tuple 2100 2101 # if it was not found as an option, but it looks like a negative 2102 # number, it was meant to be positional 2103 # unless there are negative-number-like options 2104 if self._negative_number_matcher.match(arg_string): 2105 if not self._has_negative_number_optionals: 2106 return None 2107 2108 # if it contains a space, it was meant to be a positional 2109 if ' ' in arg_string: 2110 return None 2111 2112 # it was meant to be an optional but there is no such option 2113 # in this parser (though it might be a valid option in a subparser) 2114 return None, arg_string, None 2115 2116 def _get_option_tuples(self, option_string): 2117 result = [] 2118 2119 # option strings starting with two prefix characters are only 2120 # split at the '=' 2121 chars = self.prefix_chars 2122 if option_string[0] in chars and option_string[1] in chars: 2123 if '=' in option_string: 2124 option_prefix, explicit_arg = option_string.split('=', 1) 2125 else: 2126 option_prefix = option_string 2127 explicit_arg = None 2128 for option_string in self._option_string_actions: 2129 if option_string.startswith(option_prefix): 2130 action = self._option_string_actions[option_string] 2131 tup = action, option_string, explicit_arg 2132 result.append(tup) 2133 2134 # single character options can be concatenated with their arguments 2135 # but multiple character options always have to have their argument 2136 # separate 2137 elif option_string[0] in chars and option_string[1] not in chars: 2138 option_prefix = option_string 2139 explicit_arg = None 2140 short_option_prefix = option_string[:2] 2141 short_explicit_arg = option_string[2:] 2142 2143 for option_string in self._option_string_actions: 2144 if option_string == short_option_prefix: 2145 action = self._option_string_actions[option_string] 2146 tup = action, option_string, short_explicit_arg 2147 result.append(tup) 2148 elif option_string.startswith(option_prefix): 2149 action = self._option_string_actions[option_string] 2150 tup = action, option_string, explicit_arg 2151 result.append(tup) 2152 2153 # shouldn't ever get here 2154 else: 2155 self.error(_('unexpected option string: %s') % option_string) 2156 2157 # return the collected option tuples 2158 return result 2159 2160 def _get_nargs_pattern(self, action): 2161 # in all examples below, we have to allow for '--' args 2162 # which are represented as '-' in the pattern 2163 nargs = action.nargs 2164 2165 # the default (None) is assumed to be a single argument 2166 if nargs is None: 2167 nargs_pattern = '(-*A-*)' 2168 2169 # allow zero or one arguments 2170 elif nargs == OPTIONAL: 2171 nargs_pattern = '(-*A?-*)' 2172 2173 # allow zero or more arguments 2174 elif nargs == ZERO_OR_MORE: 2175 nargs_pattern = '(-*[A-]*)' 2176 2177 # allow one or more arguments 2178 elif nargs == ONE_OR_MORE: 2179 nargs_pattern = '(-*A[A-]*)' 2180 2181 # allow any number of options or arguments 2182 elif nargs == REMAINDER: 2183 nargs_pattern = '([-AO]*)' 2184 2185 # allow one argument followed by any number of options or arguments 2186 elif nargs == PARSER: 2187 nargs_pattern = '(-*A[-AO]*)' 2188 2189 # all others should be integers 2190 else: 2191 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs) 2192 2193 # if this is an optional action, -- is not allowed 2194 if action.option_strings: 2195 nargs_pattern = nargs_pattern.replace('-*', '') 2196 nargs_pattern = nargs_pattern.replace('-', '') 2197 2198 # return the pattern 2199 return nargs_pattern 2200 2201 # ======================== 2202 # Value conversion methods 2203 # ======================== 2204 def _get_values(self, action, arg_strings): 2205 # for everything but PARSER, REMAINDER args, strip out first '--' 2206 if action.nargs not in [PARSER, REMAINDER]: 2207 try: 2208 arg_strings.remove('--') 2209 except ValueError: 2210 pass 2211 2212 # optional argument produces a default when not present 2213 if not arg_strings and action.nargs == OPTIONAL: 2214 if action.option_strings: 2215 value = action.const 2216 else: 2217 value = action.default 2218 if isinstance(value, basestring): 2219 value = self._get_value(action, value) 2220 self._check_value(action, value) 2221 2222 # when nargs='*' on a positional, if there were no command-line 2223 # args, use the default if it is anything other than None 2224 elif (not arg_strings and action.nargs == ZERO_OR_MORE and 2225 not action.option_strings): 2226 if action.default is not None: 2227 value = action.default 2228 else: 2229 value = arg_strings 2230 self._check_value(action, value) 2231 2232 # single argument or optional argument produces a single value 2233 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]: 2234 arg_string, = arg_strings 2235 value = self._get_value(action, arg_string) 2236 self._check_value(action, value) 2237 2238 # REMAINDER arguments convert all values, checking none 2239 elif action.nargs == REMAINDER: 2240 value = [self._get_value(action, v) for v in arg_strings] 2241 2242 # PARSER arguments convert all values, but check only the first 2243 elif action.nargs == PARSER: 2244 value = [self._get_value(action, v) for v in arg_strings] 2245 self._check_value(action, value[0]) 2246 2247 # all other types of nargs produce a list 2248 else: 2249 value = [self._get_value(action, v) for v in arg_strings] 2250 for v in value: 2251 self._check_value(action, v) 2252 2253 # return the converted value 2254 return value 2255 2256 def _get_value(self, action, arg_string): 2257 type_func = self._registry_get('type', action.type, action.type) 2258 if not _callable(type_func): 2259 msg = _('%r is not callable') 2260 raise ArgumentError(action, msg % type_func) 2261 2262 # convert the value to the appropriate type 2263 try: 2264 result = type_func(arg_string) 2265 2266 # ArgumentTypeErrors indicate errors 2267 except ArgumentTypeError: 2268 name = getattr(action.type, '__name__', repr(action.type)) 2269 msg = str(_sys.exc_info()[1]) 2270 raise ArgumentError(action, msg) 2271 2272 # TypeErrors or ValueErrors also indicate errors 2273 except (TypeError, ValueError): 2274 name = getattr(action.type, '__name__', repr(action.type)) 2275 msg = _('invalid %s value: %r') 2276 raise ArgumentError(action, msg % (name, arg_string)) 2277 2278 # return the converted value 2279 return result 2280 2281 def _check_value(self, action, value): 2282 # converted value must be one of the choices (if specified) 2283 if action.choices is not None and value not in action.choices: 2284 tup = value, ', '.join(map(repr, action.choices)) 2285 msg = _('invalid choice: %r (choose from %s)') % tup 2286 raise ArgumentError(action, msg) 2287 2288 # ======================= 2289 # Help-formatting methods 2290 # ======================= 2291 def format_usage(self): 2292 formatter = self._get_formatter() 2293 formatter.add_usage(self.usage, self._actions, 2294 self._mutually_exclusive_groups) 2295 return formatter.format_help() 2296 2297 def format_help(self): 2298 formatter = self._get_formatter() 2299 2300 # usage 2301 formatter.add_usage(self.usage, self._actions, 2302 self._mutually_exclusive_groups) 2303 2304 # description 2305 formatter.add_text(self.description) 2306 2307 # positionals, optionals and user-defined groups 2308 for action_group in self._action_groups: 2309 formatter.start_section(action_group.title) 2310 formatter.add_text(action_group.description) 2311 formatter.add_arguments(action_group._group_actions) 2312 formatter.end_section() 2313 2314 # epilog 2315 formatter.add_text(self.epilog) 2316 2317 # determine help from format above 2318 return formatter.format_help() 2319 2320 def format_version(self): 2321 import warnings 2322 warnings.warn( 2323 'The format_version method is deprecated -- the "version" ' 2324 'argument to ArgumentParser is no longer supported.', 2325 DeprecationWarning) 2326 formatter = self._get_formatter() 2327 formatter.add_text(self.version) 2328 return formatter.format_help() 2329 2330 def _get_formatter(self): 2331 return self.formatter_class(prog=self.prog) 2332 2333 # ===================== 2334 # Help-printing methods 2335 # ===================== 2336 def print_usage(self, file=None): 2337 if file is None: 2338 file = _sys.stdout 2339 self._print_message(self.format_usage(), file) 2340 2341 def print_help(self, file=None): 2342 if file is None: 2343 file = _sys.stdout 2344 self._print_message(self.format_help(), file) 2345 2346 def print_version(self, file=None): 2347 import warnings 2348 warnings.warn( 2349 'The print_version method is deprecated -- the "version" ' 2350 'argument to ArgumentParser is no longer supported.', 2351 DeprecationWarning) 2352 self._print_message(self.format_version(), file) 2353 2354 def _print_message(self, message, file=None): 2355 if message: 2356 if file is None: 2357 file = _sys.stderr 2358 file.write(message) 2359 2360 # =============== 2361 # Exiting methods 2362 # =============== 2363 def exit(self, status=0, message=None): 2364 if message: 2365 self._print_message(message, _sys.stderr) 2366 _sys.exit(status) 2367 2368 def error(self, message): 2369 """error(message: string) 2370 2371 Prints a usage message incorporating the message to stderr and 2372 exits. 2373 2374 If you override this in a subclass, it should not return -- it 2375 should either exit or raise an exception. 2376 """ 2377 self.print_usage(_sys.stderr) 2378 self.exit(2, _('%s: error: %s\n') % (self.prog, message)) 2379