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