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