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