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