llvm-project
2353 строки · 84.3 Кб
1# -*- coding: utf-8 -*-
2
3# Copyright © 2006-2009 Steven J. Bethard <steven.bethard@gmail.com>.
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may not
6# use this file except in compliance with the License. You may obtain a copy
7# of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
16
17"""Command-line parsing library
18
19This module is an optparse-inspired command-line parsing library that:
20
21- handles both optional and positional arguments
22- produces highly informative usage messages
23- supports parsers that dispatch to sub-parsers
24
25The following is a simple usage example that sums integers from the
26command-line and writes the result to a file::
27
28parser = argparse.ArgumentParser(
29description='sum the integers at the command line')
30parser.add_argument(
31'integers', metavar='int', nargs='+', type=int,
32help='an integer to be summed')
33parser.add_argument(
34'--log', default=sys.stdout, type=argparse.FileType('w'),
35help='the file where the sum should be written')
36args = parser.parse_args()
37args.log.write('%s' % sum(args.integers))
38args.log.close()
39
40The module contains the following public classes:
41
42- ArgumentParser -- The main entry point for command-line parsing. As the
43example above shows, the add_argument() method is used to populate
44the parser with actions for optional and positional arguments. Then
45the parse_args() method is invoked to convert the args at the
46command-line into an object with attributes.
47
48- ArgumentError -- The exception raised by ArgumentParser objects when
49there are errors with the parser's actions. Errors raised while
50parsing the command-line are caught by ArgumentParser and emitted
51as command-line messages.
52
53- FileType -- A factory for defining types of files to be created. As the
54example above shows, instances of FileType are typically passed as
55the type= argument of add_argument() calls.
56
57- Action -- The base class for parser actions. Typically actions are
58selected by passing strings like 'store_true' or 'append_const' to
59the action= argument of add_argument(). However, for greater
60customization of ArgumentParser actions, subclasses of Action may
61be defined and passed as the action= argument.
62
63- HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
64ArgumentDefaultsHelpFormatter -- Formatter classes which
65may be passed as the formatter_class= argument to the
66ArgumentParser constructor. HelpFormatter is the default,
67RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
68not to change the formatting for help text, and
69ArgumentDefaultsHelpFormatter adds information about argument defaults
70to the help.
71
72All other classes in this module are considered implementation details.
73(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
74considered public as object names -- the API of the formatter objects is
75still considered an implementation detail.)
76"""
77
78__version__ = "1.1"79__all__ = [80"ArgumentParser",81"ArgumentError",82"Namespace",83"Action",84"FileType",85"HelpFormatter",86"RawDescriptionHelpFormatter",87"RawTextHelpFormatter",88"ArgumentDefaultsHelpFormatter",89]
90
91
92import copy as _copy93import os as _os94import re as _re95import sys as _sys96import textwrap as _textwrap97
98from gettext import gettext as _99
100try:101_set = set102except NameError:103from sets import Set as _set104
105try:106_basestring = basestring107except NameError:108_basestring = str109
110try:111_sorted = sorted112except NameError:113
114def _sorted(iterable, reverse=False):115result = list(iterable)116result.sort()117if reverse:118result.reverse()119return result120
121
122def _callable(obj):123return hasattr(obj, "__call__") or hasattr(obj, "__bases__")124
125
126# silence Python 2.6 buggy warnings about Exception.message
127if _sys.version_info[:2] == (2, 6):128import warnings129
130warnings.filterwarnings(131action="ignore",132message="BaseException.message has been deprecated as of Python 2.6",133category=DeprecationWarning,134module="argparse",135)136
137
138SUPPRESS = "==SUPPRESS=="139
140OPTIONAL = "?"141ZERO_OR_MORE = "*"142ONE_OR_MORE = "+"143PARSER = "A..."144REMAINDER = "..."145
146# =============================
147# Utility functions and classes
148# =============================
149
150
151class _AttributeHolder(object):152"""Abstract base class that provides __repr__.153
154The __repr__ method returns a string in the format::
155ClassName(attr=name, attr=name, ...)
156The attributes are determined either by a class-level attribute,
157'_kwarg_names', or by inspecting the instance __dict__.
158"""
159
160def __repr__(self):161type_name = type(self).__name__162arg_strings = []163for arg in self._get_args():164arg_strings.append(repr(arg))165for name, value in self._get_kwargs():166arg_strings.append("%s=%r" % (name, value))167return "%s(%s)" % (type_name, ", ".join(arg_strings))168
169def _get_kwargs(self):170return _sorted(self.__dict__.items())171
172def _get_args(self):173return []174
175
176def _ensure_value(namespace, name, value):177if getattr(namespace, name, None) is None:178setattr(namespace, name, value)179return getattr(namespace, name)180
181
182# ===============
183# Formatting Help
184# ===============
185
186
187class HelpFormatter(object):188"""Formatter for generating usage messages and argument help strings.189
190Only the name of this class is considered a public API. All the methods
191provided by the class are considered an implementation detail.
192"""
193
194def __init__(self, prog, indent_increment=2, max_help_position=24, width=None):195
196# default setting for width197if width is None:198try:199width = int(_os.environ["COLUMNS"])200except (KeyError, ValueError):201width = 80202width -= 2203
204self._prog = prog205self._indent_increment = indent_increment206self._max_help_position = max_help_position207self._width = width208
209self._current_indent = 0210self._level = 0211self._action_max_length = 0212
213self._root_section = self._Section(self, None)214self._current_section = self._root_section215
216self._whitespace_matcher = _re.compile(r"\s+")217self._long_break_matcher = _re.compile(r"\n\n\n+")218
219# ===============================220# Section and indentation methods221# ===============================222def _indent(self):223self._current_indent += self._indent_increment224self._level += 1225
226def _dedent(self):227self._current_indent -= self._indent_increment228assert self._current_indent >= 0, "Indent decreased below 0."229self._level -= 1230
231class _Section(object):232def __init__(self, formatter, parent, heading=None):233self.formatter = formatter234self.parent = parent235self.heading = heading236self.items = []237
238def format_help(self):239# format the indented section240if self.parent is not None:241self.formatter._indent()242join = self.formatter._join_parts243for func, args in self.items:244func(*args)245item_help = join([func(*args) for func, args in self.items])246if self.parent is not None:247self.formatter._dedent()248
249# return nothing if the section was empty250if not item_help:251return ""252
253# add the heading if the section was non-empty254if self.heading is not SUPPRESS and self.heading is not None:255current_indent = self.formatter._current_indent256heading = "%*s%s:\n" % (current_indent, "", self.heading)257else:258heading = ""259
260# join the section-initial newline, the heading and the help261return join(["\n", heading, item_help, "\n"])262
263def _add_item(self, func, args):264self._current_section.items.append((func, args))265
266# ========================267# Message building methods268# ========================269def start_section(self, heading):270self._indent()271section = self._Section(self, self._current_section, heading)272self._add_item(section.format_help, [])273self._current_section = section274
275def end_section(self):276self._current_section = self._current_section.parent277self._dedent()278
279def add_text(self, text):280if text is not SUPPRESS and text is not None:281self._add_item(self._format_text, [text])282
283def add_usage(self, usage, actions, groups, prefix=None):284if usage is not SUPPRESS:285args = usage, actions, groups, prefix286self._add_item(self._format_usage, args)287
288def add_argument(self, action):289if action.help is not SUPPRESS:290
291# find all invocations292get_invocation = self._format_action_invocation293invocations = [get_invocation(action)]294for subaction in self._iter_indented_subactions(action):295invocations.append(get_invocation(subaction))296
297# update the maximum item length298invocation_length = max([len(s) for s in invocations])299action_length = invocation_length + self._current_indent300self._action_max_length = max(self._action_max_length, action_length)301
302# add the item to the list303self._add_item(self._format_action, [action])304
305def add_arguments(self, actions):306for action in actions:307self.add_argument(action)308
309# =======================310# Help-formatting methods311# =======================312def format_help(self):313help = self._root_section.format_help()314if help:315help = self._long_break_matcher.sub("\n\n", help)316help = help.strip("\n") + "\n"317return help318
319def _join_parts(self, part_strings):320return "".join([part for part in part_strings if part and part is not SUPPRESS])321
322def _format_usage(self, usage, actions, groups, prefix):323if prefix is None:324prefix = _("usage: ")325
326# if usage is specified, use that327if usage is not None:328usage = usage % dict(prog=self._prog)329
330# if no optionals or positionals are available, usage is just prog331elif usage is None and not actions:332usage = "%(prog)s" % dict(prog=self._prog)333
334# if optionals and positionals are available, calculate usage335elif usage is None:336prog = "%(prog)s" % dict(prog=self._prog)337
338# split optionals from positionals339optionals = []340positionals = []341for action in actions:342if action.option_strings:343optionals.append(action)344else:345positionals.append(action)346
347# build full usage string348format = self._format_actions_usage349action_usage = format(optionals + positionals, groups)350usage = " ".join([s for s in [prog, action_usage] if s])351
352# wrap the usage parts if it's too long353text_width = self._width - self._current_indent354if len(prefix) + len(usage) > text_width:355
356# break usage into wrappable parts357part_regexp = r"\(.*?\)+|\[.*?\]+|\S+"358opt_usage = format(optionals, groups)359pos_usage = format(positionals, groups)360opt_parts = _re.findall(part_regexp, opt_usage)361pos_parts = _re.findall(part_regexp, pos_usage)362assert " ".join(opt_parts) == opt_usage363assert " ".join(pos_parts) == pos_usage364
365# helper for wrapping lines366def get_lines(parts, indent, prefix=None):367lines = []368line = []369if prefix is not None:370line_len = len(prefix) - 1371else:372line_len = len(indent) - 1373for part in parts:374if line_len + 1 + len(part) > text_width:375lines.append(indent + " ".join(line))376line = []377line_len = len(indent) - 1378line.append(part)379line_len += len(part) + 1380if line:381lines.append(indent + " ".join(line))382if prefix is not None:383lines[0] = lines[0][len(indent) :]384return lines385
386# if prog is short, follow it with optionals or positionals387if len(prefix) + len(prog) <= 0.75 * text_width:388indent = " " * (len(prefix) + len(prog) + 1)389if opt_parts:390lines = get_lines([prog] + opt_parts, indent, prefix)391lines.extend(get_lines(pos_parts, indent))392elif pos_parts:393lines = get_lines([prog] + pos_parts, indent, prefix)394else:395lines = [prog]396
397# if prog is long, put it on its own line398else:399indent = " " * len(prefix)400parts = opt_parts + pos_parts401lines = get_lines(parts, indent)402if len(lines) > 1:403lines = []404lines.extend(get_lines(opt_parts, indent))405lines.extend(get_lines(pos_parts, indent))406lines = [prog] + lines407
408# join lines into usage409usage = "\n".join(lines)410
411# prefix with 'usage:'412return "%s%s\n\n" % (prefix, usage)413
414def _format_actions_usage(self, actions, groups):415# find group indices and identify actions in groups416group_actions = _set()417inserts = {}418for group in groups:419try:420start = actions.index(group._group_actions[0])421except ValueError:422continue423else:424end = start + len(group._group_actions)425if actions[start:end] == group._group_actions:426for action in group._group_actions:427group_actions.add(action)428if not group.required:429inserts[start] = "["430inserts[end] = "]"431else:432inserts[start] = "("433inserts[end] = ")"434for i in range(start + 1, end):435inserts[i] = "|"436
437# collect all actions format strings438parts = []439for i, action in enumerate(actions):440
441# suppressed arguments are marked with None442# remove | separators for suppressed arguments443if action.help is SUPPRESS:444parts.append(None)445if inserts.get(i) == "|":446inserts.pop(i)447elif inserts.get(i + 1) == "|":448inserts.pop(i + 1)449
450# produce all arg strings451elif not action.option_strings:452part = self._format_args(action, action.dest)453
454# if it's in a group, strip the outer []455if action in group_actions:456if part[0] == "[" and part[-1] == "]":457part = part[1:-1]458
459# add the action string to the list460parts.append(part)461
462# produce the first way to invoke the option in brackets463else:464option_string = action.option_strings[0]465
466# if the Optional doesn't take a value, format is:467# -s or --long468if action.nargs == 0:469part = "%s" % option_string470
471# if the Optional takes a value, format is:472# -s ARGS or --long ARGS473else:474default = action.dest.upper()475args_string = self._format_args(action, default)476part = "%s %s" % (option_string, args_string)477
478# make it look optional if it's not required or in a group479if not action.required and action not in group_actions:480part = "[%s]" % part481
482# add the action string to the list483parts.append(part)484
485# insert things at the necessary indices486for i in _sorted(inserts, reverse=True):487parts[i:i] = [inserts[i]]488
489# join all the action items with spaces490text = " ".join([item for item in parts if item is not None])491
492# clean up separators for mutually exclusive groups493open = r"[\[(]"494close = r"[\])]"495text = _re.sub(r"(%s) " % open, r"\1", text)496text = _re.sub(r" (%s)" % close, r"\1", text)497text = _re.sub(r"%s *%s" % (open, close), r"", text)498text = _re.sub(r"\(([^|]*)\)", r"\1", text)499text = text.strip()500
501# return the text502return text503
504def _format_text(self, text):505if "%(prog)" in text:506text = text % dict(prog=self._prog)507text_width = self._width - self._current_indent508indent = " " * self._current_indent509return self._fill_text(text, text_width, indent) + "\n\n"510
511def _format_action(self, action):512# determine the required width and the entry label513help_position = min(self._action_max_length + 2, self._max_help_position)514help_width = self._width - help_position515action_width = help_position - self._current_indent - 2516action_header = self._format_action_invocation(action)517
518# ho nelp; start on same line and add a final newline519if not action.help:520tup = self._current_indent, "", action_header521action_header = "%*s%s\n" % tup522
523# short action name; start on the same line and pad two spaces524elif len(action_header) <= action_width:525tup = self._current_indent, "", action_width, action_header526action_header = "%*s%-*s " % tup527indent_first = 0528
529# long action name; start on the next line530else:531tup = self._current_indent, "", action_header532action_header = "%*s%s\n" % tup533indent_first = help_position534
535# collect the pieces of the action help536parts = [action_header]537
538# if there was help for the action, add lines of help text539if action.help:540help_text = self._expand_help(action)541help_lines = self._split_lines(help_text, help_width)542parts.append("%*s%s\n" % (indent_first, "", help_lines[0]))543for line in help_lines[1:]:544parts.append("%*s%s\n" % (help_position, "", line))545
546# or add a newline if the description doesn't end with one547elif not action_header.endswith("\n"):548parts.append("\n")549
550# if there are any sub-actions, add their help as well551for subaction in self._iter_indented_subactions(action):552parts.append(self._format_action(subaction))553
554# return a single string555return self._join_parts(parts)556
557def _format_action_invocation(self, action):558if not action.option_strings:559(metavar,) = self._metavar_formatter(action, action.dest)(1)560return metavar561
562else:563parts = []564
565# if the Optional doesn't take a value, format is:566# -s, --long567if action.nargs == 0:568parts.extend(action.option_strings)569
570# if the Optional takes a value, format is:571# -s ARGS, --long ARGS572else:573default = action.dest.upper()574args_string = self._format_args(action, default)575for option_string in action.option_strings:576parts.append("%s %s" % (option_string, args_string))577
578return ", ".join(parts)579
580def _metavar_formatter(self, action, default_metavar):581if action.metavar is not None:582result = action.metavar583elif action.choices is not None:584choice_strs = [str(choice) for choice in action.choices]585result = "{%s}" % ",".join(choice_strs)586else:587result = default_metavar588
589def format(tuple_size):590if isinstance(result, tuple):591return result592else:593return (result,) * tuple_size594
595return format596
597def _format_args(self, action, default_metavar):598get_metavar = self._metavar_formatter(action, default_metavar)599if action.nargs is None:600result = "%s" % get_metavar(1)601elif action.nargs == OPTIONAL:602result = "[%s]" % get_metavar(1)603elif action.nargs == ZERO_OR_MORE:604result = "[%s [%s ...]]" % get_metavar(2)605elif action.nargs == ONE_OR_MORE:606result = "%s [%s ...]" % get_metavar(2)607elif action.nargs == REMAINDER:608result = "..."609elif action.nargs == PARSER:610result = "%s ..." % get_metavar(1)611else:612formats = ["%s" for _ in range(action.nargs)]613result = " ".join(formats) % get_metavar(action.nargs)614return result615
616def _expand_help(self, action):617params = dict(vars(action), prog=self._prog)618for name in list(params):619if params[name] is SUPPRESS:620del params[name]621for name in list(params):622if hasattr(params[name], "__name__"):623params[name] = params[name].__name__624if params.get("choices") is not None:625choices_str = ", ".join([str(c) for c in params["choices"]])626params["choices"] = choices_str627return self._get_help_string(action) % params628
629def _iter_indented_subactions(self, action):630try:631get_subactions = action._get_subactions632except AttributeError:633pass634else:635self._indent()636for subaction in get_subactions():637yield subaction638self._dedent()639
640def _split_lines(self, text, width):641text = self._whitespace_matcher.sub(" ", text).strip()642return _textwrap.wrap(text, width)643
644def _fill_text(self, text, width, indent):645text = self._whitespace_matcher.sub(" ", text).strip()646return _textwrap.fill(647text, width, initial_indent=indent, subsequent_indent=indent648)649
650def _get_help_string(self, action):651return action.help652
653
654class RawDescriptionHelpFormatter(HelpFormatter):655"""Help message formatter which retains any formatting in descriptions.656
657Only the name of this class is considered a public API. All the methods
658provided by the class are considered an implementation detail.
659"""
660
661def _fill_text(self, text, width, indent):662return "".join([indent + line for line in text.splitlines(True)])663
664
665class RawTextHelpFormatter(RawDescriptionHelpFormatter):666"""Help message formatter which retains formatting of all help text.667
668Only the name of this class is considered a public API. All the methods
669provided by the class are considered an implementation detail.
670"""
671
672def _split_lines(self, text, width):673return text.splitlines()674
675
676class ArgumentDefaultsHelpFormatter(HelpFormatter):677"""Help message formatter which adds default values to argument help.678
679Only the name of this class is considered a public API. All the methods
680provided by the class are considered an implementation detail.
681"""
682
683def _get_help_string(self, action):684help = action.help685if "%(default)" not in action.help:686if action.default is not SUPPRESS:687defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]688if action.option_strings or action.nargs in defaulting_nargs:689help += " (default: %(default)s)"690return help691
692
693# =====================
694# Options and Arguments
695# =====================
696
697
698def _get_action_name(argument):699if argument is None:700return None701elif argument.option_strings:702return "/".join(argument.option_strings)703elif argument.metavar not in (None, SUPPRESS):704return argument.metavar705elif argument.dest not in (None, SUPPRESS):706return argument.dest707else:708return None709
710
711class ArgumentError(Exception):712"""An error from creating or using an argument (optional or positional).713
714The string value of this exception is the message, augmented with
715information about the argument that caused it.
716"""
717
718def __init__(self, argument, message):719self.argument_name = _get_action_name(argument)720self.message = message721
722def __str__(self):723if self.argument_name is None:724format = "%(message)s"725else:726format = "argument %(argument_name)s: %(message)s"727return format % dict(message=self.message, argument_name=self.argument_name)728
729
730class ArgumentTypeError(Exception):731"""An error from trying to convert a command line string to a type."""732
733pass734
735
736# ==============
737# Action classes
738# ==============
739
740
741class Action(_AttributeHolder):742"""Information about how to convert command line strings to Python objects.743
744Action objects are used by an ArgumentParser to represent the information
745needed to parse a single argument from one or more strings from the
746command line. The keyword arguments to the Action constructor are also
747all attributes of Action instances.
748
749Keyword Arguments:
750
751- option_strings -- A list of command-line option strings which
752should be associated with this action.
753
754- dest -- The name of the attribute to hold the created object(s)
755
756- nargs -- The number of command-line arguments that should be
757consumed. By default, one argument will be consumed and a single
758value will be produced. Other values include:
759- N (an integer) consumes N arguments (and produces a list)
760- '?' consumes zero or one arguments
761- '*' consumes zero or more arguments (and produces a list)
762- '+' consumes one or more arguments (and produces a list)
763Note that the difference between the default and nargs=1 is that
764with the default, a single value will be produced, while with
765nargs=1, a list containing a single value will be produced.
766
767- const -- The value to be produced if the option is specified and the
768option uses an action that takes no values.
769
770- default -- The value to be produced if the option is not specified.
771
772- type -- The type which the command-line arguments should be converted
773to, should be one of 'string', 'int', 'float', 'complex' or a
774callable object that accepts a single string argument. If None,
775'string' is assumed.
776
777- choices -- A container of values that should be allowed. If not None,
778after a command-line argument has been converted to the appropriate
779type, an exception will be raised if it is not a member of this
780collection.
781
782- required -- True if the action must always be specified at the
783command line. This is only meaningful for optional command-line
784arguments.
785
786- help -- The help string describing the argument.
787
788- metavar -- The name to be used for the option's argument with the
789help string. If None, the 'dest' value will be used as the name.
790"""
791
792def __init__(793self,794option_strings,795dest,796nargs=None,797const=None,798default=None,799type=None,800choices=None,801required=False,802help=None,803metavar=None,804):805self.option_strings = option_strings806self.dest = dest807self.nargs = nargs808self.const = const809self.default = default810self.type = type811self.choices = choices812self.required = required813self.help = help814self.metavar = metavar815
816def _get_kwargs(self):817names = [818"option_strings",819"dest",820"nargs",821"const",822"default",823"type",824"choices",825"help",826"metavar",827]828return [(name, getattr(self, name)) for name in names]829
830def __call__(self, parser, namespace, values, option_string=None):831raise NotImplementedError(_(".__call__() not defined"))832
833
834class _StoreAction(Action):835def __init__(836self,837option_strings,838dest,839nargs=None,840const=None,841default=None,842type=None,843choices=None,844required=False,845help=None,846metavar=None,847):848if nargs == 0:849raise ValueError(850"nargs for store actions must be > 0; if you "851"have nothing to store, actions such as store "852"true or store const may be more appropriate"853)854if const is not None and nargs != OPTIONAL:855raise ValueError("nargs must be %r to supply const" % OPTIONAL)856super(_StoreAction, self).__init__(857option_strings=option_strings,858dest=dest,859nargs=nargs,860const=const,861default=default,862type=type,863choices=choices,864required=required,865help=help,866metavar=metavar,867)868
869def __call__(self, parser, namespace, values, option_string=None):870setattr(namespace, self.dest, values)871
872
873class _StoreConstAction(Action):874def __init__(875self,876option_strings,877dest,878const,879default=None,880required=False,881help=None,882metavar=None,883):884super(_StoreConstAction, self).__init__(885option_strings=option_strings,886dest=dest,887nargs=0,888const=const,889default=default,890required=required,891help=help,892)893
894def __call__(self, parser, namespace, values, option_string=None):895setattr(namespace, self.dest, self.const)896
897
898class _StoreTrueAction(_StoreConstAction):899def __init__(self, option_strings, dest, default=False, required=False, help=None):900super(_StoreTrueAction, self).__init__(901option_strings=option_strings,902dest=dest,903const=True,904default=default,905required=required,906help=help,907)908
909
910class _StoreFalseAction(_StoreConstAction):911def __init__(self, option_strings, dest, default=True, required=False, help=None):912super(_StoreFalseAction, self).__init__(913option_strings=option_strings,914dest=dest,915const=False,916default=default,917required=required,918help=help,919)920
921
922class _AppendAction(Action):923def __init__(924self,925option_strings,926dest,927nargs=None,928const=None,929default=None,930type=None,931choices=None,932required=False,933help=None,934metavar=None,935):936if nargs == 0:937raise ValueError(938"nargs for append actions must be > 0; if arg "939"strings are not supplying the value to append, "940"the append const action may be more appropriate"941)942if const is not None and nargs != OPTIONAL:943raise ValueError("nargs must be %r to supply const" % OPTIONAL)944super(_AppendAction, self).__init__(945option_strings=option_strings,946dest=dest,947nargs=nargs,948const=const,949default=default,950type=type,951choices=choices,952required=required,953help=help,954metavar=metavar,955)956
957def __call__(self, parser, namespace, values, option_string=None):958items = _copy.copy(_ensure_value(namespace, self.dest, []))959items.append(values)960setattr(namespace, self.dest, items)961
962
963class _AppendConstAction(Action):964def __init__(965self,966option_strings,967dest,968const,969default=None,970required=False,971help=None,972metavar=None,973):974super(_AppendConstAction, self).__init__(975option_strings=option_strings,976dest=dest,977nargs=0,978const=const,979default=default,980required=required,981help=help,982metavar=metavar,983)984
985def __call__(self, parser, namespace, values, option_string=None):986items = _copy.copy(_ensure_value(namespace, self.dest, []))987items.append(self.const)988setattr(namespace, self.dest, items)989
990
991class _CountAction(Action):992def __init__(self, option_strings, dest, default=None, required=False, help=None):993super(_CountAction, self).__init__(994option_strings=option_strings,995dest=dest,996nargs=0,997default=default,998required=required,999help=help,1000)1001
1002def __call__(self, parser, namespace, values, option_string=None):1003new_count = _ensure_value(namespace, self.dest, 0) + 11004setattr(namespace, self.dest, new_count)1005
1006
1007class _HelpAction(Action):1008def __init__(self, option_strings, dest=SUPPRESS, default=SUPPRESS, help=None):1009super(_HelpAction, self).__init__(1010option_strings=option_strings,1011dest=dest,1012default=default,1013nargs=0,1014help=help,1015)1016
1017def __call__(self, parser, namespace, values, option_string=None):1018parser.print_help()1019parser.exit()1020
1021
1022class _VersionAction(Action):1023def __init__(1024self, option_strings, version=None, dest=SUPPRESS, default=SUPPRESS, help=None1025):1026super(_VersionAction, self).__init__(1027option_strings=option_strings,1028dest=dest,1029default=default,1030nargs=0,1031help=help,1032)1033self.version = version1034
1035def __call__(self, parser, namespace, values, option_string=None):1036version = self.version1037if version is None:1038version = parser.version1039formatter = parser._get_formatter()1040formatter.add_text(version)1041parser.exit(message=formatter.format_help())1042
1043
1044class _SubParsersAction(Action):1045class _ChoicesPseudoAction(Action):1046def __init__(self, name, help):1047sup = super(_SubParsersAction._ChoicesPseudoAction, self)1048sup.__init__(option_strings=[], dest=name, help=help)1049
1050def __init__(1051self, option_strings, prog, parser_class, dest=SUPPRESS, help=None, metavar=None1052):1053
1054self._prog_prefix = prog1055self._parser_class = parser_class1056self._name_parser_map = {}1057self._choices_actions = []1058
1059super(_SubParsersAction, self).__init__(1060option_strings=option_strings,1061dest=dest,1062nargs=PARSER,1063choices=self._name_parser_map,1064help=help,1065metavar=metavar,1066)1067
1068def add_parser(self, name, **kwargs):1069# set prog from the existing prefix1070if kwargs.get("prog") is None:1071kwargs["prog"] = "%s %s" % (self._prog_prefix, name)1072
1073# create a pseudo-action to hold the choice help1074if "help" in kwargs:1075help = kwargs.pop("help")1076choice_action = self._ChoicesPseudoAction(name, help)1077self._choices_actions.append(choice_action)1078
1079# create the parser and add it to the map1080parser = self._parser_class(**kwargs)1081self._name_parser_map[name] = parser1082return parser1083
1084def _get_subactions(self):1085return self._choices_actions1086
1087def __call__(self, parser, namespace, values, option_string=None):1088parser_name = values[0]1089arg_strings = values[1:]1090
1091# set the parser name if requested1092if self.dest is not SUPPRESS:1093setattr(namespace, self.dest, parser_name)1094
1095# select the parser1096try:1097parser = self._name_parser_map[parser_name]1098except KeyError:1099tup = parser_name, ", ".join(self._name_parser_map)1100msg = _("unknown parser %r (choices: %s)" % tup)1101raise ArgumentError(self, msg)1102
1103# parse all the remaining options into the namespace1104parser.parse_args(arg_strings, namespace)1105
1106
1107# ==============
1108# Type classes
1109# ==============
1110
1111
1112class FileType(object):1113"""Factory for creating file object types1114
1115Instances of FileType are typically passed as type= arguments to the
1116ArgumentParser add_argument() method.
1117
1118Keyword Arguments:
1119- mode -- A string indicating how the file is to be opened. Accepts the
1120same values as the builtin open() function.
1121- bufsize -- The file's desired buffer size. Accepts the same values as
1122the builtin open() function.
1123"""
1124
1125def __init__(self, mode="r", bufsize=None):1126self._mode = mode1127self._bufsize = bufsize1128
1129def __call__(self, string):1130# the special argument "-" means sys.std{in,out}1131if string == "-":1132if "r" in self._mode:1133return _sys.stdin1134elif "w" in self._mode:1135return _sys.stdout1136else:1137msg = _('argument "-" with mode %r' % self._mode)1138raise ValueError(msg)1139
1140# all other arguments are used as file names1141if self._bufsize:1142return open(string, self._mode, self._bufsize)1143else:1144return open(string, self._mode)1145
1146def __repr__(self):1147args = [self._mode, self._bufsize]1148args_str = ", ".join([repr(arg) for arg in args if arg is not None])1149return "%s(%s)" % (type(self).__name__, args_str)1150
1151
1152# ===========================
1153# Optional and Positional Parsing
1154# ===========================
1155
1156
1157class Namespace(_AttributeHolder):1158"""Simple object for storing attributes.1159
1160Implements equality by attribute names and values, and provides a simple
1161string representation.
1162"""
1163
1164def __init__(self, **kwargs):1165for name in kwargs:1166setattr(self, name, kwargs[name])1167
1168def __eq__(self, other):1169return vars(self) == vars(other)1170
1171def __ne__(self, other):1172return not (self == other)1173
1174def __contains__(self, key):1175return key in self.__dict__1176
1177
1178class _ActionsContainer(object):1179def __init__(self, description, prefix_chars, argument_default, conflict_handler):1180super(_ActionsContainer, self).__init__()1181
1182self.description = description1183self.argument_default = argument_default1184self.prefix_chars = prefix_chars1185self.conflict_handler = conflict_handler1186
1187# set up registries1188self._registries = {}1189
1190# register actions1191self.register("action", None, _StoreAction)1192self.register("action", "store", _StoreAction)1193self.register("action", "store_const", _StoreConstAction)1194self.register("action", "store_true", _StoreTrueAction)1195self.register("action", "store_false", _StoreFalseAction)1196self.register("action", "append", _AppendAction)1197self.register("action", "append_const", _AppendConstAction)1198self.register("action", "count", _CountAction)1199self.register("action", "help", _HelpAction)1200self.register("action", "version", _VersionAction)1201self.register("action", "parsers", _SubParsersAction)1202
1203# raise an exception if the conflict handler is invalid1204self._get_handler()1205
1206# action storage1207self._actions = []1208self._option_string_actions = {}1209
1210# groups1211self._action_groups = []1212self._mutually_exclusive_groups = []1213
1214# defaults storage1215self._defaults = {}1216
1217# determines whether an "option" looks like a negative number1218self._negative_number_matcher = _re.compile(r"^-\d+$|^-\d*\.\d+$")1219
1220# whether or not there are any optionals that look like negative1221# numbers -- uses a list so it can be shared and edited1222self._has_negative_number_optionals = []1223
1224# ====================1225# Registration methods1226# ====================1227def register(self, registry_name, value, object):1228registry = self._registries.setdefault(registry_name, {})1229registry[value] = object1230
1231def _registry_get(self, registry_name, value, default=None):1232return self._registries[registry_name].get(value, default)1233
1234# ==================================1235# Namespace default accessor methods1236# ==================================1237def set_defaults(self, **kwargs):1238self._defaults.update(kwargs)1239
1240# if these defaults match any existing arguments, replace1241# the previous default on the object with the new one1242for action in self._actions:1243if action.dest in kwargs:1244action.default = kwargs[action.dest]1245
1246def get_default(self, dest):1247for action in self._actions:1248if action.dest == dest and action.default is not None:1249return action.default1250return self._defaults.get(dest, None)1251
1252# =======================1253# Adding argument actions1254# =======================1255def add_argument(self, *args, **kwargs):1256"""1257add_argument(dest, ..., name=value, ...)
1258add_argument(option_string, option_string, ..., name=value, ...)
1259"""
1260
1261# if no positional args are supplied or only one is supplied and1262# it doesn't look like an option string, parse a positional1263# argument1264chars = self.prefix_chars1265if not args or len(args) == 1 and args[0][0] not in chars:1266if args and "dest" in kwargs:1267raise ValueError("dest supplied twice for positional argument")1268kwargs = self._get_positional_kwargs(*args, **kwargs)1269
1270# otherwise, we're adding an optional argument1271else:1272kwargs = self._get_optional_kwargs(*args, **kwargs)1273
1274# if no default was supplied, use the parser-level default1275if "default" not in kwargs:1276dest = kwargs["dest"]1277if dest in self._defaults:1278kwargs["default"] = self._defaults[dest]1279elif self.argument_default is not None:1280kwargs["default"] = self.argument_default1281
1282# create the action object, and add it to the parser1283action_class = self._pop_action_class(kwargs)1284if not _callable(action_class):1285raise ValueError('unknown action "%s"' % action_class)1286action = action_class(**kwargs)1287
1288# raise an error if the action type is not callable1289type_func = self._registry_get("type", action.type, action.type)1290if not _callable(type_func):1291raise ValueError("%r is not callable" % type_func)1292
1293return self._add_action(action)1294
1295def add_argument_group(self, *args, **kwargs):1296group = _ArgumentGroup(self, *args, **kwargs)1297self._action_groups.append(group)1298return group1299
1300def add_mutually_exclusive_group(self, **kwargs):1301group = _MutuallyExclusiveGroup(self, **kwargs)1302self._mutually_exclusive_groups.append(group)1303return group1304
1305def _add_action(self, action):1306# resolve any conflicts1307self._check_conflict(action)1308
1309# add to actions list1310self._actions.append(action)1311action.container = self1312
1313# index the action by any option strings it has1314for option_string in action.option_strings:1315self._option_string_actions[option_string] = action1316
1317# set the flag if any option strings look like negative numbers1318for option_string in action.option_strings:1319if self._negative_number_matcher.match(option_string):1320if not self._has_negative_number_optionals:1321self._has_negative_number_optionals.append(True)1322
1323# return the created action1324return action1325
1326def _remove_action(self, action):1327self._actions.remove(action)1328
1329def _add_container_actions(self, container):1330# collect groups by titles1331title_group_map = {}1332for group in self._action_groups:1333if group.title in title_group_map:1334msg = _("cannot merge actions - two groups are named %r")1335raise ValueError(msg % (group.title))1336title_group_map[group.title] = group1337
1338# map each action to its group1339group_map = {}1340for group in container._action_groups:1341
1342# if a group with the title exists, use that, otherwise1343# create a new group matching the container's group1344if group.title not in title_group_map:1345title_group_map[group.title] = self.add_argument_group(1346title=group.title,1347description=group.description,1348conflict_handler=group.conflict_handler,1349)1350
1351# map the actions to their new group1352for action in group._group_actions:1353group_map[action] = title_group_map[group.title]1354
1355# add container's mutually exclusive groups1356# NOTE: if add_mutually_exclusive_group ever gains title= and1357# description= then this code will need to be expanded as above1358for group in container._mutually_exclusive_groups:1359mutex_group = self.add_mutually_exclusive_group(required=group.required)1360
1361# map the actions to their new mutex group1362for action in group._group_actions:1363group_map[action] = mutex_group1364
1365# add all actions to this container or their group1366for action in container._actions:1367group_map.get(action, self)._add_action(action)1368
1369def _get_positional_kwargs(self, dest, **kwargs):1370# make sure required is not specified1371if "required" in kwargs:1372msg = _("'required' is an invalid argument for positionals")1373raise TypeError(msg)1374
1375# mark positional arguments as required if at least one is1376# always required1377if kwargs.get("nargs") not in [OPTIONAL, ZERO_OR_MORE]:1378kwargs["required"] = True1379if kwargs.get("nargs") == ZERO_OR_MORE and "default" not in kwargs:1380kwargs["required"] = True1381
1382# return the keyword arguments with no option strings1383return dict(kwargs, dest=dest, option_strings=[])1384
1385def _get_optional_kwargs(self, *args, **kwargs):1386# determine short and long option strings1387option_strings = []1388long_option_strings = []1389for option_string in args:1390# error on strings that don't start with an appropriate prefix1391if not option_string[0] in self.prefix_chars:1392msg = _("invalid option string %r: " "must start with a character %r")1393tup = option_string, self.prefix_chars1394raise ValueError(msg % tup)1395
1396# strings starting with two prefix characters are long options1397option_strings.append(option_string)1398if option_string[0] in self.prefix_chars:1399if len(option_string) > 1:1400if option_string[1] in self.prefix_chars:1401long_option_strings.append(option_string)1402
1403# infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'1404dest = kwargs.pop("dest", None)1405if dest is None:1406if long_option_strings:1407dest_option_string = long_option_strings[0]1408else:1409dest_option_string = option_strings[0]1410dest = dest_option_string.lstrip(self.prefix_chars)1411if not dest:1412msg = _("dest= is required for options like %r")1413raise ValueError(msg % option_string)1414dest = dest.replace("-", "_")1415
1416# return the updated keyword arguments1417return dict(kwargs, dest=dest, option_strings=option_strings)1418
1419def _pop_action_class(self, kwargs, default=None):1420action = kwargs.pop("action", default)1421return self._registry_get("action", action, action)1422
1423def _get_handler(self):1424# determine function from conflict handler string1425handler_func_name = "_handle_conflict_%s" % self.conflict_handler1426try:1427return getattr(self, handler_func_name)1428except AttributeError:1429msg = _("invalid conflict_resolution value: %r")1430raise ValueError(msg % self.conflict_handler)1431
1432def _check_conflict(self, action):1433
1434# find all options that conflict with this option1435confl_optionals = []1436for option_string in action.option_strings:1437if option_string in self._option_string_actions:1438confl_optional = self._option_string_actions[option_string]1439confl_optionals.append((option_string, confl_optional))1440
1441# resolve any conflicts1442if confl_optionals:1443conflict_handler = self._get_handler()1444conflict_handler(action, confl_optionals)1445
1446def _handle_conflict_error(self, action, conflicting_actions):1447message = _("conflicting option string(s): %s")1448conflict_string = ", ".join(1449[option_string for option_string, action in conflicting_actions]1450)1451raise ArgumentError(action, message % conflict_string)1452
1453def _handle_conflict_resolve(self, action, conflicting_actions):1454
1455# remove all conflicting options1456for option_string, action in conflicting_actions:1457
1458# remove the conflicting option1459action.option_strings.remove(option_string)1460self._option_string_actions.pop(option_string, None)1461
1462# if the option now has no option string, remove it from the1463# container holding it1464if not action.option_strings:1465action.container._remove_action(action)1466
1467
1468class _ArgumentGroup(_ActionsContainer):1469def __init__(self, container, title=None, description=None, **kwargs):1470# add any missing keyword arguments by checking the container1471update = kwargs.setdefault1472update("conflict_handler", container.conflict_handler)1473update("prefix_chars", container.prefix_chars)1474update("argument_default", container.argument_default)1475super_init = super(_ArgumentGroup, self).__init__1476super_init(description=description, **kwargs)1477
1478# group attributes1479self.title = title1480self._group_actions = []1481
1482# share most attributes with the container1483self._registries = container._registries1484self._actions = container._actions1485self._option_string_actions = container._option_string_actions1486self._defaults = container._defaults1487self._has_negative_number_optionals = container._has_negative_number_optionals1488
1489def _add_action(self, action):1490action = super(_ArgumentGroup, self)._add_action(action)1491self._group_actions.append(action)1492return action1493
1494def _remove_action(self, action):1495super(_ArgumentGroup, self)._remove_action(action)1496self._group_actions.remove(action)1497
1498
1499class _MutuallyExclusiveGroup(_ArgumentGroup):1500def __init__(self, container, required=False):1501super(_MutuallyExclusiveGroup, self).__init__(container)1502self.required = required1503self._container = container1504
1505def _add_action(self, action):1506if action.required:1507msg = _("mutually exclusive arguments must be optional")1508raise ValueError(msg)1509action = self._container._add_action(action)1510self._group_actions.append(action)1511return action1512
1513def _remove_action(self, action):1514self._container._remove_action(action)1515self._group_actions.remove(action)1516
1517
1518class ArgumentParser(_AttributeHolder, _ActionsContainer):1519"""Object for parsing command line strings into Python objects.1520
1521Keyword Arguments:
1522- prog -- The name of the program (default: sys.argv[0])
1523- usage -- A usage message (default: auto-generated from arguments)
1524- description -- A description of what the program does
1525- epilog -- Text following the argument descriptions
1526- parents -- Parsers whose arguments should be copied into this one
1527- formatter_class -- HelpFormatter class for printing help messages
1528- prefix_chars -- Characters that prefix optional arguments
1529- fromfile_prefix_chars -- Characters that prefix files containing
1530additional arguments
1531- argument_default -- The default value for all arguments
1532- conflict_handler -- String indicating how to handle conflicts
1533- add_help -- Add a -h/-help option
1534"""
1535
1536def __init__(1537self,1538prog=None,1539usage=None,1540description=None,1541epilog=None,1542version=None,1543parents=[],1544formatter_class=HelpFormatter,1545prefix_chars="-",1546fromfile_prefix_chars=None,1547argument_default=None,1548conflict_handler="error",1549add_help=True,1550):1551
1552if version is not None:1553import warnings1554
1555warnings.warn(1556"""The "version" argument to ArgumentParser is deprecated. """1557"""Please use """1558""""add_argument(..., action='version', version="N", ...)" """1559"""instead""",1560DeprecationWarning,1561)1562
1563superinit = super(ArgumentParser, self).__init__1564superinit(1565description=description,1566prefix_chars=prefix_chars,1567argument_default=argument_default,1568conflict_handler=conflict_handler,1569)1570
1571# default setting for prog1572if prog is None:1573prog = _os.path.basename(_sys.argv[0])1574
1575self.prog = prog1576self.usage = usage1577self.epilog = epilog1578self.version = version1579self.formatter_class = formatter_class1580self.fromfile_prefix_chars = fromfile_prefix_chars1581self.add_help = add_help1582
1583add_group = self.add_argument_group1584self._positionals = add_group(_("positional arguments"))1585self._optionals = add_group(_("optional arguments"))1586self._subparsers = None1587
1588# register types1589def identity(string):1590return string1591
1592self.register("type", None, identity)1593
1594# add help and version arguments if necessary1595# (using explicit default to override global argument_default)1596if self.add_help:1597self.add_argument(1598"-h",1599"--help",1600action="help",1601default=SUPPRESS,1602help=_("show this help message and exit"),1603)1604if self.version:1605self.add_argument(1606"-v",1607"--version",1608action="version",1609default=SUPPRESS,1610version=self.version,1611help=_("show program's version number and exit"),1612)1613
1614# add parent arguments and defaults1615for parent in parents:1616self._add_container_actions(parent)1617try:1618defaults = parent._defaults1619except AttributeError:1620pass1621else:1622self._defaults.update(defaults)1623
1624# =======================1625# Pretty __repr__ methods1626# =======================1627def _get_kwargs(self):1628names = [1629"prog",1630"usage",1631"description",1632"version",1633"formatter_class",1634"conflict_handler",1635"add_help",1636]1637return [(name, getattr(self, name)) for name in names]1638
1639# ==================================1640# Optional/Positional adding methods1641# ==================================1642def add_subparsers(self, **kwargs):1643if self._subparsers is not None:1644self.error(_("cannot have multiple subparser arguments"))1645
1646# add the parser class to the arguments if it's not present1647kwargs.setdefault("parser_class", type(self))1648
1649if "title" in kwargs or "description" in kwargs:1650title = _(kwargs.pop("title", "subcommands"))1651description = _(kwargs.pop("description", None))1652self._subparsers = self.add_argument_group(title, description)1653else:1654self._subparsers = self._positionals1655
1656# prog defaults to the usage message of this parser, skipping1657# optional arguments and with no "usage:" prefix1658if kwargs.get("prog") is None:1659formatter = self._get_formatter()1660positionals = self._get_positional_actions()1661groups = self._mutually_exclusive_groups1662formatter.add_usage(self.usage, positionals, groups, "")1663kwargs["prog"] = formatter.format_help().strip()1664
1665# create the parsers action and add it to the positionals list1666parsers_class = self._pop_action_class(kwargs, "parsers")1667action = parsers_class(option_strings=[], **kwargs)1668self._subparsers._add_action(action)1669
1670# return the created parsers action1671return action1672
1673def _add_action(self, action):1674if action.option_strings:1675self._optionals._add_action(action)1676else:1677self._positionals._add_action(action)1678return action1679
1680def _get_optional_actions(self):1681return [action for action in self._actions if action.option_strings]1682
1683def _get_positional_actions(self):1684return [action for action in self._actions if not action.option_strings]1685
1686# =====================================1687# Command line argument parsing methods1688# =====================================1689def parse_args(self, args=None, namespace=None):1690args, argv = self.parse_known_args(args, namespace)1691if argv:1692msg = _("unrecognized arguments: %s")1693self.error(msg % " ".join(argv))1694return args1695
1696def parse_known_args(self, args=None, namespace=None):1697# args default to the system args1698if args is None:1699args = _sys.argv[1:]1700
1701# default Namespace built from parser defaults1702if namespace is None:1703namespace = Namespace()1704
1705# add any action defaults that aren't present1706for action in self._actions:1707if action.dest is not SUPPRESS:1708if not hasattr(namespace, action.dest):1709if action.default is not SUPPRESS:1710default = action.default1711if isinstance(action.default, _basestring):1712default = self._get_value(action, default)1713setattr(namespace, action.dest, default)1714
1715# add any parser defaults that aren't present1716for dest in self._defaults:1717if not hasattr(namespace, dest):1718setattr(namespace, dest, self._defaults[dest])1719
1720# parse the arguments and exit if there are any errors1721try:1722return self._parse_known_args(args, namespace)1723except ArgumentError:1724err = _sys.exc_info()[1]1725self.error(str(err))1726
1727def _parse_known_args(self, arg_strings, namespace):1728# replace arg strings that are file references1729if self.fromfile_prefix_chars is not None:1730arg_strings = self._read_args_from_files(arg_strings)1731
1732# map all mutually exclusive arguments to the other arguments1733# they can't occur with1734action_conflicts = {}1735for mutex_group in self._mutually_exclusive_groups:1736group_actions = mutex_group._group_actions1737for i, mutex_action in enumerate(mutex_group._group_actions):1738conflicts = action_conflicts.setdefault(mutex_action, [])1739conflicts.extend(group_actions[:i])1740conflicts.extend(group_actions[i + 1 :])1741
1742# find all option indices, and determine the arg_string_pattern1743# which has an 'O' if there is an option at an index,1744# an 'A' if there is an argument, or a '-' if there is a '--'1745option_string_indices = {}1746arg_string_pattern_parts = []1747arg_strings_iter = iter(arg_strings)1748for i, arg_string in enumerate(arg_strings_iter):1749
1750# all args after -- are non-options1751if arg_string == "--":1752arg_string_pattern_parts.append("-")1753for arg_string in arg_strings_iter:1754arg_string_pattern_parts.append("A")1755
1756# otherwise, add the arg to the arg strings1757# and note the index if it was an option1758else:1759option_tuple = self._parse_optional(arg_string)1760if option_tuple is None:1761pattern = "A"1762else:1763option_string_indices[i] = option_tuple1764pattern = "O"1765arg_string_pattern_parts.append(pattern)1766
1767# join the pieces together to form the pattern1768arg_strings_pattern = "".join(arg_string_pattern_parts)1769
1770# converts arg strings to the appropriate and then takes the action1771seen_actions = _set()1772seen_non_default_actions = _set()1773
1774def take_action(action, argument_strings, option_string=None):1775seen_actions.add(action)1776argument_values = self._get_values(action, argument_strings)1777
1778# error if this argument is not allowed with other previously1779# seen arguments, assuming that actions that use the default1780# value don't really count as "present"1781if argument_values is not action.default:1782seen_non_default_actions.add(action)1783for conflict_action in action_conflicts.get(action, []):1784if conflict_action in seen_non_default_actions:1785msg = _("not allowed with argument %s")1786action_name = _get_action_name(conflict_action)1787raise ArgumentError(action, msg % action_name)1788
1789# take the action if we didn't receive a SUPPRESS value1790# (e.g. from a default)1791if argument_values is not SUPPRESS:1792action(self, namespace, argument_values, option_string)1793
1794# function to convert arg_strings into an optional action1795def consume_optional(start_index):1796
1797# get the optional identified at this index1798option_tuple = option_string_indices[start_index]1799action, option_string, explicit_arg = option_tuple1800
1801# identify additional optionals in the same arg string1802# (e.g. -xyz is the same as -x -y -z if no args are required)1803match_argument = self._match_argument1804action_tuples = []1805while True:1806
1807# if we found no optional action, skip it1808if action is None:1809extras.append(arg_strings[start_index])1810return start_index + 11811
1812# if there is an explicit argument, try to match the1813# optional's string arguments to only this1814if explicit_arg is not None:1815arg_count = match_argument(action, "A")1816
1817# if the action is a single-dash option and takes no1818# arguments, try to parse more single-dash options out1819# of the tail of the option string1820chars = self.prefix_chars1821if arg_count == 0 and option_string[1] not in chars:1822action_tuples.append((action, [], option_string))1823for char in self.prefix_chars:1824option_string = char + explicit_arg[0]1825explicit_arg = explicit_arg[1:] or None1826optionals_map = self._option_string_actions1827if option_string in optionals_map:1828action = optionals_map[option_string]1829break1830else:1831msg = _("ignored explicit argument %r")1832raise ArgumentError(action, msg % explicit_arg)1833
1834# if the action expect exactly one argument, we've1835# successfully matched the option; exit the loop1836elif arg_count == 1:1837stop = start_index + 11838args = [explicit_arg]1839action_tuples.append((action, args, option_string))1840break1841
1842# error if a double-dash option did not use the1843# explicit argument1844else:1845msg = _("ignored explicit argument %r")1846raise ArgumentError(action, msg % explicit_arg)1847
1848# if there is no explicit argument, try to match the1849# optional's string arguments with the following strings1850# if successful, exit the loop1851else:1852start = start_index + 11853selected_patterns = arg_strings_pattern[start:]1854arg_count = match_argument(action, selected_patterns)1855stop = start + arg_count1856args = arg_strings[start:stop]1857action_tuples.append((action, args, option_string))1858break1859
1860# add the Optional to the list and return the index at which1861# the Optional's string args stopped1862assert action_tuples1863for action, args, option_string in action_tuples:1864take_action(action, args, option_string)1865return stop1866
1867# the list of Positionals left to be parsed; this is modified1868# by consume_positionals()1869positionals = self._get_positional_actions()1870
1871# function to convert arg_strings into positional actions1872def consume_positionals(start_index):1873# match as many Positionals as possible1874match_partial = self._match_arguments_partial1875selected_pattern = arg_strings_pattern[start_index:]1876arg_counts = match_partial(positionals, selected_pattern)1877
1878# slice off the appropriate arg strings for each Positional1879# and add the Positional and its args to the list1880for action, arg_count in zip(positionals, arg_counts):1881args = arg_strings[start_index : start_index + arg_count]1882start_index += arg_count1883take_action(action, args)1884
1885# slice off the Positionals that we just parsed and return the1886# index at which the Positionals' string args stopped1887positionals[:] = positionals[len(arg_counts) :]1888return start_index1889
1890# consume Positionals and Optionals alternately, until we have1891# passed the last option string1892extras = []1893start_index = 01894if option_string_indices:1895max_option_string_index = max(option_string_indices)1896else:1897max_option_string_index = -11898while start_index <= max_option_string_index:1899
1900# consume any Positionals preceding the next option1901next_option_string_index = min(1902[index for index in option_string_indices if index >= start_index]1903)1904if start_index != next_option_string_index:1905positionals_end_index = consume_positionals(start_index)1906
1907# only try to parse the next optional if we didn't consume1908# the option string during the positionals parsing1909if positionals_end_index > start_index:1910start_index = positionals_end_index1911continue1912else:1913start_index = positionals_end_index1914
1915# if we consumed all the positionals we could and we're not1916# at the index of an option string, there were extra arguments1917if start_index not in option_string_indices:1918strings = arg_strings[start_index:next_option_string_index]1919extras.extend(strings)1920start_index = next_option_string_index1921
1922# consume the next optional and any arguments for it1923start_index = consume_optional(start_index)1924
1925# consume any positionals following the last Optional1926stop_index = consume_positionals(start_index)1927
1928# if we didn't consume all the argument strings, there were extras1929extras.extend(arg_strings[stop_index:])1930
1931# if we didn't use all the Positional objects, there were too few1932# arg strings supplied.1933if positionals:1934self.error(_("too few arguments"))1935
1936# make sure all required actions were present1937for action in self._actions:1938if action.required:1939if action not in seen_actions:1940name = _get_action_name(action)1941self.error(_("argument %s is required") % name)1942
1943# make sure all required groups had one option present1944for group in self._mutually_exclusive_groups:1945if group.required:1946for action in group._group_actions:1947if action in seen_non_default_actions:1948break1949
1950# if no actions were used, report the error1951else:1952names = [1953_get_action_name(action)1954for action in group._group_actions1955if action.help is not SUPPRESS1956]1957msg = _("one of the arguments %s is required")1958self.error(msg % " ".join(names))1959
1960# return the updated namespace and the extra arguments1961return namespace, extras1962
1963def _read_args_from_files(self, arg_strings):1964# expand arguments referencing files1965new_arg_strings = []1966for arg_string in arg_strings:1967
1968# for regular arguments, just add them back into the list1969if arg_string[0] not in self.fromfile_prefix_chars:1970new_arg_strings.append(arg_string)1971
1972# replace arguments referencing files with the file content1973else:1974try:1975args_file = open(arg_string[1:])1976try:1977arg_strings = []1978for arg_line in args_file.read().splitlines():1979for arg in self.convert_arg_line_to_args(arg_line):1980arg_strings.append(arg)1981arg_strings = self._read_args_from_files(arg_strings)1982new_arg_strings.extend(arg_strings)1983finally:1984args_file.close()1985except IOError:1986err = _sys.exc_info()[1]1987self.error(str(err))1988
1989# return the modified argument list1990return new_arg_strings1991
1992def convert_arg_line_to_args(self, arg_line):1993return [arg_line]1994
1995def _match_argument(self, action, arg_strings_pattern):1996# match the pattern for this action to the arg strings1997nargs_pattern = self._get_nargs_pattern(action)1998match = _re.match(nargs_pattern, arg_strings_pattern)1999
2000# raise an exception if we weren't able to find a match2001if match is None:2002nargs_errors = {2003None: _("expected one argument"),2004OPTIONAL: _("expected at most one argument"),2005ONE_OR_MORE: _("expected at least one argument"),2006}2007default = _("expected %s argument(s)") % action.nargs2008msg = nargs_errors.get(action.nargs, default)2009raise ArgumentError(action, msg)2010
2011# return the number of arguments matched2012return len(match.group(1))2013
2014def _match_arguments_partial(self, actions, arg_strings_pattern):2015# progressively shorten the actions list by slicing off the2016# final actions until we find a match2017result = []2018for i in range(len(actions), 0, -1):2019actions_slice = actions[:i]2020pattern = "".join(2021[self._get_nargs_pattern(action) for action in actions_slice]2022)2023match = _re.match(pattern, arg_strings_pattern)2024if match is not None:2025result.extend([len(string) for string in match.groups()])2026break2027
2028# return the list of arg string counts2029return result2030
2031def _parse_optional(self, arg_string):2032# if it's an empty string, it was meant to be a positional2033if not arg_string:2034return None2035
2036# if it doesn't start with a prefix, it was meant to be positional2037if not arg_string[0] in self.prefix_chars:2038return None2039
2040# if the option string is present in the parser, return the action2041if arg_string in self._option_string_actions:2042action = self._option_string_actions[arg_string]2043return action, arg_string, None2044
2045# if it's just a single character, it was meant to be positional2046if len(arg_string) == 1:2047return None2048
2049# if the option string before the "=" is present, return the action2050if "=" in arg_string:2051option_string, explicit_arg = arg_string.split("=", 1)2052if option_string in self._option_string_actions:2053action = self._option_string_actions[option_string]2054return action, option_string, explicit_arg2055
2056# search through all possible prefixes of the option string2057# and all actions in the parser for possible interpretations2058option_tuples = self._get_option_tuples(arg_string)2059
2060# if multiple actions match, the option string was ambiguous2061if len(option_tuples) > 1:2062options = ", ".join(2063[option_string for action, option_string, explicit_arg in option_tuples]2064)2065tup = arg_string, options2066self.error(_("ambiguous option: %s could match %s") % tup)2067
2068# if exactly one action matched, this segmentation is good,2069# so return the parsed action2070elif len(option_tuples) == 1:2071(option_tuple,) = option_tuples2072return option_tuple2073
2074# if it was not found as an option, but it looks like a negative2075# number, it was meant to be positional2076# unless there are negative-number-like options2077if self._negative_number_matcher.match(arg_string):2078if not self._has_negative_number_optionals:2079return None2080
2081# if it contains a space, it was meant to be a positional2082if " " in arg_string:2083return None2084
2085# it was meant to be an optional but there is no such option2086# in this parser (though it might be a valid option in a subparser)2087return None, arg_string, None2088
2089def _get_option_tuples(self, option_string):2090result = []2091
2092# option strings starting with two prefix characters are only2093# split at the '='2094chars = self.prefix_chars2095if option_string[0] in chars and option_string[1] in chars:2096if "=" in option_string:2097option_prefix, explicit_arg = option_string.split("=", 1)2098else:2099option_prefix = option_string2100explicit_arg = None2101for option_string in self._option_string_actions:2102if option_string.startswith(option_prefix):2103action = self._option_string_actions[option_string]2104tup = action, option_string, explicit_arg2105result.append(tup)2106
2107# single character options can be concatenated with their arguments2108# but multiple character options always have to have their argument2109# separate2110elif option_string[0] in chars and option_string[1] not in chars:2111option_prefix = option_string2112explicit_arg = None2113short_option_prefix = option_string[:2]2114short_explicit_arg = option_string[2:]2115
2116for option_string in self._option_string_actions:2117if option_string == short_option_prefix:2118action = self._option_string_actions[option_string]2119tup = action, option_string, short_explicit_arg2120result.append(tup)2121elif option_string.startswith(option_prefix):2122action = self._option_string_actions[option_string]2123tup = action, option_string, explicit_arg2124result.append(tup)2125
2126# shouldn't ever get here2127else:2128self.error(_("unexpected option string: %s") % option_string)2129
2130# return the collected option tuples2131return result2132
2133def _get_nargs_pattern(self, action):2134# in all examples below, we have to allow for '--' args2135# which are represented as '-' in the pattern2136nargs = action.nargs2137
2138# the default (None) is assumed to be a single argument2139if nargs is None:2140nargs_pattern = "(-*A-*)"2141
2142# allow zero or one arguments2143elif nargs == OPTIONAL:2144nargs_pattern = "(-*A?-*)"2145
2146# allow zero or more arguments2147elif nargs == ZERO_OR_MORE:2148nargs_pattern = "(-*[A-]*)"2149
2150# allow one or more arguments2151elif nargs == ONE_OR_MORE:2152nargs_pattern = "(-*A[A-]*)"2153
2154# allow any number of options or arguments2155elif nargs == REMAINDER:2156nargs_pattern = "([-AO]*)"2157
2158# allow one argument followed by any number of options or arguments2159elif nargs == PARSER:2160nargs_pattern = "(-*A[-AO]*)"2161
2162# all others should be integers2163else:2164nargs_pattern = "(-*%s-*)" % "-*".join("A" * nargs)2165
2166# if this is an optional action, -- is not allowed2167if action.option_strings:2168nargs_pattern = nargs_pattern.replace("-*", "")2169nargs_pattern = nargs_pattern.replace("-", "")2170
2171# return the pattern2172return nargs_pattern2173
2174# ========================2175# Value conversion methods2176# ========================2177def _get_values(self, action, arg_strings):2178# for everything but PARSER args, strip out '--'2179if action.nargs not in [PARSER, REMAINDER]:2180arg_strings = [s for s in arg_strings if s != "--"]2181
2182# optional argument produces a default when not present2183if not arg_strings and action.nargs == OPTIONAL:2184if action.option_strings:2185value = action.const2186else:2187value = action.default2188if isinstance(value, _basestring):2189value = self._get_value(action, value)2190self._check_value(action, value)2191
2192# when nargs='*' on a positional, if there were no command-line2193# args, use the default if it is anything other than None2194elif (2195not arg_strings2196and action.nargs == ZERO_OR_MORE2197and not action.option_strings2198):2199if action.default is not None:2200value = action.default2201else:2202value = arg_strings2203self._check_value(action, value)2204
2205# single argument or optional argument produces a single value2206elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:2207(arg_string,) = arg_strings2208value = self._get_value(action, arg_string)2209self._check_value(action, value)2210
2211# REMAINDER arguments convert all values, checking none2212elif action.nargs == REMAINDER:2213value = [self._get_value(action, v) for v in arg_strings]2214
2215# PARSER arguments convert all values, but check only the first2216elif action.nargs == PARSER:2217value = [self._get_value(action, v) for v in arg_strings]2218self._check_value(action, value[0])2219
2220# all other types of nargs produce a list2221else:2222value = [self._get_value(action, v) for v in arg_strings]2223for v in value:2224self._check_value(action, v)2225
2226# return the converted value2227return value2228
2229def _get_value(self, action, arg_string):2230type_func = self._registry_get("type", action.type, action.type)2231if not _callable(type_func):2232msg = _("%r is not callable")2233raise ArgumentError(action, msg % type_func)2234
2235# convert the value to the appropriate type2236try:2237result = type_func(arg_string)2238
2239# ArgumentTypeErrors indicate errors2240except ArgumentTypeError:2241name = getattr(action.type, "__name__", repr(action.type))2242msg = str(_sys.exc_info()[1])2243raise ArgumentError(action, msg)2244
2245# TypeErrors or ValueErrors also indicate errors2246except (TypeError, ValueError):2247name = getattr(action.type, "__name__", repr(action.type))2248msg = _("invalid %s value: %r")2249raise ArgumentError(action, msg % (name, arg_string))2250
2251# return the converted value2252return result2253
2254def _check_value(self, action, value):2255# converted value must be one of the choices (if specified)2256if action.choices is not None and value not in action.choices:2257tup = value, ", ".join(map(repr, action.choices))2258msg = _("invalid choice: %r (choose from %s)") % tup2259raise ArgumentError(action, msg)2260
2261# =======================2262# Help-formatting methods2263# =======================2264def format_usage(self):2265formatter = self._get_formatter()2266formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)2267return formatter.format_help()2268
2269def format_help(self):2270formatter = self._get_formatter()2271
2272# usage2273formatter.add_usage(self.usage, self._actions, self._mutually_exclusive_groups)2274
2275# description2276formatter.add_text(self.description)2277
2278# positionals, optionals and user-defined groups2279for action_group in self._action_groups:2280formatter.start_section(action_group.title)2281formatter.add_text(action_group.description)2282formatter.add_arguments(action_group._group_actions)2283formatter.end_section()2284
2285# epilog2286formatter.add_text(self.epilog)2287
2288# determine help from format above2289return formatter.format_help()2290
2291def format_version(self):2292import warnings2293
2294warnings.warn(2295'The format_version method is deprecated -- the "version" '2296"argument to ArgumentParser is no longer supported.",2297DeprecationWarning,2298)2299formatter = self._get_formatter()2300formatter.add_text(self.version)2301return formatter.format_help()2302
2303def _get_formatter(self):2304return self.formatter_class(prog=self.prog)2305
2306# =====================2307# Help-printing methods2308# =====================2309def print_usage(self, file=None):2310if file is None:2311file = _sys.stdout2312self._print_message(self.format_usage(), file)2313
2314def print_help(self, file=None):2315if file is None:2316file = _sys.stdout2317self._print_message(self.format_help(), file)2318
2319def print_version(self, file=None):2320import warnings2321
2322warnings.warn(2323'The print_version method is deprecated -- the "version" '2324"argument to ArgumentParser is no longer supported.",2325DeprecationWarning,2326)2327self._print_message(self.format_version(), file)2328
2329def _print_message(self, message, file=None):2330if message:2331if file is None:2332file = _sys.stderr2333file.write(message)2334
2335# ===============2336# Exiting methods2337# ===============2338def exit(self, status=0, message=None):2339if message:2340self._print_message(message, _sys.stderr)2341_sys.exit(status)2342
2343def error(self, message):2344"""error(message: string)2345
2346Prints a usage message incorporating the message to stderr and
2347exits.
2348
2349If you override this in a subclass, it should not return -- it
2350should either exit or raise an exception.
2351"""
2352self.print_usage(_sys.stderr)2353self.exit(2, _("%s: error: %s\n") % (self.prog, message))2354