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