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