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