00001
00002
00003 """Command-line parsing library
00004
00005 This module is an optparse-inspired command-line parsing library that:
00006
00007 - handles both optional and positional arguments
00008 - produces highly informative usage messages
00009 - supports parsers that dispatch to sub-parsers
00010
00011 The following is a simple usage example that sums integers from the
00012 command-line and writes the result to a file::
00013
00014 parser = argparse.ArgumentParser(
00015 description='sum the integers at the command line')
00016 parser.add_argument(
00017 'integers', metavar='int', nargs='+', type=int,
00018 help='an integer to be summed')
00019 parser.add_argument(
00020 '--log', default=sys.stdout, type=argparse.FileType('w'),
00021 help='the file where the sum should be written')
00022 args = parser.parse_args()
00023 args.log.write('%s' % sum(args.integers))
00024 args.log.close()
00025
00026 The module contains the following public classes:
00027
00028 - ArgumentParser -- The main entry point for command-line parsing. As the
00029 example above shows, the add_argument() method is used to populate
00030 the parser with actions for optional and positional arguments. Then
00031 the parse_args() method is invoked to convert the args at the
00032 command-line into an object with attributes.
00033
00034 - ArgumentError -- The exception raised by ArgumentParser objects when
00035 there are errors with the parser's actions. Errors raised while
00036 parsing the command-line are caught by ArgumentParser and emitted
00037 as command-line messages.
00038
00039 - FileType -- A factory for defining types of files to be created. As the
00040 example above shows, instances of FileType are typically passed as
00041 the type= argument of add_argument() calls.
00042
00043 - Action -- The base class for parser actions. Typically actions are
00044 selected by passing strings like 'store_true' or 'append_const' to
00045 the action= argument of add_argument(). However, for greater
00046 customization of ArgumentParser actions, subclasses of Action may
00047 be defined and passed as the action= argument.
00048
00049 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
00050 ArgumentDefaultsHelpFormatter -- Formatter classes which
00051 may be passed as the formatter_class= argument to the
00052 ArgumentParser constructor. HelpFormatter is the default,
00053 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
00054 not to change the formatting for help text, and
00055 ArgumentDefaultsHelpFormatter adds information about argument defaults
00056 to the help.
00057
00058 All other classes in this module are considered implementation details.
00059 (Also note that HelpFormatter and RawDescriptionHelpFormatter are only
00060 considered public as object names -- the API of the formatter objects is
00061 still considered an implementation detail.)
00062 """
00063
00064 __version__ = '1.1'
00065 __all__ = [
00066 'ArgumentParser',
00067 'ArgumentError',
00068 'ArgumentTypeError',
00069 'FileType',
00070 'HelpFormatter',
00071 'ArgumentDefaultsHelpFormatter',
00072 'RawDescriptionHelpFormatter',
00073 'RawTextHelpFormatter',
00074 'Namespace',
00075 'Action',
00076 'ONE_OR_MORE',
00077 'OPTIONAL',
00078 'PARSER',
00079 'REMAINDER',
00080 'SUPPRESS',
00081 'ZERO_OR_MORE',
00082 ]
00083
00084
00085 import copy as _copy
00086 import os as _os
00087 import re as _re
00088 import sys as _sys
00089 import textwrap as _textwrap
00090
00091 from gettext import gettext as _
00092
00093
00094 def _callable(obj):
00095 return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
00096
00097
00098 SUPPRESS = '==SUPPRESS=='
00099
00100 OPTIONAL = '?'
00101 ZERO_OR_MORE = '*'
00102 ONE_OR_MORE = '+'
00103 PARSER = 'A...'
00104 REMAINDER = '...'
00105 _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
00106
00107
00108
00109
00110
00111 class _AttributeHolder(object):
00112 """Abstract base class that provides __repr__.
00113
00114 The __repr__ method returns a string in the format::
00115 ClassName(attr=name, attr=name, ...)
00116 The attributes are determined either by a class-level attribute,
00117 '_kwarg_names', or by inspecting the instance __dict__.
00118 """
00119
00120 def __repr__(self):
00121 type_name = type(self).__name__
00122 arg_strings = []
00123 for arg in self._get_args():
00124 arg_strings.append(repr(arg))
00125 for name, value in self._get_kwargs():
00126 arg_strings.append('%s=%r' % (name, value))
00127 return '%s(%s)' % (type_name, ', '.join(arg_strings))
00128
00129 def _get_kwargs(self):
00130 return sorted(self.__dict__.items())
00131
00132 def _get_args(self):
00133 return []
00134
00135
00136 def _ensure_value(namespace, name, value):
00137 if getattr(namespace, name, None) is None:
00138 setattr(namespace, name, value)
00139 return getattr(namespace, name)
00140
00141
00142
00143
00144
00145
00146 class HelpFormatter(object):
00147 """Formatter for generating usage messages and argument help strings.
00148
00149 Only the name of this class is considered a public API. All the methods
00150 provided by the class are considered an implementation detail.
00151 """
00152
00153 def __init__(self,
00154 prog,
00155 indent_increment=2,
00156 max_help_position=24,
00157 width=None):
00158
00159
00160 if width is None:
00161 try:
00162 width = int(_os.environ['COLUMNS'])
00163 except (KeyError, ValueError):
00164 width = 80
00165 width -= 2
00166
00167 self._prog = prog
00168 self._indent_increment = indent_increment
00169 self._max_help_position = max_help_position
00170 self._width = width
00171
00172 self._current_indent = 0
00173 self._level = 0
00174 self._action_max_length = 0
00175
00176 self._root_section = self._Section(self, None)
00177 self._current_section = self._root_section
00178
00179 self._whitespace_matcher = _re.compile(r'\s+')
00180 self._long_break_matcher = _re.compile(r'\n\n\n+')
00181
00182
00183
00184
00185 def _indent(self):
00186 self._current_indent += self._indent_increment
00187 self._level += 1
00188
00189 def _dedent(self):
00190 self._current_indent -= self._indent_increment
00191 assert self._current_indent >= 0, 'Indent decreased below 0.'
00192 self._level -= 1
00193
00194 class _Section(object):
00195
00196 def __init__(self, formatter, parent, heading=None):
00197 self.formatter = formatter
00198 self.parent = parent
00199 self.heading = heading
00200 self.items = []
00201
00202 def format_help(self):
00203
00204 if self.parent is not None:
00205 self.formatter._indent()
00206 join = self.formatter._join_parts
00207 for func, args in self.items:
00208 func(*args)
00209 item_help = join([func(*args) for func, args in self.items])
00210 if self.parent is not None:
00211 self.formatter._dedent()
00212
00213
00214 if not item_help:
00215 return ''
00216
00217
00218 if self.heading is not SUPPRESS and self.heading is not None:
00219 current_indent = self.formatter._current_indent
00220 heading = '%*s%s:\n' % (current_indent, '', self.heading)
00221 else:
00222 heading = ''
00223
00224
00225 return join(['\n', heading, item_help, '\n'])
00226
00227 def _add_item(self, func, args):
00228 self._current_section.items.append((func, args))
00229
00230
00231
00232
00233 def start_section(self, heading):
00234 self._indent()
00235 section = self._Section(self, self._current_section, heading)
00236 self._add_item(section.format_help, [])
00237 self._current_section = section
00238
00239 def end_section(self):
00240 self._current_section = self._current_section.parent
00241 self._dedent()
00242
00243 def add_text(self, text):
00244 if text is not SUPPRESS and text is not None:
00245 self._add_item(self._format_text, [text])
00246
00247 def add_usage(self, usage, actions, groups, prefix=None):
00248 if usage is not SUPPRESS:
00249 args = usage, actions, groups, prefix
00250 self._add_item(self._format_usage, args)
00251
00252 def add_argument(self, action):
00253 if action.help is not SUPPRESS:
00254
00255
00256 get_invocation = self._format_action_invocation
00257 invocations = [get_invocation(action)]
00258 for subaction in self._iter_indented_subactions(action):
00259 invocations.append(get_invocation(subaction))
00260
00261
00262 invocation_length = max([len(s) for s in invocations])
00263 action_length = invocation_length + self._current_indent
00264 self._action_max_length = max(self._action_max_length,
00265 action_length)
00266
00267
00268 self._add_item(self._format_action, [action])
00269
00270 def add_arguments(self, actions):
00271 for action in actions:
00272 self.add_argument(action)
00273
00274
00275
00276
00277 def format_help(self):
00278 help = self._root_section.format_help()
00279 if help:
00280 help = self._long_break_matcher.sub('\n\n', help)
00281 help = help.strip('\n') + '\n'
00282 return help
00283
00284 def _join_parts(self, part_strings):
00285 return ''.join([part
00286 for part in part_strings
00287 if part and part is not SUPPRESS])
00288
00289 def _format_usage(self, usage, actions, groups, prefix):
00290 if prefix is None:
00291 prefix = _('usage: ')
00292
00293
00294 if usage is not None:
00295 usage = usage % dict(prog=self._prog)
00296
00297
00298 elif usage is None and not actions:
00299 usage = '%(prog)s' % dict(prog=self._prog)
00300
00301
00302 elif usage is None:
00303 prog = '%(prog)s' % dict(prog=self._prog)
00304
00305
00306 optionals = []
00307 positionals = []
00308 for action in actions:
00309 if action.option_strings:
00310 optionals.append(action)
00311 else:
00312 positionals.append(action)
00313
00314
00315 format = self._format_actions_usage
00316 action_usage = format(optionals + positionals, groups)
00317 usage = ' '.join([s for s in [prog, action_usage] if s])
00318
00319
00320 text_width = self._width - self._current_indent
00321 if len(prefix) + len(usage) > text_width:
00322
00323
00324 part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
00325 opt_usage = format(optionals, groups)
00326 pos_usage = format(positionals, groups)
00327 opt_parts = _re.findall(part_regexp, opt_usage)
00328 pos_parts = _re.findall(part_regexp, pos_usage)
00329 assert ' '.join(opt_parts) == opt_usage
00330 assert ' '.join(pos_parts) == pos_usage
00331
00332
00333 def get_lines(parts, indent, prefix=None):
00334 lines = []
00335 line = []
00336 if prefix is not None:
00337 line_len = len(prefix) - 1
00338 else:
00339 line_len = len(indent) - 1
00340 for part in parts:
00341 if line_len + 1 + len(part) > text_width:
00342 lines.append(indent + ' '.join(line))
00343 line = []
00344 line_len = len(indent) - 1
00345 line.append(part)
00346 line_len += len(part) + 1
00347 if line:
00348 lines.append(indent + ' '.join(line))
00349 if prefix is not None:
00350 lines[0] = lines[0][len(indent):]
00351 return lines
00352
00353
00354 if len(prefix) + len(prog) <= 0.75 * text_width:
00355 indent = ' ' * (len(prefix) + len(prog) + 1)
00356 if opt_parts:
00357 lines = get_lines([prog] + opt_parts, indent, prefix)
00358 lines.extend(get_lines(pos_parts, indent))
00359 elif pos_parts:
00360 lines = get_lines([prog] + pos_parts, indent, prefix)
00361 else:
00362 lines = [prog]
00363
00364
00365 else:
00366 indent = ' ' * len(prefix)
00367 parts = opt_parts + pos_parts
00368 lines = get_lines(parts, indent)
00369 if len(lines) > 1:
00370 lines = []
00371 lines.extend(get_lines(opt_parts, indent))
00372 lines.extend(get_lines(pos_parts, indent))
00373 lines = [prog] + lines
00374
00375
00376 usage = '\n'.join(lines)
00377
00378
00379 return '%s%s\n\n' % (prefix, usage)
00380
00381 def _format_actions_usage(self, actions, groups):
00382
00383 group_actions = set()
00384 inserts = {}
00385 for group in groups:
00386 try:
00387 start = actions.index(group._group_actions[0])
00388 except ValueError:
00389 continue
00390 else:
00391 end = start + len(group._group_actions)
00392 if actions[start:end] == group._group_actions:
00393 for action in group._group_actions:
00394 group_actions.add(action)
00395 if not group.required:
00396 if start in inserts:
00397 inserts[start] += ' ['
00398 else:
00399 inserts[start] = '['
00400 inserts[end] = ']'
00401 else:
00402 if start in inserts:
00403 inserts[start] += ' ('
00404 else:
00405 inserts[start] = '('
00406 inserts[end] = ')'
00407 for i in range(start + 1, end):
00408 inserts[i] = '|'
00409
00410
00411 parts = []
00412 for i, action in enumerate(actions):
00413
00414
00415
00416 if action.help is SUPPRESS:
00417 parts.append(None)
00418 if inserts.get(i) == '|':
00419 inserts.pop(i)
00420 elif inserts.get(i + 1) == '|':
00421 inserts.pop(i + 1)
00422
00423
00424 elif not action.option_strings:
00425 part = self._format_args(action, action.dest)
00426
00427
00428 if action in group_actions:
00429 if part[0] == '[' and part[-1] == ']':
00430 part = part[1:-1]
00431
00432
00433 parts.append(part)
00434
00435
00436 else:
00437 option_string = action.option_strings[0]
00438
00439
00440
00441 if action.nargs == 0:
00442 part = '%s' % option_string
00443
00444
00445
00446 else:
00447 default = action.dest.upper()
00448 args_string = self._format_args(action, default)
00449 part = '%s %s' % (option_string, args_string)
00450
00451
00452 if not action.required and action not in group_actions:
00453 part = '[%s]' % part
00454
00455
00456 parts.append(part)
00457
00458
00459 for i in sorted(inserts, reverse=True):
00460 parts[i:i] = [inserts[i]]
00461
00462
00463 text = ' '.join([item for item in parts if item is not None])
00464
00465
00466 open = r'[\[(]'
00467 close = r'[\])]'
00468 text = _re.sub(r'(%s) ' % open, r'\1', text)
00469 text = _re.sub(r' (%s)' % close, r'\1', text)
00470 text = _re.sub(r'%s *%s' % (open, close), r'', text)
00471 text = _re.sub(r'\(([^|]*)\)', r'\1', text)
00472 text = text.strip()
00473
00474
00475 return text
00476
00477 def _format_text(self, text):
00478 if '%(prog)' in text:
00479 text = text % dict(prog=self._prog)
00480 text_width = self._width - self._current_indent
00481 indent = ' ' * self._current_indent
00482 return self._fill_text(text, text_width, indent) + '\n\n'
00483
00484 def _format_action(self, action):
00485
00486 help_position = min(self._action_max_length + 2,
00487 self._max_help_position)
00488 help_width = self._width - help_position
00489 action_width = help_position - self._current_indent - 2
00490 action_header = self._format_action_invocation(action)
00491
00492
00493 if not action.help:
00494 tup = self._current_indent, '', action_header
00495 action_header = '%*s%s\n' % tup
00496
00497
00498 elif len(action_header) <= action_width:
00499 tup = self._current_indent, '', action_width, action_header
00500 action_header = '%*s%-*s ' % tup
00501 indent_first = 0
00502
00503
00504 else:
00505 tup = self._current_indent, '', action_header
00506 action_header = '%*s%s\n' % tup
00507 indent_first = help_position
00508
00509
00510 parts = [action_header]
00511
00512
00513 if action.help:
00514 help_text = self._expand_help(action)
00515 help_lines = self._split_lines(help_text, help_width)
00516 parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
00517 for line in help_lines[1:]:
00518 parts.append('%*s%s\n' % (help_position, '', line))
00519
00520
00521 elif not action_header.endswith('\n'):
00522 parts.append('\n')
00523
00524
00525 for subaction in self._iter_indented_subactions(action):
00526 parts.append(self._format_action(subaction))
00527
00528
00529 return self._join_parts(parts)
00530
00531 def _format_action_invocation(self, action):
00532 if not action.option_strings:
00533 metavar, = self._metavar_formatter(action, action.dest)(1)
00534 return metavar
00535
00536 else:
00537 parts = []
00538
00539
00540
00541 if action.nargs == 0:
00542 parts.extend(action.option_strings)
00543
00544
00545
00546 else:
00547 default = action.dest.upper()
00548 args_string = self._format_args(action, default)
00549 for option_string in action.option_strings:
00550 parts.append('%s %s' % (option_string, args_string))
00551
00552 return ', '.join(parts)
00553
00554 def _metavar_formatter(self, action, default_metavar):
00555 if action.metavar is not None:
00556 result = action.metavar
00557 elif action.choices is not None:
00558 choice_strs = [str(choice) for choice in action.choices]
00559 result = '{%s}' % ','.join(choice_strs)
00560 else:
00561 result = default_metavar
00562
00563 def format(tuple_size):
00564 if isinstance(result, tuple):
00565 return result
00566 else:
00567 return (result, ) * tuple_size
00568 return format
00569
00570 def _format_args(self, action, default_metavar):
00571 get_metavar = self._metavar_formatter(action, default_metavar)
00572 if action.nargs is None:
00573 result = '%s' % get_metavar(1)
00574 elif action.nargs == OPTIONAL:
00575 result = '[%s]' % get_metavar(1)
00576 elif action.nargs == ZERO_OR_MORE:
00577 result = '[%s [%s ...]]' % get_metavar(2)
00578 elif action.nargs == ONE_OR_MORE:
00579 result = '%s [%s ...]' % get_metavar(2)
00580 elif action.nargs == REMAINDER:
00581 result = '...'
00582 elif action.nargs == PARSER:
00583 result = '%s ...' % get_metavar(1)
00584 else:
00585 formats = ['%s' for _ in range(action.nargs)]
00586 result = ' '.join(formats) % get_metavar(action.nargs)
00587 return result
00588
00589 def _expand_help(self, action):
00590 params = dict(vars(action), prog=self._prog)
00591 for name in list(params):
00592 if params[name] is SUPPRESS:
00593 del params[name]
00594 for name in list(params):
00595 if hasattr(params[name], '__name__'):
00596 params[name] = params[name].__name__
00597 if params.get('choices') is not None:
00598 choices_str = ', '.join([str(c) for c in params['choices']])
00599 params['choices'] = choices_str
00600 return self._get_help_string(action) % params
00601
00602 def _iter_indented_subactions(self, action):
00603 try:
00604 get_subactions = action._get_subactions
00605 except AttributeError:
00606 pass
00607 else:
00608 self._indent()
00609 for subaction in get_subactions():
00610 yield subaction
00611 self._dedent()
00612
00613 def _split_lines(self, text, width):
00614 text = self._whitespace_matcher.sub(' ', text).strip()
00615 return _textwrap.wrap(text, width)
00616
00617 def _fill_text(self, text, width, indent):
00618 text = self._whitespace_matcher.sub(' ', text).strip()
00619 return _textwrap.fill(text, width, initial_indent=indent,
00620 subsequent_indent=indent)
00621
00622 def _get_help_string(self, action):
00623 return action.help
00624
00625
00626 class RawDescriptionHelpFormatter(HelpFormatter):
00627 """Help message formatter which retains any formatting in descriptions.
00628
00629 Only the name of this class is considered a public API. All the methods
00630 provided by the class are considered an implementation detail.
00631 """
00632
00633 def _fill_text(self, text, width, indent):
00634 return ''.join([indent + line for line in text.splitlines(True)])
00635
00636
00637 class RawTextHelpFormatter(RawDescriptionHelpFormatter):
00638 """Help message formatter which retains formatting of all help text.
00639
00640 Only the name of this class is considered a public API. All the methods
00641 provided by the class are considered an implementation detail.
00642 """
00643
00644 def _split_lines(self, text, width):
00645 return text.splitlines()
00646
00647
00648 class ArgumentDefaultsHelpFormatter(HelpFormatter):
00649 """Help message formatter which adds default values to argument help.
00650
00651 Only the name of this class is considered a public API. All the methods
00652 provided by the class are considered an implementation detail.
00653 """
00654
00655 def _get_help_string(self, action):
00656 help = action.help
00657 if '%(default)' not in action.help:
00658 if action.default is not SUPPRESS:
00659 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
00660 if action.option_strings or action.nargs in defaulting_nargs:
00661 help += ' (default: %(default)s)'
00662 return help
00663
00664
00665
00666
00667
00668
00669 def _get_action_name(argument):
00670 if argument is None:
00671 return None
00672 elif argument.option_strings:
00673 return '/'.join(argument.option_strings)
00674 elif argument.metavar not in (None, SUPPRESS):
00675 return argument.metavar
00676 elif argument.dest not in (None, SUPPRESS):
00677 return argument.dest
00678 else:
00679 return None
00680
00681
00682 class ArgumentError(Exception):
00683 """An error from creating or using an argument (optional or positional).
00684
00685 The string value of this exception is the message, augmented with
00686 information about the argument that caused it.
00687 """
00688
00689 def __init__(self, argument, message):
00690 self.argument_name = _get_action_name(argument)
00691 self.message = message
00692
00693 def __str__(self):
00694 if self.argument_name is None:
00695 format = '%(message)s'
00696 else:
00697 format = 'argument %(argument_name)s: %(message)s'
00698 return format % dict(message=self.message,
00699 argument_name=self.argument_name)
00700
00701
00702 class ArgumentTypeError(Exception):
00703 """An error from trying to convert a command line string to a type."""
00704 pass
00705
00706
00707
00708
00709
00710
00711 class Action(_AttributeHolder):
00712 """Information about how to convert command line strings to Python objects.
00713
00714 Action objects are used by an ArgumentParser to represent the information
00715 needed to parse a single argument from one or more strings from the
00716 command line. The keyword arguments to the Action constructor are also
00717 all attributes of Action instances.
00718
00719 Keyword Arguments:
00720
00721 - option_strings -- A list of command-line option strings which
00722 should be associated with this action.
00723
00724 - dest -- The name of the attribute to hold the created object(s)
00725
00726 - nargs -- The number of command-line arguments that should be
00727 consumed. By default, one argument will be consumed and a single
00728 value will be produced. Other values include:
00729 - N (an integer) consumes N arguments (and produces a list)
00730 - '?' consumes zero or one arguments
00731 - '*' consumes zero or more arguments (and produces a list)
00732 - '+' consumes one or more arguments (and produces a list)
00733 Note that the difference between the default and nargs=1 is that
00734 with the default, a single value will be produced, while with
00735 nargs=1, a list containing a single value will be produced.
00736
00737 - const -- The value to be produced if the option is specified and the
00738 option uses an action that takes no values.
00739
00740 - default -- The value to be produced if the option is not specified.
00741
00742 - type -- The type which the command-line arguments should be converted
00743 to, should be one of 'string', 'int', 'float', 'complex' or a
00744 callable object that accepts a single string argument. If None,
00745 'string' is assumed.
00746
00747 - choices -- A container of values that should be allowed. If not None,
00748 after a command-line argument has been converted to the appropriate
00749 type, an exception will be raised if it is not a member of this
00750 collection.
00751
00752 - required -- True if the action must always be specified at the
00753 command line. This is only meaningful for optional command-line
00754 arguments.
00755
00756 - help -- The help string describing the argument.
00757
00758 - metavar -- The name to be used for the option's argument with the
00759 help string. If None, the 'dest' value will be used as the name.
00760 """
00761
00762 def __init__(self,
00763 option_strings,
00764 dest,
00765 nargs=None,
00766 const=None,
00767 default=None,
00768 type=None,
00769 choices=None,
00770 required=False,
00771 help=None,
00772 metavar=None):
00773 self.option_strings = option_strings
00774 self.dest = dest
00775 self.nargs = nargs
00776 self.const = const
00777 self.default = default
00778 self.type = type
00779 self.choices = choices
00780 self.required = required
00781 self.help = help
00782 self.metavar = metavar
00783
00784 def _get_kwargs(self):
00785 names = [
00786 'option_strings',
00787 'dest',
00788 'nargs',
00789 'const',
00790 'default',
00791 'type',
00792 'choices',
00793 'help',
00794 'metavar',
00795 ]
00796 return [(name, getattr(self, name)) for name in names]
00797
00798 def __call__(self, parser, namespace, values, option_string=None):
00799 raise NotImplementedError(_('.__call__() not defined'))
00800
00801
00802 class _StoreAction(Action):
00803
00804 def __init__(self,
00805 option_strings,
00806 dest,
00807 nargs=None,
00808 const=None,
00809 default=None,
00810 type=None,
00811 choices=None,
00812 required=False,
00813 help=None,
00814 metavar=None):
00815 if nargs == 0:
00816 raise ValueError('nargs for store actions must be > 0; if you '
00817 'have nothing to store, actions such as store '
00818 'true or store const may be more appropriate')
00819 if const is not None and nargs != OPTIONAL:
00820 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
00821 super(_StoreAction, self).__init__(
00822 option_strings=option_strings,
00823 dest=dest,
00824 nargs=nargs,
00825 const=const,
00826 default=default,
00827 type=type,
00828 choices=choices,
00829 required=required,
00830 help=help,
00831 metavar=metavar)
00832
00833 def __call__(self, parser, namespace, values, option_string=None):
00834 setattr(namespace, self.dest, values)
00835
00836
00837 class _StoreConstAction(Action):
00838
00839 def __init__(self,
00840 option_strings,
00841 dest,
00842 const,
00843 default=None,
00844 required=False,
00845 help=None,
00846 metavar=None):
00847 super(_StoreConstAction, self).__init__(
00848 option_strings=option_strings,
00849 dest=dest,
00850 nargs=0,
00851 const=const,
00852 default=default,
00853 required=required,
00854 help=help)
00855
00856 def __call__(self, parser, namespace, values, option_string=None):
00857 setattr(namespace, self.dest, self.const)
00858
00859
00860 class _StoreTrueAction(_StoreConstAction):
00861
00862 def __init__(self,
00863 option_strings,
00864 dest,
00865 default=False,
00866 required=False,
00867 help=None):
00868 super(_StoreTrueAction, self).__init__(
00869 option_strings=option_strings,
00870 dest=dest,
00871 const=True,
00872 default=default,
00873 required=required,
00874 help=help)
00875
00876
00877 class _StoreFalseAction(_StoreConstAction):
00878
00879 def __init__(self,
00880 option_strings,
00881 dest,
00882 default=True,
00883 required=False,
00884 help=None):
00885 super(_StoreFalseAction, self).__init__(
00886 option_strings=option_strings,
00887 dest=dest,
00888 const=False,
00889 default=default,
00890 required=required,
00891 help=help)
00892
00893
00894 class _AppendAction(Action):
00895
00896 def __init__(self,
00897 option_strings,
00898 dest,
00899 nargs=None,
00900 const=None,
00901 default=None,
00902 type=None,
00903 choices=None,
00904 required=False,
00905 help=None,
00906 metavar=None):
00907 if nargs == 0:
00908 raise ValueError('nargs for append actions must be > 0; if arg '
00909 'strings are not supplying the value to append, '
00910 'the append const action may be more appropriate')
00911 if const is not None and nargs != OPTIONAL:
00912 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
00913 super(_AppendAction, self).__init__(
00914 option_strings=option_strings,
00915 dest=dest,
00916 nargs=nargs,
00917 const=const,
00918 default=default,
00919 type=type,
00920 choices=choices,
00921 required=required,
00922 help=help,
00923 metavar=metavar)
00924
00925 def __call__(self, parser, namespace, values, option_string=None):
00926 items = _copy.copy(_ensure_value(namespace, self.dest, []))
00927 items.append(values)
00928 setattr(namespace, self.dest, items)
00929
00930
00931 class _AppendConstAction(Action):
00932
00933 def __init__(self,
00934 option_strings,
00935 dest,
00936 const,
00937 default=None,
00938 required=False,
00939 help=None,
00940 metavar=None):
00941 super(_AppendConstAction, self).__init__(
00942 option_strings=option_strings,
00943 dest=dest,
00944 nargs=0,
00945 const=const,
00946 default=default,
00947 required=required,
00948 help=help,
00949 metavar=metavar)
00950
00951 def __call__(self, parser, namespace, values, option_string=None):
00952 items = _copy.copy(_ensure_value(namespace, self.dest, []))
00953 items.append(self.const)
00954 setattr(namespace, self.dest, items)
00955
00956
00957 class _CountAction(Action):
00958
00959 def __init__(self,
00960 option_strings,
00961 dest,
00962 default=None,
00963 required=False,
00964 help=None):
00965 super(_CountAction, self).__init__(
00966 option_strings=option_strings,
00967 dest=dest,
00968 nargs=0,
00969 default=default,
00970 required=required,
00971 help=help)
00972
00973 def __call__(self, parser, namespace, values, option_string=None):
00974 new_count = _ensure_value(namespace, self.dest, 0) + 1
00975 setattr(namespace, self.dest, new_count)
00976
00977
00978 class _HelpAction(Action):
00979
00980 def __init__(self,
00981 option_strings,
00982 dest=SUPPRESS,
00983 default=SUPPRESS,
00984 help=None):
00985 super(_HelpAction, self).__init__(
00986 option_strings=option_strings,
00987 dest=dest,
00988 default=default,
00989 nargs=0,
00990 help=help)
00991
00992 def __call__(self, parser, namespace, values, option_string=None):
00993 parser.print_help()
00994 parser.exit()
00995
00996
00997 class _VersionAction(Action):
00998
00999 def __init__(self,
01000 option_strings,
01001 version=None,
01002 dest=SUPPRESS,
01003 default=SUPPRESS,
01004 help="show program's version number and exit"):
01005 super(_VersionAction, self).__init__(
01006 option_strings=option_strings,
01007 dest=dest,
01008 default=default,
01009 nargs=0,
01010 help=help)
01011 self.version = version
01012
01013 def __call__(self, parser, namespace, values, option_string=None):
01014 version = self.version
01015 if version is None:
01016 version = parser.version
01017 formatter = parser._get_formatter()
01018 formatter.add_text(version)
01019 parser.exit(message=formatter.format_help())
01020
01021
01022 class _SubParsersAction(Action):
01023
01024 class _ChoicesPseudoAction(Action):
01025
01026 def __init__(self, name, help):
01027 sup = super(_SubParsersAction._ChoicesPseudoAction, self)
01028 sup.__init__(option_strings=[], dest=name, help=help)
01029
01030 def __init__(self,
01031 option_strings,
01032 prog,
01033 parser_class,
01034 dest=SUPPRESS,
01035 help=None,
01036 metavar=None):
01037
01038 self._prog_prefix = prog
01039 self._parser_class = parser_class
01040 self._name_parser_map = {}
01041 self._choices_actions = []
01042
01043 super(_SubParsersAction, self).__init__(
01044 option_strings=option_strings,
01045 dest=dest,
01046 nargs=PARSER,
01047 choices=self._name_parser_map,
01048 help=help,
01049 metavar=metavar)
01050
01051 def add_parser(self, name, **kwargs):
01052
01053 if kwargs.get('prog') is None:
01054 kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
01055
01056
01057 if 'help' in kwargs:
01058 help = kwargs.pop('help')
01059 choice_action = self._ChoicesPseudoAction(name, help)
01060 self._choices_actions.append(choice_action)
01061
01062
01063 parser = self._parser_class(**kwargs)
01064 self._name_parser_map[name] = parser
01065 return parser
01066
01067 def _get_subactions(self):
01068 return self._choices_actions
01069
01070 def __call__(self, parser, namespace, values, option_string=None):
01071 parser_name = values[0]
01072 arg_strings = values[1:]
01073
01074
01075 if self.dest is not SUPPRESS:
01076 setattr(namespace, self.dest, parser_name)
01077
01078
01079 try:
01080 parser = self._name_parser_map[parser_name]
01081 except KeyError:
01082 tup = parser_name, ', '.join(self._name_parser_map)
01083 msg = _('unknown parser %r (choices: %s)' % tup)
01084 raise ArgumentError(self, msg)
01085
01086
01087
01088
01089 namespace, arg_strings = parser.parse_known_args(arg_strings, namespace)
01090 if arg_strings:
01091 vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
01092 getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
01093
01094
01095
01096
01097
01098
01099 class FileType(object):
01100 """Factory for creating file object types
01101
01102 Instances of FileType are typically passed as type= arguments to the
01103 ArgumentParser add_argument() method.
01104
01105 Keyword Arguments:
01106 - mode -- A string indicating how the file is to be opened. Accepts the
01107 same values as the builtin open() function.
01108 - bufsize -- The file's desired buffer size. Accepts the same values as
01109 the builtin open() function.
01110 """
01111
01112 def __init__(self, mode='r', bufsize=None):
01113 self._mode = mode
01114 self._bufsize = bufsize
01115
01116 def __call__(self, string):
01117
01118 if string == '-':
01119 if 'r' in self._mode:
01120 return _sys.stdin
01121 elif 'w' in self._mode:
01122 return _sys.stdout
01123 else:
01124 msg = _('argument "-" with mode %r' % self._mode)
01125 raise ValueError(msg)
01126
01127
01128 if self._bufsize:
01129 return open(string, self._mode, self._bufsize)
01130 else:
01131 return open(string, self._mode)
01132
01133 def __repr__(self):
01134 args = [self._mode, self._bufsize]
01135 args_str = ', '.join([repr(arg) for arg in args if arg is not None])
01136 return '%s(%s)' % (type(self).__name__, args_str)
01137
01138
01139
01140
01141
01142 class Namespace(_AttributeHolder):
01143 """Simple object for storing attributes.
01144
01145 Implements equality by attribute names and values, and provides a simple
01146 string representation.
01147 """
01148
01149 def __init__(self, **kwargs):
01150 for name in kwargs:
01151 setattr(self, name, kwargs[name])
01152
01153 __hash__ = None
01154
01155 def __eq__(self, other):
01156 return vars(self) == vars(other)
01157
01158 def __ne__(self, other):
01159 return not (self == other)
01160
01161 def __contains__(self, key):
01162 return key in self.__dict__
01163
01164
01165 class _ActionsContainer(object):
01166
01167 def __init__(self,
01168 description,
01169 prefix_chars,
01170 argument_default,
01171 conflict_handler):
01172 super(_ActionsContainer, self).__init__()
01173
01174 self.description = description
01175 self.argument_default = argument_default
01176 self.prefix_chars = prefix_chars
01177 self.conflict_handler = conflict_handler
01178
01179
01180 self._registries = {}
01181
01182
01183 self.register('action', None, _StoreAction)
01184 self.register('action', 'store', _StoreAction)
01185 self.register('action', 'store_const', _StoreConstAction)
01186 self.register('action', 'store_true', _StoreTrueAction)
01187 self.register('action', 'store_false', _StoreFalseAction)
01188 self.register('action', 'append', _AppendAction)
01189 self.register('action', 'append_const', _AppendConstAction)
01190 self.register('action', 'count', _CountAction)
01191 self.register('action', 'help', _HelpAction)
01192 self.register('action', 'version', _VersionAction)
01193 self.register('action', 'parsers', _SubParsersAction)
01194
01195
01196 self._get_handler()
01197
01198
01199 self._actions = []
01200 self._option_string_actions = {}
01201
01202
01203 self._action_groups = []
01204 self._mutually_exclusive_groups = []
01205
01206
01207 self._defaults = {}
01208
01209
01210 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
01211
01212
01213
01214 self._has_negative_number_optionals = []
01215
01216
01217
01218
01219 def register(self, registry_name, value, object):
01220 registry = self._registries.setdefault(registry_name, {})
01221 registry[value] = object
01222
01223 def _registry_get(self, registry_name, value, default=None):
01224 return self._registries[registry_name].get(value, default)
01225
01226
01227
01228
01229 def set_defaults(self, **kwargs):
01230 self._defaults.update(kwargs)
01231
01232
01233
01234 for action in self._actions:
01235 if action.dest in kwargs:
01236 action.default = kwargs[action.dest]
01237
01238 def get_default(self, dest):
01239 for action in self._actions:
01240 if action.dest == dest and action.default is not None:
01241 return action.default
01242 return self._defaults.get(dest, None)
01243
01244
01245
01246
01247
01248 def add_argument(self, *args, **kwargs):
01249 """
01250 add_argument(dest, ..., name=value, ...)
01251 add_argument(option_string, option_string, ..., name=value, ...)
01252 """
01253
01254
01255
01256
01257 chars = self.prefix_chars
01258 if not args or len(args) == 1 and args[0][0] not in chars:
01259 if args and 'dest' in kwargs:
01260 raise ValueError('dest supplied twice for positional argument')
01261 kwargs = self._get_positional_kwargs(*args, **kwargs)
01262
01263
01264 else:
01265 kwargs = self._get_optional_kwargs(*args, **kwargs)
01266
01267
01268 if 'default' not in kwargs:
01269 dest = kwargs['dest']
01270 if dest in self._defaults:
01271 kwargs['default'] = self._defaults[dest]
01272 elif self.argument_default is not None:
01273 kwargs['default'] = self.argument_default
01274
01275
01276 action_class = self._pop_action_class(kwargs)
01277 if not _callable(action_class):
01278 raise ValueError('unknown action "%s"' % action_class)
01279 action = action_class(**kwargs)
01280
01281
01282 type_func = self._registry_get('type', action.type, action.type)
01283 if not _callable(type_func):
01284 raise ValueError('%r is not callable' % type_func)
01285
01286 return self._add_action(action)
01287
01288 def add_argument_group(self, *args, **kwargs):
01289 group = _ArgumentGroup(self, *args, **kwargs)
01290 self._action_groups.append(group)
01291 return group
01292
01293 def add_mutually_exclusive_group(self, **kwargs):
01294 group = _MutuallyExclusiveGroup(self, **kwargs)
01295 self._mutually_exclusive_groups.append(group)
01296 return group
01297
01298 def _add_action(self, action):
01299
01300 self._check_conflict(action)
01301
01302
01303 self._actions.append(action)
01304 action.container = self
01305
01306
01307 for option_string in action.option_strings:
01308 self._option_string_actions[option_string] = action
01309
01310
01311 for option_string in action.option_strings:
01312 if self._negative_number_matcher.match(option_string):
01313 if not self._has_negative_number_optionals:
01314 self._has_negative_number_optionals.append(True)
01315
01316
01317 return action
01318
01319 def _remove_action(self, action):
01320 self._actions.remove(action)
01321
01322 def _add_container_actions(self, container):
01323
01324 title_group_map = {}
01325 for group in self._action_groups:
01326 if group.title in title_group_map:
01327 msg = _('cannot merge actions - two groups are named %r')
01328 raise ValueError(msg % (group.title))
01329 title_group_map[group.title] = group
01330
01331
01332 group_map = {}
01333 for group in container._action_groups:
01334
01335
01336
01337 if group.title not in title_group_map:
01338 title_group_map[group.title] = self.add_argument_group(
01339 title=group.title,
01340 description=group.description,
01341 conflict_handler=group.conflict_handler)
01342
01343
01344 for action in group._group_actions:
01345 group_map[action] = title_group_map[group.title]
01346
01347
01348
01349
01350 for group in container._mutually_exclusive_groups:
01351 mutex_group = self.add_mutually_exclusive_group(
01352 required=group.required)
01353
01354
01355 for action in group._group_actions:
01356 group_map[action] = mutex_group
01357
01358
01359 for action in container._actions:
01360 group_map.get(action, self)._add_action(action)
01361
01362 def _get_positional_kwargs(self, dest, **kwargs):
01363
01364 if 'required' in kwargs:
01365 msg = _("'required' is an invalid argument for positionals")
01366 raise TypeError(msg)
01367
01368
01369
01370 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
01371 kwargs['required'] = True
01372 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
01373 kwargs['required'] = True
01374
01375
01376 return dict(kwargs, dest=dest, option_strings=[])
01377
01378 def _get_optional_kwargs(self, *args, **kwargs):
01379
01380 option_strings = []
01381 long_option_strings = []
01382 for option_string in args:
01383
01384 if not option_string[0] in self.prefix_chars:
01385 msg = _('invalid option string %r: '
01386 'must start with a character %r')
01387 tup = option_string, self.prefix_chars
01388 raise ValueError(msg % tup)
01389
01390
01391 option_strings.append(option_string)
01392 if option_string[0] in self.prefix_chars:
01393 if len(option_string) > 1:
01394 if option_string[1] in self.prefix_chars:
01395 long_option_strings.append(option_string)
01396
01397
01398 dest = kwargs.pop('dest', None)
01399 if dest is None:
01400 if long_option_strings:
01401 dest_option_string = long_option_strings[0]
01402 else:
01403 dest_option_string = option_strings[0]
01404 dest = dest_option_string.lstrip(self.prefix_chars)
01405 if not dest:
01406 msg = _('dest= is required for options like %r')
01407 raise ValueError(msg % option_string)
01408 dest = dest.replace('-', '_')
01409
01410
01411 return dict(kwargs, dest=dest, option_strings=option_strings)
01412
01413 def _pop_action_class(self, kwargs, default=None):
01414 action = kwargs.pop('action', default)
01415 return self._registry_get('action', action, action)
01416
01417 def _get_handler(self):
01418
01419 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
01420 try:
01421 return getattr(self, handler_func_name)
01422 except AttributeError:
01423 msg = _('invalid conflict_resolution value: %r')
01424 raise ValueError(msg % self.conflict_handler)
01425
01426 def _check_conflict(self, action):
01427
01428
01429 confl_optionals = []
01430 for option_string in action.option_strings:
01431 if option_string in self._option_string_actions:
01432 confl_optional = self._option_string_actions[option_string]
01433 confl_optionals.append((option_string, confl_optional))
01434
01435
01436 if confl_optionals:
01437 conflict_handler = self._get_handler()
01438 conflict_handler(action, confl_optionals)
01439
01440 def _handle_conflict_error(self, action, conflicting_actions):
01441 message = _('conflicting option string(s): %s')
01442 conflict_string = ', '.join([option_string
01443 for option_string, action
01444 in conflicting_actions])
01445 raise ArgumentError(action, message % conflict_string)
01446
01447 def _handle_conflict_resolve(self, action, conflicting_actions):
01448
01449
01450 for option_string, action in conflicting_actions:
01451
01452
01453 action.option_strings.remove(option_string)
01454 self._option_string_actions.pop(option_string, None)
01455
01456
01457
01458 if not action.option_strings:
01459 action.container._remove_action(action)
01460
01461
01462 class _ArgumentGroup(_ActionsContainer):
01463
01464 def __init__(self, container, title=None, description=None, **kwargs):
01465
01466 update = kwargs.setdefault
01467 update('conflict_handler', container.conflict_handler)
01468 update('prefix_chars', container.prefix_chars)
01469 update('argument_default', container.argument_default)
01470 super_init = super(_ArgumentGroup, self).__init__
01471 super_init(description=description, **kwargs)
01472
01473
01474 self.title = title
01475 self._group_actions = []
01476
01477
01478 self._registries = container._registries
01479 self._actions = container._actions
01480 self._option_string_actions = container._option_string_actions
01481 self._defaults = container._defaults
01482 self._has_negative_number_optionals = \
01483 container._has_negative_number_optionals
01484
01485 def _add_action(self, action):
01486 action = super(_ArgumentGroup, self)._add_action(action)
01487 self._group_actions.append(action)
01488 return action
01489
01490 def _remove_action(self, action):
01491 super(_ArgumentGroup, self)._remove_action(action)
01492 self._group_actions.remove(action)
01493
01494
01495 class _MutuallyExclusiveGroup(_ArgumentGroup):
01496
01497 def __init__(self, container, required=False):
01498 super(_MutuallyExclusiveGroup, self).__init__(container)
01499 self.required = required
01500 self._container = container
01501
01502 def _add_action(self, action):
01503 if action.required:
01504 msg = _('mutually exclusive arguments must be optional')
01505 raise ValueError(msg)
01506 action = self._container._add_action(action)
01507 self._group_actions.append(action)
01508 return action
01509
01510 def _remove_action(self, action):
01511 self._container._remove_action(action)
01512 self._group_actions.remove(action)
01513
01514
01515 class ArgumentParser(_AttributeHolder, _ActionsContainer):
01516 """Object for parsing command line strings into Python objects.
01517
01518 Keyword Arguments:
01519 - prog -- The name of the program (default: sys.argv[0])
01520 - usage -- A usage message (default: auto-generated from arguments)
01521 - description -- A description of what the program does
01522 - epilog -- Text following the argument descriptions
01523 - parents -- Parsers whose arguments should be copied into this one
01524 - formatter_class -- HelpFormatter class for printing help messages
01525 - prefix_chars -- Characters that prefix optional arguments
01526 - fromfile_prefix_chars -- Characters that prefix files containing
01527 additional arguments
01528 - argument_default -- The default value for all arguments
01529 - conflict_handler -- String indicating how to handle conflicts
01530 - add_help -- Add a -h/-help option
01531 """
01532
01533 def __init__(self,
01534 prog=None,
01535 usage=None,
01536 description=None,
01537 epilog=None,
01538 version=None,
01539 parents=[],
01540 formatter_class=HelpFormatter,
01541 prefix_chars='-',
01542 fromfile_prefix_chars=None,
01543 argument_default=None,
01544 conflict_handler='error',
01545 add_help=True):
01546
01547 if version is not None:
01548 import warnings
01549 warnings.warn(
01550 """The "version" argument to ArgumentParser is deprecated. """
01551 """Please use """
01552 """"add_argument(..., action='version', version="N", ...)" """
01553 """instead""", DeprecationWarning)
01554
01555 superinit = super(ArgumentParser, self).__init__
01556 superinit(description=description,
01557 prefix_chars=prefix_chars,
01558 argument_default=argument_default,
01559 conflict_handler=conflict_handler)
01560
01561
01562 if prog is None:
01563 prog = _os.path.basename(_sys.argv[0])
01564
01565 self.prog = prog
01566 self.usage = usage
01567 self.epilog = epilog
01568 self.version = version
01569 self.formatter_class = formatter_class
01570 self.fromfile_prefix_chars = fromfile_prefix_chars
01571 self.add_help = add_help
01572
01573 add_group = self.add_argument_group
01574 self._positionals = add_group(_('positional arguments'))
01575 self._optionals = add_group(_('optional arguments'))
01576 self._subparsers = None
01577
01578
01579 def identity(string):
01580 return string
01581 self.register('type', None, identity)
01582
01583
01584
01585 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
01586 if self.add_help:
01587 self.add_argument(
01588 default_prefix+'h', default_prefix*2+'help',
01589 action='help', default=SUPPRESS,
01590 help=_('show this help message and exit'))
01591 if self.version:
01592 self.add_argument(
01593 default_prefix+'v', default_prefix*2+'version',
01594 action='version', default=SUPPRESS,
01595 version=self.version,
01596 help=_("show program's version number and exit"))
01597
01598
01599 for parent in parents:
01600 self._add_container_actions(parent)
01601 try:
01602 defaults = parent._defaults
01603 except AttributeError:
01604 pass
01605 else:
01606 self._defaults.update(defaults)
01607
01608
01609
01610
01611 def _get_kwargs(self):
01612 names = [
01613 'prog',
01614 'usage',
01615 'description',
01616 'version',
01617 'formatter_class',
01618 'conflict_handler',
01619 'add_help',
01620 ]
01621 return [(name, getattr(self, name)) for name in names]
01622
01623
01624
01625
01626 def add_subparsers(self, **kwargs):
01627 if self._subparsers is not None:
01628 self.error(_('cannot have multiple subparser arguments'))
01629
01630
01631 kwargs.setdefault('parser_class', type(self))
01632
01633 if 'title' in kwargs or 'description' in kwargs:
01634 title = _(kwargs.pop('title', 'subcommands'))
01635 description = _(kwargs.pop('description', None))
01636 self._subparsers = self.add_argument_group(title, description)
01637 else:
01638 self._subparsers = self._positionals
01639
01640
01641
01642 if kwargs.get('prog') is None:
01643 formatter = self._get_formatter()
01644 positionals = self._get_positional_actions()
01645 groups = self._mutually_exclusive_groups
01646 formatter.add_usage(self.usage, positionals, groups, '')
01647 kwargs['prog'] = formatter.format_help().strip()
01648
01649
01650 parsers_class = self._pop_action_class(kwargs, 'parsers')
01651 action = parsers_class(option_strings=[], **kwargs)
01652 self._subparsers._add_action(action)
01653
01654
01655 return action
01656
01657 def _add_action(self, action):
01658 if action.option_strings:
01659 self._optionals._add_action(action)
01660 else:
01661 self._positionals._add_action(action)
01662 return action
01663
01664 def _get_optional_actions(self):
01665 return [action
01666 for action in self._actions
01667 if action.option_strings]
01668
01669 def _get_positional_actions(self):
01670 return [action
01671 for action in self._actions
01672 if not action.option_strings]
01673
01674
01675
01676
01677 def parse_args(self, args=None, namespace=None):
01678 args, argv = self.parse_known_args(args, namespace)
01679 if argv:
01680 msg = _('unrecognized arguments: %s')
01681 self.error(msg % ' '.join(argv))
01682 return args
01683
01684 def parse_known_args(self, args=None, namespace=None):
01685
01686 if args is None:
01687 args = _sys.argv[1:]
01688
01689
01690 if namespace is None:
01691 namespace = Namespace()
01692
01693
01694 for action in self._actions:
01695 if action.dest is not SUPPRESS:
01696 if not hasattr(namespace, action.dest):
01697 if action.default is not SUPPRESS:
01698 default = action.default
01699 if isinstance(action.default, basestring):
01700 default = self._get_value(action, default)
01701 setattr(namespace, action.dest, default)
01702
01703
01704 for dest in self._defaults:
01705 if not hasattr(namespace, dest):
01706 setattr(namespace, dest, self._defaults[dest])
01707
01708
01709 try:
01710 namespace, args = self._parse_known_args(args, namespace)
01711 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
01712 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
01713 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
01714 return namespace, args
01715 except ArgumentError:
01716 err = _sys.exc_info()[1]
01717 self.error(str(err))
01718
01719 def _parse_known_args(self, arg_strings, namespace):
01720
01721 if self.fromfile_prefix_chars is not None:
01722 arg_strings = self._read_args_from_files(arg_strings)
01723
01724
01725
01726 action_conflicts = {}
01727 for mutex_group in self._mutually_exclusive_groups:
01728 group_actions = mutex_group._group_actions
01729 for i, mutex_action in enumerate(mutex_group._group_actions):
01730 conflicts = action_conflicts.setdefault(mutex_action, [])
01731 conflicts.extend(group_actions[:i])
01732 conflicts.extend(group_actions[i + 1:])
01733
01734
01735
01736
01737 option_string_indices = {}
01738 arg_string_pattern_parts = []
01739 arg_strings_iter = iter(arg_strings)
01740 for i, arg_string in enumerate(arg_strings_iter):
01741
01742
01743 if arg_string == '--':
01744 arg_string_pattern_parts.append('-')
01745 for arg_string in arg_strings_iter:
01746 arg_string_pattern_parts.append('A')
01747
01748
01749
01750 else:
01751 option_tuple = self._parse_optional(arg_string)
01752 if option_tuple is None:
01753 pattern = 'A'
01754 else:
01755 option_string_indices[i] = option_tuple
01756 pattern = 'O'
01757 arg_string_pattern_parts.append(pattern)
01758
01759
01760 arg_strings_pattern = ''.join(arg_string_pattern_parts)
01761
01762
01763 seen_actions = set()
01764 seen_non_default_actions = set()
01765
01766 def take_action(action, argument_strings, option_string=None):
01767 seen_actions.add(action)
01768 argument_values = self._get_values(action, argument_strings)
01769
01770
01771
01772
01773 if argument_values is not action.default:
01774 seen_non_default_actions.add(action)
01775 for conflict_action in action_conflicts.get(action, []):
01776 if conflict_action in seen_non_default_actions:
01777 msg = _('not allowed with argument %s')
01778 action_name = _get_action_name(conflict_action)
01779 raise ArgumentError(action, msg % action_name)
01780
01781
01782
01783 if argument_values is not SUPPRESS:
01784 action(self, namespace, argument_values, option_string)
01785
01786
01787 def consume_optional(start_index):
01788
01789
01790 option_tuple = option_string_indices[start_index]
01791 action, option_string, explicit_arg = option_tuple
01792
01793
01794
01795 match_argument = self._match_argument
01796 action_tuples = []
01797 while True:
01798
01799
01800 if action is None:
01801 extras.append(arg_strings[start_index])
01802 return start_index + 1
01803
01804
01805
01806 if explicit_arg is not None:
01807 arg_count = match_argument(action, 'A')
01808
01809
01810
01811
01812 chars = self.prefix_chars
01813 if arg_count == 0 and option_string[1] not in chars:
01814 action_tuples.append((action, [], option_string))
01815 char = option_string[0]
01816 option_string = char + explicit_arg[0]
01817 new_explicit_arg = explicit_arg[1:] or None
01818 optionals_map = self._option_string_actions
01819 if option_string in optionals_map:
01820 action = optionals_map[option_string]
01821 explicit_arg = new_explicit_arg
01822 else:
01823 msg = _('ignored explicit argument %r')
01824 raise ArgumentError(action, msg % explicit_arg)
01825
01826
01827
01828 elif arg_count == 1:
01829 stop = start_index + 1
01830 args = [explicit_arg]
01831 action_tuples.append((action, args, option_string))
01832 break
01833
01834
01835
01836 else:
01837 msg = _('ignored explicit argument %r')
01838 raise ArgumentError(action, msg % explicit_arg)
01839
01840
01841
01842
01843 else:
01844 start = start_index + 1
01845 selected_patterns = arg_strings_pattern[start:]
01846 arg_count = match_argument(action, selected_patterns)
01847 stop = start + arg_count
01848 args = arg_strings[start:stop]
01849 action_tuples.append((action, args, option_string))
01850 break
01851
01852
01853
01854 assert action_tuples
01855 for action, args, option_string in action_tuples:
01856 take_action(action, args, option_string)
01857 return stop
01858
01859
01860
01861 positionals = self._get_positional_actions()
01862
01863
01864 def consume_positionals(start_index):
01865
01866 match_partial = self._match_arguments_partial
01867 selected_pattern = arg_strings_pattern[start_index:]
01868 arg_counts = match_partial(positionals, selected_pattern)
01869
01870
01871
01872 for action, arg_count in zip(positionals, arg_counts):
01873 args = arg_strings[start_index: start_index + arg_count]
01874 start_index += arg_count
01875 take_action(action, args)
01876
01877
01878
01879 positionals[:] = positionals[len(arg_counts):]
01880 return start_index
01881
01882
01883
01884 extras = []
01885 start_index = 0
01886 if option_string_indices:
01887 max_option_string_index = max(option_string_indices)
01888 else:
01889 max_option_string_index = -1
01890 while start_index <= max_option_string_index:
01891
01892
01893 next_option_string_index = min([
01894 index
01895 for index in option_string_indices
01896 if index >= start_index])
01897 if start_index != next_option_string_index:
01898 positionals_end_index = consume_positionals(start_index)
01899
01900
01901
01902 if positionals_end_index > start_index:
01903 start_index = positionals_end_index
01904 continue
01905 else:
01906 start_index = positionals_end_index
01907
01908
01909
01910 if start_index not in option_string_indices:
01911 strings = arg_strings[start_index:next_option_string_index]
01912 extras.extend(strings)
01913 start_index = next_option_string_index
01914
01915
01916 start_index = consume_optional(start_index)
01917
01918
01919 stop_index = consume_positionals(start_index)
01920
01921
01922 extras.extend(arg_strings[stop_index:])
01923
01924
01925
01926 if positionals:
01927 self.error(_('too few arguments'))
01928
01929
01930 for action in self._actions:
01931 if action.required:
01932 if action not in seen_actions:
01933 name = _get_action_name(action)
01934 self.error(_('argument %s is required') % name)
01935
01936
01937 for group in self._mutually_exclusive_groups:
01938 if group.required:
01939 for action in group._group_actions:
01940 if action in seen_non_default_actions:
01941 break
01942
01943
01944 else:
01945 names = [_get_action_name(action)
01946 for action in group._group_actions
01947 if action.help is not SUPPRESS]
01948 msg = _('one of the arguments %s is required')
01949 self.error(msg % ' '.join(names))
01950
01951
01952 return namespace, extras
01953
01954 def _read_args_from_files(self, arg_strings):
01955
01956 new_arg_strings = []
01957 for arg_string in arg_strings:
01958
01959
01960 if arg_string[0] not in self.fromfile_prefix_chars:
01961 new_arg_strings.append(arg_string)
01962
01963
01964 else:
01965 try:
01966 args_file = open(arg_string[1:])
01967 try:
01968 arg_strings = []
01969 for arg_line in args_file.read().splitlines():
01970 for arg in self.convert_arg_line_to_args(arg_line):
01971 arg_strings.append(arg)
01972 arg_strings = self._read_args_from_files(arg_strings)
01973 new_arg_strings.extend(arg_strings)
01974 finally:
01975 args_file.close()
01976 except IOError:
01977 err = _sys.exc_info()[1]
01978 self.error(str(err))
01979
01980
01981 return new_arg_strings
01982
01983 def convert_arg_line_to_args(self, arg_line):
01984 return [arg_line]
01985
01986 def _match_argument(self, action, arg_strings_pattern):
01987
01988 nargs_pattern = self._get_nargs_pattern(action)
01989 match = _re.match(nargs_pattern, arg_strings_pattern)
01990
01991
01992 if match is None:
01993 nargs_errors = {
01994 None: _('expected one argument'),
01995 OPTIONAL: _('expected at most one argument'),
01996 ONE_OR_MORE: _('expected at least one argument'),
01997 }
01998 default = _('expected %s argument(s)') % action.nargs
01999 msg = nargs_errors.get(action.nargs, default)
02000 raise ArgumentError(action, msg)
02001
02002
02003 return len(match.group(1))
02004
02005 def _match_arguments_partial(self, actions, arg_strings_pattern):
02006
02007
02008 result = []
02009 for i in range(len(actions), 0, -1):
02010 actions_slice = actions[:i]
02011 pattern = ''.join([self._get_nargs_pattern(action)
02012 for action in actions_slice])
02013 match = _re.match(pattern, arg_strings_pattern)
02014 if match is not None:
02015 result.extend([len(string) for string in match.groups()])
02016 break
02017
02018
02019 return result
02020
02021 def _parse_optional(self, arg_string):
02022
02023 if not arg_string:
02024 return None
02025
02026
02027 if not arg_string[0] in self.prefix_chars:
02028 return None
02029
02030
02031 if arg_string in self._option_string_actions:
02032 action = self._option_string_actions[arg_string]
02033 return action, arg_string, None
02034
02035
02036 if len(arg_string) == 1:
02037 return None
02038
02039
02040 if '=' in arg_string:
02041 option_string, explicit_arg = arg_string.split('=', 1)
02042 if option_string in self._option_string_actions:
02043 action = self._option_string_actions[option_string]
02044 return action, option_string, explicit_arg
02045
02046
02047
02048 option_tuples = self._get_option_tuples(arg_string)
02049
02050
02051 if len(option_tuples) > 1:
02052 options = ', '.join([option_string
02053 for action, option_string, explicit_arg in option_tuples])
02054 tup = arg_string, options
02055 self.error(_('ambiguous option: %s could match %s') % tup)
02056
02057
02058
02059 elif len(option_tuples) == 1:
02060 option_tuple, = option_tuples
02061 return option_tuple
02062
02063
02064
02065
02066 if self._negative_number_matcher.match(arg_string):
02067 if not self._has_negative_number_optionals:
02068 return None
02069
02070
02071 if ' ' in arg_string:
02072 return None
02073
02074
02075
02076 return None, arg_string, None
02077
02078 def _get_option_tuples(self, option_string):
02079 result = []
02080
02081
02082
02083 chars = self.prefix_chars
02084 if option_string[0] in chars and option_string[1] in chars:
02085 if '=' in option_string:
02086 option_prefix, explicit_arg = option_string.split('=', 1)
02087 else:
02088 option_prefix = option_string
02089 explicit_arg = None
02090 for option_string in self._option_string_actions:
02091 if option_string.startswith(option_prefix):
02092 action = self._option_string_actions[option_string]
02093 tup = action, option_string, explicit_arg
02094 result.append(tup)
02095
02096
02097
02098
02099 elif option_string[0] in chars and option_string[1] not in chars:
02100 option_prefix = option_string
02101 explicit_arg = None
02102 short_option_prefix = option_string[:2]
02103 short_explicit_arg = option_string[2:]
02104
02105 for option_string in self._option_string_actions:
02106 if option_string == short_option_prefix:
02107 action = self._option_string_actions[option_string]
02108 tup = action, option_string, short_explicit_arg
02109 result.append(tup)
02110 elif option_string.startswith(option_prefix):
02111 action = self._option_string_actions[option_string]
02112 tup = action, option_string, explicit_arg
02113 result.append(tup)
02114
02115
02116 else:
02117 self.error(_('unexpected option string: %s') % option_string)
02118
02119
02120 return result
02121
02122 def _get_nargs_pattern(self, action):
02123
02124
02125 nargs = action.nargs
02126
02127
02128 if nargs is None:
02129 nargs_pattern = '(-*A-*)'
02130
02131
02132 elif nargs == OPTIONAL:
02133 nargs_pattern = '(-*A?-*)'
02134
02135
02136 elif nargs == ZERO_OR_MORE:
02137 nargs_pattern = '(-*[A-]*)'
02138
02139
02140 elif nargs == ONE_OR_MORE:
02141 nargs_pattern = '(-*A[A-]*)'
02142
02143
02144 elif nargs == REMAINDER:
02145 nargs_pattern = '([-AO]*)'
02146
02147
02148 elif nargs == PARSER:
02149 nargs_pattern = '(-*A[-AO]*)'
02150
02151
02152 else:
02153 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
02154
02155
02156 if action.option_strings:
02157 nargs_pattern = nargs_pattern.replace('-*', '')
02158 nargs_pattern = nargs_pattern.replace('-', '')
02159
02160
02161 return nargs_pattern
02162
02163
02164
02165
02166 def _get_values(self, action, arg_strings):
02167
02168 if action.nargs not in [PARSER, REMAINDER]:
02169 arg_strings = [s for s in arg_strings if s != '--']
02170
02171
02172 if not arg_strings and action.nargs == OPTIONAL:
02173 if action.option_strings:
02174 value = action.const
02175 else:
02176 value = action.default
02177 if isinstance(value, basestring):
02178 value = self._get_value(action, value)
02179 self._check_value(action, value)
02180
02181
02182
02183 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
02184 not action.option_strings):
02185 if action.default is not None:
02186 value = action.default
02187 else:
02188 value = arg_strings
02189 self._check_value(action, value)
02190
02191
02192 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
02193 arg_string, = arg_strings
02194 value = self._get_value(action, arg_string)
02195 self._check_value(action, value)
02196
02197
02198 elif action.nargs == REMAINDER:
02199 value = [self._get_value(action, v) for v in arg_strings]
02200
02201
02202 elif action.nargs == PARSER:
02203 value = [self._get_value(action, v) for v in arg_strings]
02204 self._check_value(action, value[0])
02205
02206
02207 else:
02208 value = [self._get_value(action, v) for v in arg_strings]
02209 for v in value:
02210 self._check_value(action, v)
02211
02212
02213 return value
02214
02215 def _get_value(self, action, arg_string):
02216 type_func = self._registry_get('type', action.type, action.type)
02217 if not _callable(type_func):
02218 msg = _('%r is not callable')
02219 raise ArgumentError(action, msg % type_func)
02220
02221
02222 try:
02223 result = type_func(arg_string)
02224
02225
02226 except ArgumentTypeError:
02227 name = getattr(action.type, '__name__', repr(action.type))
02228 msg = str(_sys.exc_info()[1])
02229 raise ArgumentError(action, msg)
02230
02231
02232 except (TypeError, ValueError):
02233 name = getattr(action.type, '__name__', repr(action.type))
02234 msg = _('invalid %s value: %r')
02235 raise ArgumentError(action, msg % (name, arg_string))
02236
02237
02238 return result
02239
02240 def _check_value(self, action, value):
02241
02242 if action.choices is not None and value not in action.choices:
02243 tup = value, ', '.join(map(repr, action.choices))
02244 msg = _('invalid choice: %r (choose from %s)') % tup
02245 raise ArgumentError(action, msg)
02246
02247
02248
02249
02250 def format_usage(self):
02251 formatter = self._get_formatter()
02252 formatter.add_usage(self.usage, self._actions,
02253 self._mutually_exclusive_groups)
02254 return formatter.format_help()
02255
02256 def format_help(self):
02257 formatter = self._get_formatter()
02258
02259
02260 formatter.add_usage(self.usage, self._actions,
02261 self._mutually_exclusive_groups)
02262
02263
02264 formatter.add_text(self.description)
02265
02266
02267 for action_group in self._action_groups:
02268 formatter.start_section(action_group.title)
02269 formatter.add_text(action_group.description)
02270 formatter.add_arguments(action_group._group_actions)
02271 formatter.end_section()
02272
02273
02274 formatter.add_text(self.epilog)
02275
02276
02277 return formatter.format_help()
02278
02279 def format_version(self):
02280 import warnings
02281 warnings.warn(
02282 'The format_version method is deprecated -- the "version" '
02283 'argument to ArgumentParser is no longer supported.',
02284 DeprecationWarning)
02285 formatter = self._get_formatter()
02286 formatter.add_text(self.version)
02287 return formatter.format_help()
02288
02289 def _get_formatter(self):
02290 return self.formatter_class(prog=self.prog)
02291
02292
02293
02294
02295 def print_usage(self, file=None):
02296 if file is None:
02297 file = _sys.stdout
02298 self._print_message(self.format_usage(), file)
02299
02300 def print_help(self, file=None):
02301 if file is None:
02302 file = _sys.stdout
02303 self._print_message(self.format_help(), file)
02304
02305 def print_version(self, file=None):
02306 import warnings
02307 warnings.warn(
02308 'The print_version method is deprecated -- the "version" '
02309 'argument to ArgumentParser is no longer supported.',
02310 DeprecationWarning)
02311 self._print_message(self.format_version(), file)
02312
02313 def _print_message(self, message, file=None):
02314 if message:
02315 if file is None:
02316 file = _sys.stderr
02317 file.write(message)
02318
02319
02320
02321
02322 def exit(self, status=0, message=None):
02323 if message:
02324 self._print_message(message, _sys.stderr)
02325 _sys.exit(status)
02326
02327 def error(self, message):
02328 """error(message: string)
02329
02330 Prints a usage message incorporating the message to stderr and
02331 exits.
02332
02333 If you override this in a subclass, it should not return -- it
02334 should either exit or raise an exception.
02335 """
02336 self.print_usage(_sys.stderr)
02337 self.exit(2, _('%s: error: %s\n') % (self.prog, message))