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