17 """Command-line parsing library
19 This module is an optparse-inspired command-line parsing library that:
21 - handles both optional and positional arguments
22 - produces highly informative usage messages
23 - supports parsers that dispatch to sub-parsers
25 The following is a simple usage example that sums integers from the
26 command-line and writes the result to a file::
28 parser = argparse.ArgumentParser(
29 description='sum the integers at the command line')
31 'integers', metavar='int', nargs='+', type=int,
32 help='an integer to be summed')
34 '--log', default=sys.stdout, type=argparse.FileType('w'),
35 help='the file where the sum should be written')
36 args = parser.parse_args()
37 args.log.write('%s' % sum(args.integers))
40 The module contains the following public classes:
42 - ArgumentParser -- The main entry point for command-line parsing. As the
43 example above shows, the add_argument() method is used to populate
44 the parser with actions for optional and positional arguments. Then
45 the parse_args() method is invoked to convert the args at the
46 command-line into an object with attributes.
48 - ArgumentError -- The exception raised by ArgumentParser objects when
49 there are errors with the parser's actions. Errors raised while
50 parsing the command-line are caught by ArgumentParser and emitted
51 as command-line messages.
53 - FileType -- A factory for defining types of files to be created. As the
54 example above shows, instances of FileType are typically passed as
55 the type= argument of add_argument() calls.
57 - Action -- The base class for parser actions. Typically actions are
58 selected by passing strings like 'store_true' or 'append_const' to
59 the action= argument of add_argument(). However, for greater
60 customization of ArgumentParser actions, subclasses of Action may
61 be defined and passed as the action= argument.
63 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
64 ArgumentDefaultsHelpFormatter -- Formatter classes which
65 may be passed as the formatter_class= argument to the
66 ArgumentParser constructor. HelpFormatter is the default,
67 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
68 not to change the formatting for help text, and
69 ArgumentDefaultsHelpFormatter adds information about argument defaults
72 All other classes in this module are considered implementation details.
73 (Also note that HelpFormatter and RawDescriptionHelpFormatter are only
74 considered public as object names -- the API of the formatter objects is
75 still considered an implementation detail.)
86 'RawDescriptionHelpFormatter',
87 'RawTextHelpFormatter',
88 'ArgumentDefaultsHelpFormatter',
96 import textwrap
as _textwrap
98 from gettext
import gettext
as _
103 from sets
import Set
as _set
106 _basestring = basestring
115 result =
list(iterable)
123 return hasattr(obj,
'__call__')
or hasattr(obj,
'__bases__')
126 if _sys.version_info[:2] == (2, 6):
128 warnings.filterwarnings(
130 message=
'BaseException.message has been deprecated as of Python 2.6',
131 category=DeprecationWarning,
135 SUPPRESS =
'==SUPPRESS=='
148 """Abstract base class that provides __repr__.
150 The __repr__ method returns a string in the format::
151 ClassName(attr=name, attr=name, ...)
152 The attributes are determined either by a class-level attribute,
153 '_kwarg_names', or by inspecting the instance __dict__.
157 type_name = type(self).__name__
160 arg_strings.append(repr(arg))
162 arg_strings.append(
'%s=%r' % (name, value))
163 return '%s(%s)' % (type_name,
', '.
join(arg_strings))
166 return _sorted(self.__dict__.items())
173 if getattr(namespace, name,
None)
is None:
174 setattr(namespace, name, value)
175 return getattr(namespace, name)
183 """Formatter for generating usage messages and argument help strings.
185 Only the name of this class is considered a public API. All the methods
186 provided by the class are considered an implementation detail.
192 max_help_position=24,
198 width = int(_os.environ[
'COLUMNS'])
199 except (KeyError, ValueError):
232 def __init__(self, formatter, parent, heading=None):
240 if self.
parent is not None:
241 self.formatter._indent()
242 join = self.formatter._join_parts
243 for func, args
in self.
items:
245 item_help =
join([func(*args)
for func, args
in self.
items])
246 if self.
parent is not None:
247 self.formatter._dedent()
255 current_indent = self.formatter._current_indent
256 heading =
'%*s%s:\n' % (current_indent,
'', self.
heading)
261 return join([
'\n', heading, item_help,
'\n'])
264 self._current_section.items.append((func, args))
280 if text
is not SUPPRESS
and text
is not None:
283 def add_usage(self, usage, actions, groups, prefix=None):
284 if usage
is not SUPPRESS:
285 args = usage, actions, groups, prefix
289 if action.help
is not SUPPRESS:
293 invocations = [get_invocation(action)]
295 invocations.append(get_invocation(subaction))
298 invocation_length =
max([len(s)
for s
in invocations])
307 for action
in actions:
314 help = self._root_section.format_help()
316 help = self._long_break_matcher.sub(
'\n\n', help)
317 help = help.strip(
'\n') +
'\n'
322 for part
in part_strings
323 if part
and part
is not SUPPRESS])
327 prefix = _(
'usage: ')
330 if usage
is not None:
334 elif usage
is None and not actions:
335 usage =
'%(prog)s' %
dict(prog=self.
_prog)
339 prog =
'%(prog)s' %
dict(prog=self.
_prog)
344 for action
in actions:
345 if action.option_strings:
346 optionals.append(action)
348 positionals.append(action)
352 action_usage =
format(optionals + positionals, groups)
353 usage =
' '.
join([s
for s
in [prog, action_usage]
if s])
357 if len(prefix) + len(usage) > text_width:
360 part_regexp =
r'\(.*?\)+|\[.*?\]+|\S+'
361 opt_usage =
format(optionals, groups)
362 pos_usage =
format(positionals, groups)
363 opt_parts = _re.findall(part_regexp, opt_usage)
364 pos_parts = _re.findall(part_regexp, pos_usage)
365 assert ' '.
join(opt_parts) == opt_usage
366 assert ' '.
join(pos_parts) == pos_usage
369 def get_lines(parts, indent, prefix=None):
372 if prefix
is not None:
373 line_len = len(prefix) - 1
375 line_len = len(indent) - 1
377 if line_len + 1 + len(part) > text_width:
378 lines.append(indent +
' '.
join(line))
380 line_len = len(indent) - 1
382 line_len += len(part) + 1
384 lines.append(indent +
' '.
join(line))
385 if prefix
is not None:
386 lines[0] = lines[0][len(indent):]
390 if len(prefix) + len(prog) <= 0.75 * text_width:
391 indent =
' ' * (len(prefix) + len(prog) + 1)
393 lines = get_lines([prog] + opt_parts, indent, prefix)
394 lines.extend(get_lines(pos_parts, indent))
396 lines = get_lines([prog] + pos_parts, indent, prefix)
402 indent =
' ' * len(prefix)
403 parts = opt_parts + pos_parts
404 lines = get_lines(parts, indent)
407 lines.extend(get_lines(opt_parts, indent))
408 lines.extend(get_lines(pos_parts, indent))
409 lines = [prog] + lines
412 usage =
'\n'.
join(lines)
415 return '%s%s\n\n' % (prefix, usage)
419 group_actions =
_set()
423 start = actions.index(group._group_actions[0])
427 end = start + len(group._group_actions)
428 if actions[start:end] == group._group_actions:
429 for action
in group._group_actions:
430 group_actions.add(action)
431 if not group.required:
437 for i
in range(start + 1, end):
442 for i, action
in enumerate(actions):
446 if action.help
is SUPPRESS:
448 if inserts.get(i) ==
'|':
450 elif inserts.get(i + 1) ==
'|':
454 elif not action.option_strings:
458 if action
in group_actions:
459 if part[0] ==
'[' and part[-1] ==
']':
467 option_string = action.option_strings[0]
471 if action.nargs == 0:
472 part =
'%s' % option_string
477 default = action.dest.upper()
479 part =
'%s %s' % (option_string, args_string)
482 if not action.required
and action
not in group_actions:
489 for i
in _sorted(inserts, reverse=
True):
490 parts[i:i] = [inserts[i]]
493 text =
' '.
join([item
for item
in parts
if item
is not None])
498 text = _re.sub(
r'(%s) ' % open,
r'\1', text)
499 text = _re.sub(
r' (%s)' % close,
r'\1', text)
500 text = _re.sub(
r'%s *%s' % (open, close),
r'', text)
501 text = _re.sub(
r'\(([^|]*)\)',
r'\1', text)
508 if '%(prog)' in text:
512 return self.
_fill_text(text, text_width, indent) +
'\n\n'
518 help_width = self.
_width - help_position
525 action_header =
'%*s%s\n' % tup
528 elif len(action_header) <= action_width:
530 action_header =
'%*s%-*s ' % tup
536 action_header =
'%*s%s\n' % tup
537 indent_first = help_position
540 parts = [action_header]
546 parts.append(
'%*s%s\n' % (indent_first,
'', help_lines[0]))
547 for line
in help_lines[1:]:
548 parts.append(
'%*s%s\n' % (help_position,
'', line))
551 elif not action_header.endswith(
'\n'):
562 if not action.option_strings:
571 if action.nargs == 0:
572 parts.extend(action.option_strings)
577 default = action.dest.upper()
579 for option_string
in action.option_strings:
580 parts.append(
'%s %s' % (option_string, args_string))
582 return ', '.
join(parts)
585 if action.metavar
is not None:
586 result = action.metavar
587 elif action.choices
is not None:
588 choice_strs = [str(choice)
for choice
in action.choices]
589 result =
'{%s}' %
','.
join(choice_strs)
591 result = default_metavar
594 if isinstance(result, tuple):
597 return (result, ) * tuple_size
602 if action.nargs
is None:
603 result =
'%s' % get_metavar(1)
604 elif action.nargs == OPTIONAL:
605 result =
'[%s]' % get_metavar(1)
606 elif action.nargs == ZERO_OR_MORE:
607 result =
'[%s [%s ...]]' % get_metavar(2)
608 elif action.nargs == ONE_OR_MORE:
609 result =
'%s [%s ...]' % get_metavar(2)
610 elif action.nargs == REMAINDER:
612 elif action.nargs == PARSER:
613 result =
'%s ...' % get_metavar(1)
615 formats = [
'%s' for _
in range(action.nargs)]
616 result =
' '.
join(formats) % get_metavar(action.nargs)
620 params =
dict(vars(action), prog=self.
_prog)
621 for name
in list(params):
622 if params[name]
is SUPPRESS:
624 for name
in list(params):
625 if hasattr(params[name],
'__name__'):
626 params[name] = params[name].__name__
627 if params.get(
'choices')
is not None:
628 choices_str =
', '.
join([str(c)
for c
in params[
'choices']])
629 params[
'choices'] = choices_str
634 get_subactions = action._get_subactions
635 except AttributeError:
639 for subaction
in get_subactions():
644 text = self._whitespace_matcher.sub(
' ', text).strip()
645 return _textwrap.wrap(text, width)
648 text = self._whitespace_matcher.sub(
' ', text).strip()
649 return _textwrap.fill(text, width, initial_indent=indent,
650 subsequent_indent=indent)
657 """Help message formatter which retains any formatting in descriptions.
659 Only the name of this class is considered a public API. All the methods
660 provided by the class are considered an implementation detail.
664 return ''.
join([indent + line
for line
in text.splitlines(
True)])
668 """Help message formatter which retains formatting of all help text.
670 Only the name of this class is considered a public API. All the methods
671 provided by the class are considered an implementation detail.
675 return text.splitlines()
679 """Help message formatter which adds default values to argument help.
681 Only the name of this class is considered a public API. All the methods
682 provided by the class are considered an implementation detail.
687 if '%(default)' not in action.help:
688 if action.default
is not SUPPRESS:
689 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
690 if action.option_strings
or action.nargs
in defaulting_nargs:
691 help +=
' (default: %(default)s)'
702 elif argument.option_strings:
703 return '/'.
join(argument.option_strings)
704 elif argument.metavar
not in (
None, SUPPRESS):
705 return argument.metavar
706 elif argument.dest
not in (
None, SUPPRESS):
713 """An error from creating or using an argument (optional or positional).
715 The string value of this exception is the message, augmented with
716 information about the argument that caused it.
725 format =
'%(message)s'
727 format =
'argument %(argument_name)s: %(message)s'
733 """An error from trying to convert a command line string to a type."""
742 """Information about how to convert command line strings to Python objects.
744 Action objects are used by an ArgumentParser to represent the information
745 needed to parse a single argument from one or more strings from the
746 command line. The keyword arguments to the Action constructor are also
747 all attributes of Action instances.
751 - option_strings -- A list of command-line option strings which
752 should be associated with this action.
754 - dest -- The name of the attribute to hold the created object(s)
756 - nargs -- The number of command-line arguments that should be
757 consumed. By default, one argument will be consumed and a single
758 value will be produced. Other values include:
759 - N (an integer) consumes N arguments (and produces a list)
760 - '?' consumes zero or one arguments
761 - '*' consumes zero or more arguments (and produces a list)
762 - '+' consumes one or more arguments (and produces a list)
763 Note that the difference between the default and nargs=1 is that
764 with the default, a single value will be produced, while with
765 nargs=1, a list containing a single value will be produced.
767 - const -- The value to be produced if the option is specified and the
768 option uses an action that takes no values.
770 - default -- The value to be produced if the option is not specified.
772 - type -- The type which the command-line arguments should be converted
773 to, should be one of 'string', 'int', 'float', 'complex' or a
774 callable object that accepts a single string argument. If None,
777 - choices -- A container of values that should be allowed. If not None,
778 after a command-line argument has been converted to the appropriate
779 type, an exception will be raised if it is not a member of this
782 - required -- True if the action must always be specified at the
783 command line. This is only meaningful for optional command-line
786 - help -- The help string describing the argument.
788 - metavar -- The name to be used for the option's argument with the
789 help string. If None, the 'dest' value will be used as the name.
826 return [(name, getattr(self, name))
for name
in names]
828 def __call__(self, parser, namespace, values, option_string=None):
829 raise NotImplementedError(_(
'.__call__() not defined'))
846 raise ValueError(
'nargs for store actions must be > 0; if you '
847 'have nothing to store, actions such as store '
848 'true or store const may be more appropriate')
849 if const
is not None and nargs != OPTIONAL:
850 raise ValueError(
'nargs must be %r to supply const' % OPTIONAL)
852 option_strings=option_strings,
863 def __call__(self, parser, namespace, values, option_string=None):
864 setattr(namespace, self.
dest, values)
877 super(_StoreConstAction, self).
__init__(
878 option_strings=option_strings,
886 def __call__(self, parser, namespace, values, option_string=None):
887 setattr(namespace, self.
dest, self.
const)
898 super(_StoreTrueAction, self).
__init__(
899 option_strings=option_strings,
915 super(_StoreFalseAction, self).
__init__(
916 option_strings=option_strings,
938 raise ValueError(
'nargs for append actions must be > 0; if arg '
939 'strings are not supplying the value to append, '
940 'the append const action may be more appropriate')
941 if const
is not None and nargs != OPTIONAL:
942 raise ValueError(
'nargs must be %r to supply const' % OPTIONAL)
943 super(_AppendAction, self).
__init__(
944 option_strings=option_strings,
955 def __call__(self, parser, namespace, values, option_string=None):
958 setattr(namespace, self.
dest, items)
971 super(_AppendConstAction, self).
__init__(
972 option_strings=option_strings,
981 def __call__(self, parser, namespace, values, option_string=None):
983 items.append(self.
const)
984 setattr(namespace, self.
dest, items)
996 option_strings=option_strings,
1003 def __call__(self, parser, namespace, values, option_string=None):
1005 setattr(namespace, self.
dest, new_count)
1016 option_strings=option_strings,
1022 def __call__(self, parser, namespace, values, option_string=None):
1035 super(_VersionAction, self).
__init__(
1036 option_strings=option_strings,
1043 def __call__(self, parser, namespace, values, option_string=None):
1046 version = parser.version
1047 formatter = parser._get_formatter()
1048 formatter.add_text(version)
1049 parser.exit(message=formatter.format_help())
1058 sup.__init__(option_strings=[], dest=name, help=help)
1073 super(_SubParsersAction, self).
__init__(
1074 option_strings=option_strings,
1083 if kwargs.get(
'prog')
is None:
1087 if 'help' in kwargs:
1088 help = kwargs.pop(
'help')
1090 self._choices_actions.append(choice_action)
1100 def __call__(self, parser, namespace, values, option_string=None):
1101 parser_name = values[0]
1102 arg_strings = values[1:]
1105 if self.
dest is not SUPPRESS:
1106 setattr(namespace, self.
dest, parser_name)
1113 msg = _(
'unknown parser %r (choices: %s)' % tup)
1117 parser.parse_args(arg_strings, namespace)
1125 """Factory for creating file object types
1127 Instances of FileType are typically passed as type= arguments to the
1128 ArgumentParser add_argument() method.
1131 - mode -- A string indicating how the file is to be opened. Accepts the
1132 same values as the builtin open() function.
1133 - bufsize -- The file's desired buffer size. Accepts the same values as
1134 the builtin open() function.
1144 if 'r' in self._mode:
1146 elif 'w' in self.
_mode:
1149 msg = _(
'argument "-" with mode %r' % self.
_mode)
1150 raise ValueError(msg)
1156 return open(string, self.
_mode)
1160 args_str =
', '.
join([repr(arg)
for arg
in args
if arg
is not None])
1161 return '%s(%s)' % (type(self).__name__, args_str)
1168 """Simple object for storing attributes.
1170 Implements equality by attribute names and values, and provides a simple
1171 string representation.
1176 setattr(self, name, kwargs[name])
1179 return vars(self) == vars(other)
1182 return not (self == other)
1185 return key
in self.__dict__
1195 super(_ActionsContainer, self).
__init__()
1206 self.
register(
'action',
None, _StoreAction)
1207 self.
register(
'action',
'store', _StoreAction)
1208 self.
register(
'action',
'store_const', _StoreConstAction)
1209 self.
register(
'action',
'store_true', _StoreTrueAction)
1210 self.
register(
'action',
'store_false', _StoreFalseAction)
1211 self.
register(
'action',
'append', _AppendAction)
1212 self.
register(
'action',
'append_const', _AppendConstAction)
1213 self.
register(
'action',
'count', _CountAction)
1214 self.
register(
'action',
'help', _HelpAction)
1215 self.
register(
'action',
'version', _VersionAction)
1216 self.
register(
'action',
'parsers', _SubParsersAction)
1243 registry = self._registries.setdefault(registry_name, {})
1244 registry[value] = object
1253 self._defaults.update(kwargs)
1258 if action.dest
in kwargs:
1259 action.default = kwargs[action.dest]
1263 if action.dest == dest
and action.default
is not None:
1264 return action.default
1265 return self._defaults.get(dest,
None)
1273 add_argument(dest, ..., name=value, ...)
1274 add_argument(option_string, option_string, ..., name=value, ...)
1281 if not args
or len(args) == 1
and args[0][0]
not in chars:
1282 if args
and 'dest' in kwargs:
1283 raise ValueError(
'dest supplied twice for positional argument')
1291 if 'default' not in kwargs:
1292 dest = kwargs[
'dest']
1294 kwargs[
'default'] = self.
_defaults[dest]
1301 raise ValueError(
'unknown action "%s"' % action_class)
1302 action = action_class(**kwargs)
1305 type_func = self.
_registry_get(
'type', action.type, action.type)
1307 raise ValueError(
'%r is not callable' % type_func)
1313 self._action_groups.append(group)
1318 self._mutually_exclusive_groups.append(group)
1326 self._actions.append(action)
1327 action.container = self
1330 for option_string
in action.option_strings:
1334 for option_string
in action.option_strings:
1335 if self._negative_number_matcher.match(option_string):
1337 self._has_negative_number_optionals.append(
True)
1343 self._actions.remove(action)
1347 title_group_map = {}
1349 if group.title
in title_group_map:
1350 msg = _(
'cannot merge actions - two groups are named %r')
1351 raise ValueError(msg % (group.title))
1352 title_group_map[group.title] = group
1356 for group
in container._action_groups:
1360 if group.title
not in title_group_map:
1363 description=group.description,
1364 conflict_handler=group.conflict_handler)
1367 for action
in group._group_actions:
1368 group_map[action] = title_group_map[group.title]
1373 for group
in container._mutually_exclusive_groups:
1375 required=group.required)
1378 for action
in group._group_actions:
1379 group_map[action] = mutex_group
1382 for action
in container._actions:
1387 if 'required' in kwargs:
1388 msg = _(
"'required' is an invalid argument for positionals")
1389 raise TypeError(msg)
1393 if kwargs.get(
'nargs')
not in [OPTIONAL, ZERO_OR_MORE]:
1394 kwargs[
'required'] =
True
1395 if kwargs.get(
'nargs') == ZERO_OR_MORE
and 'default' not in kwargs:
1396 kwargs[
'required'] =
True
1399 return dict(kwargs, dest=dest, option_strings=[])
1404 long_option_strings = []
1405 for option_string
in args:
1408 msg = _(
'invalid option string %r: '
1409 'must start with a character %r')
1411 raise ValueError(msg % tup)
1414 option_strings.append(option_string)
1416 if len(option_string) > 1:
1418 long_option_strings.append(option_string)
1421 dest = kwargs.pop(
'dest',
None)
1423 if long_option_strings:
1424 dest_option_string = long_option_strings[0]
1426 dest_option_string = option_strings[0]
1429 msg = _(
'dest= is required for options like %r')
1430 raise ValueError(msg % option_string)
1431 dest = dest.replace(
'-',
'_')
1434 return dict(kwargs, dest=dest, option_strings=option_strings)
1437 action = kwargs.pop(
'action', default)
1444 return getattr(self, handler_func_name)
1445 except AttributeError:
1446 msg = _(
'invalid conflict_resolution value: %r')
1452 confl_optionals = []
1453 for option_string
in action.option_strings:
1456 confl_optionals.append((option_string, confl_optional))
1464 message = _(
'conflicting option string(s): %s')
1465 conflict_string =
', '.
join([option_string
1466 for option_string, action
1467 in conflicting_actions])
1473 for option_string, action
in conflicting_actions:
1476 action.option_strings.remove(option_string)
1477 self._option_string_actions.pop(option_string,
None)
1481 if not action.option_strings:
1482 action.container._remove_action(action)
1487 def __init__(self, container, title=None, description=None, **kwargs):
1489 update = kwargs.setdefault
1490 update(
'conflict_handler', container.conflict_handler)
1491 update(
'prefix_chars', container.prefix_chars)
1492 update(
'argument_default', container.argument_default)
1493 super_init = super(_ArgumentGroup, self).__init__
1494 super_init(description=description, **kwargs)
1506 container._has_negative_number_optionals
1509 action = super(_ArgumentGroup, self).
_add_action(action)
1510 self._group_actions.append(action)
1515 self._group_actions.remove(action)
1521 super(_MutuallyExclusiveGroup, self).
__init__(container)
1527 msg = _(
'mutually exclusive arguments must be optional')
1528 raise ValueError(msg)
1529 action = self._container._add_action(action)
1530 self._group_actions.append(action)
1534 self._container._remove_action(action)
1535 self._group_actions.remove(action)
1539 """Object for parsing command line strings into Python objects.
1542 - prog -- The name of the program (default: sys.argv[0])
1543 - usage -- A usage message (default: auto-generated from arguments)
1544 - description -- A description of what the program does
1545 - epilog -- Text following the argument descriptions
1546 - parents -- Parsers whose arguments should be copied into this one
1547 - formatter_class -- HelpFormatter class for printing help messages
1548 - prefix_chars -- Characters that prefix optional arguments
1549 - fromfile_prefix_chars -- Characters that prefix files containing
1550 additional arguments
1551 - argument_default -- The default value for all arguments
1552 - conflict_handler -- String indicating how to handle conflicts
1553 - add_help -- Add a -h/-help option
1563 formatter_class=HelpFormatter,
1565 fromfile_prefix_chars=
None,
1566 argument_default=
None,
1567 conflict_handler=
'error',
1570 if version
is not None:
1573 """The "version" argument to ArgumentParser is deprecated. """
1575 """"add_argument(..., action='version', version="N", ...)" """
1576 """instead""", DeprecationWarning)
1578 superinit = super(ArgumentParser, self).__init__
1579 superinit(description=description,
1580 prefix_chars=prefix_chars,
1581 argument_default=argument_default,
1582 conflict_handler=conflict_handler)
1586 prog = _os.path.basename(_sys.argv[0])
1602 def identity(string):
1604 self.
register(
'type',
None, identity)
1610 '-h',
'--help', action=
'help', default=SUPPRESS,
1611 help=_(
'show this help message and exit'))
1614 '-v',
'--version', action=
'version', default=SUPPRESS,
1616 help=_(
"show program's version number and exit"))
1619 for parent
in parents:
1622 defaults = parent._defaults
1623 except AttributeError:
1626 self._defaults.update(defaults)
1641 return [(name, getattr(self, name))
for name
in names]
1648 self.
error(_(
'cannot have multiple subparser arguments'))
1651 kwargs.setdefault(
'parser_class', type(self))
1653 if 'title' in kwargs
or 'description' in kwargs:
1654 title = _(kwargs.pop(
'title',
'subcommands'))
1655 description = _(kwargs.pop(
'description',
None))
1662 if kwargs.get(
'prog')
is None:
1666 formatter.add_usage(self.
usage, positionals, groups,
'')
1667 kwargs[
'prog'] = formatter.format_help().strip()
1671 action = parsers_class(option_strings=[], **kwargs)
1672 self._subparsers._add_action(action)
1678 if action.option_strings:
1679 self._optionals._add_action(action)
1681 self._positionals._add_action(action)
1687 if action.option_strings]
1692 if not action.option_strings]
1700 msg = _(
'unrecognized arguments: %s')
1707 args = _sys.argv[1:]
1710 if namespace
is None:
1715 if action.dest
is not SUPPRESS:
1716 if not hasattr(namespace, action.dest):
1717 if action.default
is not SUPPRESS:
1718 default = action.default
1719 if isinstance(action.default, _basestring):
1721 setattr(namespace, action.dest, default)
1725 if not hasattr(namespace, dest):
1726 setattr(namespace, dest, self.
_defaults[dest])
1731 except ArgumentError:
1732 err = _sys.exc_info()[1]
1733 self.
error(str(err))
1742 action_conflicts = {}
1744 group_actions = mutex_group._group_actions
1745 for i, mutex_action
in enumerate(mutex_group._group_actions):
1746 conflicts = action_conflicts.setdefault(mutex_action, [])
1747 conflicts.extend(group_actions[:i])
1748 conflicts.extend(group_actions[i + 1:])
1753 option_string_indices = {}
1754 arg_string_pattern_parts = []
1755 arg_strings_iter = iter(arg_strings)
1756 for i, arg_string
in enumerate(arg_strings_iter):
1759 if arg_string ==
'--':
1760 arg_string_pattern_parts.append(
'-')
1761 for arg_string
in arg_strings_iter:
1762 arg_string_pattern_parts.append(
'A')
1768 if option_tuple
is None:
1771 option_string_indices[i] = option_tuple
1773 arg_string_pattern_parts.append(pattern)
1776 arg_strings_pattern =
''.
join(arg_string_pattern_parts)
1779 seen_actions =
_set()
1780 seen_non_default_actions =
_set()
1782 def take_action(action, argument_strings, option_string=None):
1783 seen_actions.add(action)
1784 argument_values = self.
_get_values(action, argument_strings)
1789 if argument_values
is not action.default:
1790 seen_non_default_actions.add(action)
1791 for conflict_action
in action_conflicts.get(action, []):
1792 if conflict_action
in seen_non_default_actions:
1793 msg = _(
'not allowed with argument %s')
1799 if argument_values
is not SUPPRESS:
1800 action(self, namespace, argument_values, option_string)
1803 def consume_optional(start_index):
1806 option_tuple = option_string_indices[start_index]
1807 action, option_string, explicit_arg = option_tuple
1817 extras.append(arg_strings[start_index])
1818 return start_index + 1
1822 if explicit_arg
is not None:
1823 arg_count = match_argument(action,
'A')
1829 if arg_count == 0
and option_string[1]
not in chars:
1830 action_tuples.append((action, [], option_string))
1832 option_string = char + explicit_arg[0]
1833 explicit_arg = explicit_arg[1:]
or None
1835 if option_string
in optionals_map:
1836 action = optionals_map[option_string]
1839 msg = _(
'ignored explicit argument %r')
1844 elif arg_count == 1:
1845 stop = start_index + 1
1846 args = [explicit_arg]
1847 action_tuples.append((action, args, option_string))
1853 msg = _(
'ignored explicit argument %r')
1860 start = start_index + 1
1861 selected_patterns = arg_strings_pattern[start:]
1862 arg_count = match_argument(action, selected_patterns)
1863 stop = start + arg_count
1864 args = arg_strings[start:stop]
1865 action_tuples.append((action, args, option_string))
1870 assert action_tuples
1871 for action, args, option_string
in action_tuples:
1872 take_action(action, args, option_string)
1880 def consume_positionals(start_index):
1883 selected_pattern = arg_strings_pattern[start_index:]
1884 arg_counts = match_partial(positionals, selected_pattern)
1888 for action, arg_count
in zip(positionals, arg_counts):
1889 args = arg_strings[start_index: start_index + arg_count]
1890 start_index += arg_count
1891 take_action(action, args)
1895 positionals[:] = positionals[len(arg_counts):]
1902 if option_string_indices:
1903 max_option_string_index =
max(option_string_indices)
1905 max_option_string_index = -1
1906 while start_index <= max_option_string_index:
1909 next_option_string_index =
min([
1911 for index
in option_string_indices
1912 if index >= start_index])
1913 if start_index != next_option_string_index:
1914 positionals_end_index = consume_positionals(start_index)
1918 if positionals_end_index > start_index:
1919 start_index = positionals_end_index
1922 start_index = positionals_end_index
1926 if start_index
not in option_string_indices:
1927 strings = arg_strings[start_index:next_option_string_index]
1928 extras.extend(strings)
1929 start_index = next_option_string_index
1932 start_index = consume_optional(start_index)
1935 stop_index = consume_positionals(start_index)
1938 extras.extend(arg_strings[stop_index:])
1943 self.
error(_(
'too few arguments'))
1948 if action
not in seen_actions:
1950 self.
error(_(
'argument %s is required') % name)
1955 for action
in group._group_actions:
1956 if action
in seen_non_default_actions:
1962 for action
in group._group_actions
1963 if action.help
is not SUPPRESS]
1964 msg = _(
'one of the arguments %s is required')
1968 return namespace, extras
1972 new_arg_strings = []
1973 for arg_string
in arg_strings:
1977 new_arg_strings.append(arg_string)
1982 args_file = open(arg_string[1:])
1985 for arg_line
in args_file.read().splitlines():
1987 arg_strings.append(arg)
1989 new_arg_strings.extend(arg_strings)
1993 err = _sys.exc_info()[1]
1994 self.
error(str(err))
1997 return new_arg_strings
2005 match = _re.match(nargs_pattern, arg_strings_pattern)
2010 None: _(
'expected one argument'),
2011 OPTIONAL: _(
'expected at most one argument'),
2012 ONE_OR_MORE: _(
'expected at least one argument'),
2014 default = _(
'expected %s argument(s)') % action.nargs
2015 msg = nargs_errors.get(action.nargs, default)
2019 return len(match.group(1))
2025 for i
in range(len(actions), 0, -1):
2026 actions_slice = actions[:i]
2028 for action
in actions_slice])
2029 match = _re.match(pattern, arg_strings_pattern)
2030 if match
is not None:
2031 result.extend([len(string)
for string
in match.groups()])
2049 return action, arg_string,
None
2052 if len(arg_string) == 1:
2056 if '=' in arg_string:
2057 option_string, explicit_arg = arg_string.split(
'=', 1)
2060 return action, option_string, explicit_arg
2067 if len(option_tuples) > 1:
2068 options =
', '.
join([option_string
2069 for action, option_string, explicit_arg
in option_tuples])
2070 tup = arg_string, options
2071 self.
error(_(
'ambiguous option: %s could match %s') % tup)
2075 elif len(option_tuples) == 1:
2076 option_tuple, = option_tuples
2082 if self._negative_number_matcher.match(arg_string):
2087 if ' ' in arg_string:
2092 return None, arg_string,
None
2100 if option_string[0]
in chars
and option_string[1]
in chars:
2101 if '=' in option_string:
2102 option_prefix, explicit_arg = option_string.split(
'=', 1)
2104 option_prefix = option_string
2107 if option_string.startswith(option_prefix):
2109 tup = action, option_string, explicit_arg
2115 elif option_string[0]
in chars
and option_string[1]
not in chars:
2116 option_prefix = option_string
2118 short_option_prefix = option_string[:2]
2119 short_explicit_arg = option_string[2:]
2122 if option_string == short_option_prefix:
2124 tup = action, option_string, short_explicit_arg
2126 elif option_string.startswith(option_prefix):
2128 tup = action, option_string, explicit_arg
2133 self.
error(_(
'unexpected option string: %s') % option_string)
2141 nargs = action.nargs
2145 nargs_pattern =
'(-*A-*)'
2148 elif nargs == OPTIONAL:
2149 nargs_pattern =
'(-*A?-*)'
2152 elif nargs == ZERO_OR_MORE:
2153 nargs_pattern =
'(-*[A-]*)'
2156 elif nargs == ONE_OR_MORE:
2157 nargs_pattern =
'(-*A[A-]*)'
2160 elif nargs == REMAINDER:
2161 nargs_pattern =
'([-AO]*)'
2164 elif nargs == PARSER:
2165 nargs_pattern =
'(-*A[-AO]*)'
2169 nargs_pattern =
'(-*%s-*)' %
'-*'.
join(
'A' * nargs)
2172 if action.option_strings:
2173 nargs_pattern = nargs_pattern.replace(
'-*',
'')
2174 nargs_pattern = nargs_pattern.replace(
'-',
'')
2177 return nargs_pattern
2184 if action.nargs
not in [PARSER, REMAINDER]:
2185 arg_strings = [s
for s
in arg_strings
if s !=
'--']
2188 if not arg_strings
and action.nargs == OPTIONAL:
2189 if action.option_strings:
2190 value = action.const
2192 value = action.default
2193 if isinstance(value, _basestring):
2199 elif (
not arg_strings
and action.nargs == ZERO_OR_MORE
and
2200 not action.option_strings):
2201 if action.default
is not None:
2202 value = action.default
2208 elif len(arg_strings) == 1
and action.nargs
in [
None, OPTIONAL]:
2209 arg_string, = arg_strings
2214 elif action.nargs == REMAINDER:
2215 value = [self.
_get_value(action, v)
for v
in arg_strings]
2218 elif action.nargs == PARSER:
2219 value = [self.
_get_value(action, v)
for v
in arg_strings]
2224 value = [self.
_get_value(action, v)
for v
in arg_strings]
2232 type_func = self.
_registry_get(
'type', action.type, action.type)
2234 msg = _(
'%r is not callable')
2239 result = type_func(arg_string)
2242 except ArgumentTypeError:
2243 name = getattr(action.type,
'__name__', repr(action.type))
2244 msg = str(_sys.exc_info()[1])
2248 except (TypeError, ValueError):
2249 name = getattr(action.type,
'__name__', repr(action.type))
2250 msg = _(
'invalid %s value: %r')
2258 if action.choices
is not None and value
not in action.choices:
2259 tup = value,
', '.
join(
map(repr, action.choices))
2260 msg = _(
'invalid choice: %r (choose from %s)') % tup
2270 return formatter.format_help()
2284 formatter.start_section(action_group.title)
2285 formatter.add_text(action_group.description)
2286 formatter.add_arguments(action_group._group_actions)
2287 formatter.end_section()
2290 formatter.add_text(self.
epilog)
2293 return formatter.format_help()
2298 'The format_version method is deprecated -- the "version" '
2299 'argument to ArgumentParser is no longer supported.',
2302 formatter.add_text(self.
version)
2303 return formatter.format_help()
2324 'The print_version method is deprecated -- the "version" '
2325 'argument to ArgumentParser is no longer supported.',
2338 def exit(self, status=0, message=None):
2344 """error(message: string)
2346 Prints a usage message incorporating the message to stderr and
2349 If you override this in a subclass, it should not return -- it
2350 should either exit or raise an exception.
2353 self.
exit(2, _(
'%s: error: %s\n') % (self.
prog, message))
_mutually_exclusive_groups
def _handle_conflict_resolve
def _get_positional_actions
def _get_positional_kwargs
string format
Some error handling for the usage.
_has_negative_number_optionals
def _add_container_actions
def _read_args_from_files
def _match_arguments_partial
def _handle_conflict_error
static std::string join(char **cmd)
def convert_arg_line_to_args
T get(const Candidate &c)
def _get_optional_actions
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger list("!*","!HLTx*"if it matches 2 triggers or more) will accept the event if all the matching triggers are FAIL.It will reject the event if any of the triggers are PASS or EXCEPTION(this matches the behavior of"!*"before the partial wildcard feature was incorporated).Triggers which are in the READY state are completely ignored.(READY should never be returned since the trigger paths have been run
def add_mutually_exclusive_group