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