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