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