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)
122 if _sys.version_info[:2] == (2, 6):
124 warnings.filterwarnings(
126 message=
'BaseException.message has been deprecated as of Python 2.6',
127 category=DeprecationWarning,
131 SUPPRESS =
'==SUPPRESS=='
136 PARSER =
'==PARSER=='
143 """Abstract base class that provides __repr__.
145 The __repr__ method returns a string in the format::
146 ClassName(attr=name, attr=name, ...)
147 The attributes are determined either by a class-level attribute,
148 '_kwarg_names', or by inspecting the instance __dict__.
152 type_name = type(self).__name__
155 arg_strings.append(repr(arg))
157 arg_strings.append(
'%s=%r' % (name, value))
158 return '%s(%s)' % (type_name,
', '.
join(arg_strings))
161 return _sorted(self.__dict__.items())
168 if getattr(namespace, name,
None)
is None:
169 setattr(namespace, name, value)
170 return getattr(namespace, name)
178 """Formatter for generating usage messages and argument help strings.
180 Only the name of this class is considered a public API. All the methods
181 provided by the class are considered an implementation detail.
187 max_help_position=24,
193 width = int(_os.environ[
'COLUMNS'])
194 except (KeyError, ValueError):
227 def __init__(self, formatter, parent, heading=None):
235 if self.
parent is not None:
236 self.formatter._indent()
237 join = self.formatter._join_parts
238 for func, args
in self.
items:
240 item_help =
join([func(*args)
for func, args
in self.
items])
241 if self.
parent is not None:
242 self.formatter._dedent()
250 current_indent = self.formatter._current_indent
251 heading =
'%*s%s:\n' % (current_indent,
'', self.
heading)
256 return join([
'\n', heading, item_help,
'\n'])
259 self._current_section.items.append((func, args))
275 if text
is not SUPPRESS
and text
is not None:
278 def add_usage(self, usage, actions, groups, prefix=None):
279 if usage
is not SUPPRESS:
280 args = usage, actions, groups, prefix
284 if action.help
is not SUPPRESS:
288 invocations = [get_invocation(action)]
290 invocations.append(get_invocation(subaction))
293 invocation_length =
max([len(s)
for s
in invocations])
302 for action
in actions:
309 help = self._root_section.format_help()
311 help = self._long_break_matcher.sub(
'\n\n', help)
312 help = help.strip(
'\n') +
'\n'
317 for part
in part_strings
318 if part
and part
is not SUPPRESS])
322 prefix = _(
'usage: ')
325 if usage
is not None:
329 elif usage
is None and not actions:
330 usage =
'%(prog)s' %
dict(prog=self.
_prog)
334 prog =
'%(prog)s' %
dict(prog=self.
_prog)
339 for action
in actions:
340 if action.option_strings:
341 optionals.append(action)
343 positionals.append(action)
347 action_usage =
format(optionals + positionals, groups)
348 usage =
' '.
join([s
for s
in [prog, action_usage]
if s])
352 if len(prefix) + len(usage) > text_width:
355 part_regexp =
r'\(.*?\)+|\[.*?\]+|\S+'
356 opt_usage =
format(optionals, groups)
357 pos_usage =
format(positionals, groups)
358 opt_parts = _re.findall(part_regexp, opt_usage)
359 pos_parts = _re.findall(part_regexp, pos_usage)
360 assert ' '.
join(opt_parts) == opt_usage
361 assert ' '.
join(pos_parts) == pos_usage
364 def get_lines(parts, indent, prefix=None):
367 if prefix
is not None:
368 line_len = len(prefix) - 1
370 line_len = len(indent) - 1
372 if line_len + 1 + len(part) > text_width:
373 lines.append(indent +
' '.
join(line))
375 line_len = len(indent) - 1
377 line_len += len(part) + 1
379 lines.append(indent +
' '.
join(line))
380 if prefix
is not None:
381 lines[0] = lines[0][len(indent):]
385 if len(prefix) + len(prog) <= 0.75 * text_width:
386 indent =
' ' * (len(prefix) + len(prog) + 1)
388 lines = get_lines([prog] + opt_parts, indent, prefix)
389 lines.extend(get_lines(pos_parts, indent))
391 lines = get_lines([prog] + pos_parts, indent, prefix)
397 indent =
' ' * len(prefix)
398 parts = opt_parts + pos_parts
399 lines = get_lines(parts, indent)
402 lines.extend(get_lines(opt_parts, indent))
403 lines.extend(get_lines(pos_parts, indent))
404 lines = [prog] + lines
407 usage =
'\n'.
join(lines)
410 return '%s%s\n\n' % (prefix, usage)
414 group_actions =
_set()
418 start = actions.index(group._group_actions[0])
422 end = start + len(group._group_actions)
423 if actions[start:end] == group._group_actions:
424 for action
in group._group_actions:
425 group_actions.add(action)
426 if not group.required:
432 for i
in range(start + 1, end):
437 for i, action
in enumerate(actions):
441 if action.help
is SUPPRESS:
443 if inserts.get(i) ==
'|':
445 elif inserts.get(i + 1) ==
'|':
449 elif not action.option_strings:
453 if action
in group_actions:
454 if part[0] ==
'[' and part[-1] ==
']':
462 option_string = action.option_strings[0]
466 if action.nargs == 0:
467 part =
'%s' % option_string
472 default = action.dest.upper()
474 part =
'%s %s' % (option_string, args_string)
477 if not action.required
and action
not in group_actions:
484 for i
in _sorted(inserts, reverse=
True):
485 parts[i:i] = [inserts[i]]
488 text =
' '.
join([item
for item
in parts
if item
is not None])
493 text = _re.sub(
r'(%s) ' % open,
r'\1', text)
494 text = _re.sub(
r' (%s)' % close,
r'\1', text)
495 text = _re.sub(
r'%s *%s' % (open, close),
r'', text)
496 text = _re.sub(
r'\(([^|]*)\)',
r'\1', text)
505 return self.
_fill_text(text, text_width, indent) +
'\n\n'
511 help_width = self.
_width - help_position
518 action_header =
'%*s%s\n' % tup
521 elif len(action_header) <= action_width:
523 action_header =
'%*s%-*s ' % tup
529 action_header =
'%*s%s\n' % tup
530 indent_first = help_position
533 parts = [action_header]
539 parts.append(
'%*s%s\n' % (indent_first,
'', help_lines[0]))
540 for line
in help_lines[1:]:
541 parts.append(
'%*s%s\n' % (help_position,
'', line))
544 elif not action_header.endswith(
'\n'):
555 if not action.option_strings:
564 if action.nargs == 0:
565 parts.extend(action.option_strings)
570 default = action.dest.upper()
572 for option_string
in action.option_strings:
573 parts.append(
'%s %s' % (option_string, args_string))
575 return ', '.
join(parts)
578 if action.metavar
is not None:
579 result = action.metavar
580 elif action.choices
is not None:
581 choice_strs = [str(choice)
for choice
in action.choices]
582 result =
'{%s}' %
','.
join(choice_strs)
584 result = default_metavar
587 if isinstance(result, tuple):
590 return (result, ) * tuple_size
595 if action.nargs
is None:
596 result =
'%s' % get_metavar(1)
597 elif action.nargs == OPTIONAL:
598 result =
'[%s]' % get_metavar(1)
599 elif action.nargs == ZERO_OR_MORE:
600 result =
'[%s [%s ...]]' % get_metavar(2)
601 elif action.nargs == ONE_OR_MORE:
602 result =
'%s [%s ...]' % get_metavar(2)
603 elif action.nargs
is PARSER:
604 result =
'%s ...' % get_metavar(1)
606 formats = [
'%s' for _
in range(action.nargs)]
607 result =
' '.
join(formats) % get_metavar(action.nargs)
611 params =
dict(vars(action), prog=self.
_prog)
612 for name
in list(params):
613 if params[name]
is SUPPRESS:
615 if params.get(
'choices')
is not None:
616 choices_str =
', '.
join([str(c)
for c
in params[
'choices']])
617 params[
'choices'] = choices_str
622 get_subactions = action._get_subactions
623 except AttributeError:
627 for subaction
in get_subactions():
632 text = self._whitespace_matcher.sub(
' ', text).strip()
633 return _textwrap.wrap(text, width)
636 text = self._whitespace_matcher.sub(
' ', text).strip()
637 return _textwrap.fill(text, width, initial_indent=indent,
638 subsequent_indent=indent)
645 """Help message formatter which retains any formatting in descriptions.
647 Only the name of this class is considered a public API. All the methods
648 provided by the class are considered an implementation detail.
652 return ''.
join([indent + line
for line
in text.splitlines(
True)])
656 """Help message formatter which retains formatting of all help text.
658 Only the name of this class is considered a public API. All the methods
659 provided by the class are considered an implementation detail.
663 return text.splitlines()
667 """Help message formatter which adds default values to argument help.
669 Only the name of this class is considered a public API. All the methods
670 provided by the class are considered an implementation detail.
675 if '%(default)' not in action.help:
676 if action.default
is not SUPPRESS:
677 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
678 if action.option_strings
or action.nargs
in defaulting_nargs:
679 help +=
' (default: %(default)s)'
690 elif argument.option_strings:
691 return '/'.
join(argument.option_strings)
692 elif argument.metavar
not in (
None, SUPPRESS):
693 return argument.metavar
694 elif argument.dest
not in (
None, SUPPRESS):
701 """An error from creating or using an argument (optional or positional).
703 The string value of this exception is the message, augmented with
704 information about the argument that caused it.
713 format =
'%(message)s'
715 format =
'argument %(argument_name)s: %(message)s'
724 """Information about how to convert command line strings to Python objects.
726 Action objects are used by an ArgumentParser to represent the information
727 needed to parse a single argument from one or more strings from the
728 command line. The keyword arguments to the Action constructor are also
729 all attributes of Action instances.
733 - option_strings -- A list of command-line option strings which
734 should be associated with this action.
736 - dest -- The name of the attribute to hold the created object(s)
738 - nargs -- The number of command-line arguments that should be
739 consumed. By default, one argument will be consumed and a single
740 value will be produced. Other values include:
741 - N (an integer) consumes N arguments (and produces a list)
742 - '?' consumes zero or one arguments
743 - '*' consumes zero or more arguments (and produces a list)
744 - '+' consumes one or more arguments (and produces a list)
745 Note that the difference between the default and nargs=1 is that
746 with the default, a single value will be produced, while with
747 nargs=1, a list containing a single value will be produced.
749 - const -- The value to be produced if the option is specified and the
750 option uses an action that takes no values.
752 - default -- The value to be produced if the option is not specified.
754 - type -- The type which the command-line arguments should be converted
755 to, should be one of 'string', 'int', 'float', 'complex' or a
756 callable object that accepts a single string argument. If None,
759 - choices -- A container of values that should be allowed. If not None,
760 after a command-line argument has been converted to the appropriate
761 type, an exception will be raised if it is not a member of this
764 - required -- True if the action must always be specified at the
765 command line. This is only meaningful for optional command-line
768 - help -- The help string describing the argument.
770 - metavar -- The name to be used for the option's argument with the
771 help string. If None, the 'dest' value will be used as the name.
808 return [(name, getattr(self, name))
for name
in names]
810 def __call__(self, parser, namespace, values, option_string=None):
811 raise NotImplementedError(_(
'.__call__() not defined'))
828 raise ValueError(
'nargs for store actions must be > 0; if you '
829 'have nothing to store, actions such as store '
830 'true or store const may be more appropriate')
831 if const
is not None and nargs != OPTIONAL:
832 raise ValueError(
'nargs must be %r to supply const' % OPTIONAL)
834 option_strings=option_strings,
845 def __call__(self, parser, namespace, values, option_string=None):
846 setattr(namespace, self.
dest, values)
859 super(_StoreConstAction, self).
__init__(
860 option_strings=option_strings,
868 def __call__(self, parser, namespace, values, option_string=None):
869 setattr(namespace, self.
dest, self.
const)
880 super(_StoreTrueAction, self).
__init__(
881 option_strings=option_strings,
897 super(_StoreFalseAction, self).
__init__(
898 option_strings=option_strings,
920 raise ValueError(
'nargs for append actions must be > 0; if arg '
921 'strings are not supplying the value to append, '
922 'the append const action may be more appropriate')
923 if const
is not None and nargs != OPTIONAL:
924 raise ValueError(
'nargs must be %r to supply const' % OPTIONAL)
925 super(_AppendAction, self).
__init__(
926 option_strings=option_strings,
937 def __call__(self, parser, namespace, values, option_string=None):
940 setattr(namespace, self.
dest, items)
953 super(_AppendConstAction, self).
__init__(
954 option_strings=option_strings,
963 def __call__(self, parser, namespace, values, option_string=None):
965 items.append(self.
const)
966 setattr(namespace, self.
dest, items)
978 option_strings=option_strings,
985 def __call__(self, parser, namespace, values, option_string=None):
987 setattr(namespace, self.
dest, new_count)
998 option_strings=option_strings,
1004 def __call__(self, parser, namespace, values, option_string=None):
1016 super(_VersionAction, self).
__init__(
1017 option_strings=option_strings,
1023 def __call__(self, parser, namespace, values, option_string=None):
1024 parser.print_version()
1034 sup.__init__(option_strings=[], dest=name, help=help)
1049 super(_SubParsersAction, self).
__init__(
1050 option_strings=option_strings,
1059 if kwargs.get(
'prog')
is None:
1063 if 'help' in kwargs:
1064 help = kwargs.pop(
'help')
1066 self._choices_actions.append(choice_action)
1076 def __call__(self, parser, namespace, values, option_string=None):
1077 parser_name = values[0]
1078 arg_strings = values[1:]
1081 if self.
dest is not SUPPRESS:
1082 setattr(namespace, self.
dest, parser_name)
1089 msg = _(
'unknown parser %r (choices: %s)' % tup)
1093 parser.parse_args(arg_strings, namespace)
1101 """Factory for creating file object types
1103 Instances of FileType are typically passed as type= arguments to the
1104 ArgumentParser add_argument() method.
1107 - mode -- A string indicating how the file is to be opened. Accepts the
1108 same values as the builtin open() function.
1109 - bufsize -- The file's desired buffer size. Accepts the same values as
1110 the builtin open() function.
1120 if 'r' in self._mode:
1122 elif 'w' in self.
_mode:
1125 msg = _(
'argument "-" with mode %r' % self.
_mode)
1126 raise ValueError(msg)
1132 return open(string, self.
_mode)
1136 args_str =
', '.
join([repr(arg)
for arg
in args
if arg
is not None])
1137 return '%s(%s)' % (type(self).__name__, args_str)
1144 """Simple object for storing attributes.
1146 Implements equality by attribute names and values, and provides a simple
1147 string representation.
1152 setattr(self, name, kwargs[name])
1155 return vars(self) == vars(other)
1158 return not (self == other)
1168 super(_ActionsContainer, self).
__init__()
1179 self.
register(
'action',
None, _StoreAction)
1180 self.
register(
'action',
'store', _StoreAction)
1181 self.
register(
'action',
'store_const', _StoreConstAction)
1182 self.
register(
'action',
'store_true', _StoreTrueAction)
1183 self.
register(
'action',
'store_false', _StoreFalseAction)
1184 self.
register(
'action',
'append', _AppendAction)
1185 self.
register(
'action',
'append_const', _AppendConstAction)
1186 self.
register(
'action',
'count', _CountAction)
1187 self.
register(
'action',
'help', _HelpAction)
1188 self.
register(
'action',
'version', _VersionAction)
1189 self.
register(
'action',
'parsers', _SubParsersAction)
1216 registry = self._registries.setdefault(registry_name, {})
1217 registry[value] = object
1226 self._defaults.update(kwargs)
1231 if action.dest
in kwargs:
1232 action.default = kwargs[action.dest]
1239 add_argument(dest, ..., name=value, ...)
1240 add_argument(option_string, option_string, ..., name=value, ...)
1247 if not args
or len(args) == 1
and args[0][0]
not in chars:
1255 if 'default' not in kwargs:
1256 dest = kwargs[
'dest']
1258 kwargs[
'default'] = self.
_defaults[dest]
1264 action = action_class(**kwargs)
1269 self._action_groups.append(group)
1274 self._mutually_exclusive_groups.append(group)
1282 self._actions.append(action)
1283 action.container = self
1286 for option_string
in action.option_strings:
1290 for option_string
in action.option_strings:
1291 if self._negative_number_matcher.match(option_string):
1293 self._has_negative_number_optionals.append(
True)
1299 self._actions.remove(action)
1303 title_group_map = {}
1305 if group.title
in title_group_map:
1306 msg = _(
'cannot merge actions - two groups are named %r')
1307 raise ValueError(msg % (group.title))
1308 title_group_map[group.title] = group
1312 for group
in container._action_groups:
1316 if group.title
not in title_group_map:
1319 description=group.description,
1320 conflict_handler=group.conflict_handler)
1323 for action
in group._group_actions:
1324 group_map[action] = title_group_map[group.title]
1329 for group
in container._mutually_exclusive_groups:
1331 required=group.required)
1334 for action
in group._group_actions:
1335 group_map[action] = mutex_group
1338 for action
in container._actions:
1343 if 'required' in kwargs:
1344 msg = _(
"'required' is an invalid argument for positionals")
1345 raise TypeError(msg)
1349 if kwargs.get(
'nargs')
not in [OPTIONAL, ZERO_OR_MORE]:
1350 kwargs[
'required'] =
True
1351 if kwargs.get(
'nargs') == ZERO_OR_MORE
and 'default' not in kwargs:
1352 kwargs[
'required'] =
True
1355 return dict(kwargs, dest=dest, option_strings=[])
1360 long_option_strings = []
1361 for option_string
in args:
1363 if len(option_string) < 2:
1364 msg = _(
'invalid option string %r: '
1365 'must be at least two characters long')
1366 raise ValueError(msg % option_string)
1370 msg = _(
'invalid option string %r: '
1371 'must start with a character %r')
1373 raise ValueError(msg % tup)
1377 msg = _(
'invalid option string %r: '
1378 'must contain characters other than %r')
1380 raise ValueError(msg % tup)
1383 option_strings.append(option_string)
1386 long_option_strings.append(option_string)
1389 dest = kwargs.pop(
'dest',
None)
1391 if long_option_strings:
1392 dest_option_string = long_option_strings[0]
1394 dest_option_string = option_strings[0]
1396 dest = dest.replace(
'-',
'_')
1399 return dict(kwargs, dest=dest, option_strings=option_strings)
1402 action = kwargs.pop(
'action', default)
1409 return getattr(self, handler_func_name)
1410 except AttributeError:
1411 msg = _(
'invalid conflict_resolution value: %r')
1417 confl_optionals = []
1418 for option_string
in action.option_strings:
1421 confl_optionals.append((option_string, confl_optional))
1429 message = _(
'conflicting option string(s): %s')
1430 conflict_string =
', '.
join([option_string
1431 for option_string, action
1432 in conflicting_actions])
1438 for option_string, action
in conflicting_actions:
1441 action.option_strings.remove(option_string)
1442 self._option_string_actions.pop(option_string,
None)
1446 if not action.option_strings:
1447 action.container._remove_action(action)
1452 def __init__(self, container, title=None, description=None, **kwargs):
1454 update = kwargs.setdefault
1455 update(
'conflict_handler', container.conflict_handler)
1456 update(
'prefix_chars', container.prefix_chars)
1457 update(
'argument_default', container.argument_default)
1458 super_init = super(_ArgumentGroup, self).__init__
1459 super_init(description=description, **kwargs)
1471 container._has_negative_number_optionals
1474 action = super(_ArgumentGroup, self).
_add_action(action)
1475 self._group_actions.append(action)
1480 self._group_actions.remove(action)
1486 super(_MutuallyExclusiveGroup, self).
__init__(container)
1492 msg = _(
'mutually exclusive arguments must be optional')
1493 raise ValueError(msg)
1494 action = self._container._add_action(action)
1495 self._group_actions.append(action)
1499 self._container._remove_action(action)
1500 self._group_actions.remove(action)
1504 """Object for parsing command line strings into Python objects.
1507 - prog -- The name of the program (default: sys.argv[0])
1508 - usage -- A usage message (default: auto-generated from arguments)
1509 - description -- A description of what the program does
1510 - epilog -- Text following the argument descriptions
1511 - version -- Add a -v/--version option with the given version string
1512 - parents -- Parsers whose arguments should be copied into this one
1513 - formatter_class -- HelpFormatter class for printing help messages
1514 - prefix_chars -- Characters that prefix optional arguments
1515 - fromfile_prefix_chars -- Characters that prefix files containing
1516 additional arguments
1517 - argument_default -- The default value for all arguments
1518 - conflict_handler -- String indicating how to handle conflicts
1519 - add_help -- Add a -h/-help option
1529 formatter_class=HelpFormatter,
1531 fromfile_prefix_chars=
None,
1532 argument_default=
None,
1533 conflict_handler=
'error',
1536 superinit = super(ArgumentParser, self).__init__
1537 superinit(description=description,
1538 prefix_chars=prefix_chars,
1539 argument_default=argument_default,
1540 conflict_handler=conflict_handler)
1544 prog = _os.path.basename(_sys.argv[0])
1560 def identity(string):
1562 self.
register(
'type',
None, identity)
1568 '-h',
'--help', action=
'help', default=SUPPRESS,
1569 help=_(
'show this help message and exit'))
1572 '-v',
'--version', action=
'version', default=SUPPRESS,
1573 help=_(
"show program's version number and exit"))
1576 for parent
in parents:
1579 defaults = parent._defaults
1580 except AttributeError:
1583 self._defaults.update(defaults)
1598 return [(name, getattr(self, name))
for name
in names]
1605 self.
error(_(
'cannot have multiple subparser arguments'))
1608 kwargs.setdefault(
'parser_class', type(self))
1610 if 'title' in kwargs
or 'description' in kwargs:
1611 title = _(kwargs.pop(
'title',
'subcommands'))
1612 description = _(kwargs.pop(
'description',
None))
1619 if kwargs.get(
'prog')
is None:
1623 formatter.add_usage(self.
usage, positionals, groups,
'')
1624 kwargs[
'prog'] = formatter.format_help().strip()
1628 action = parsers_class(option_strings=[], **kwargs)
1629 self._subparsers._add_action(action)
1635 if action.option_strings:
1636 self._optionals._add_action(action)
1638 self._positionals._add_action(action)
1644 if action.option_strings]
1649 if not action.option_strings]
1657 msg = _(
'unrecognized arguments: %s')
1664 args = _sys.argv[1:]
1667 if namespace
is None:
1672 if action.dest
is not SUPPRESS:
1673 if not hasattr(namespace, action.dest):
1674 if action.default
is not SUPPRESS:
1675 default = action.default
1676 if isinstance(action.default, _basestring):
1678 setattr(namespace, action.dest, default)
1682 if not hasattr(namespace, dest):
1683 setattr(namespace, dest, self.
_defaults[dest])
1688 except ArgumentError:
1689 err = _sys.exc_info()[1]
1690 self.
error(str(err))
1699 action_conflicts = {}
1701 group_actions = mutex_group._group_actions
1702 for i, mutex_action
in enumerate(mutex_group._group_actions):
1703 conflicts = action_conflicts.setdefault(mutex_action, [])
1704 conflicts.extend(group_actions[:i])
1705 conflicts.extend(group_actions[i + 1:])
1710 option_string_indices = {}
1711 arg_string_pattern_parts = []
1712 arg_strings_iter = iter(arg_strings)
1713 for i, arg_string
in enumerate(arg_strings_iter):
1716 if arg_string ==
'--':
1717 arg_string_pattern_parts.append(
'-')
1718 for arg_string
in arg_strings_iter:
1719 arg_string_pattern_parts.append(
'A')
1725 if option_tuple
is None:
1728 option_string_indices[i] = option_tuple
1730 arg_string_pattern_parts.append(pattern)
1733 arg_strings_pattern =
''.
join(arg_string_pattern_parts)
1736 seen_actions =
_set()
1737 seen_non_default_actions =
_set()
1739 def take_action(action, argument_strings, option_string=None):
1740 seen_actions.add(action)
1741 argument_values = self.
_get_values(action, argument_strings)
1746 if argument_values
is not action.default:
1747 seen_non_default_actions.add(action)
1748 for conflict_action
in action_conflicts.get(action, []):
1749 if conflict_action
in seen_non_default_actions:
1750 msg = _(
'not allowed with argument %s')
1756 if argument_values
is not SUPPRESS:
1757 action(self, namespace, argument_values, option_string)
1760 def consume_optional(start_index):
1763 option_tuple = option_string_indices[start_index]
1764 action, option_string, explicit_arg = option_tuple
1774 extras.append(arg_strings[start_index])
1775 return start_index + 1
1779 if explicit_arg
is not None:
1780 arg_count = match_argument(action,
'A')
1786 if arg_count == 0
and option_string[1]
not in chars:
1787 action_tuples.append((action, [], option_string))
1789 option_string = char + explicit_arg[0]
1790 explicit_arg = explicit_arg[1:]
or None
1792 if option_string
in optionals_map:
1793 action = optionals_map[option_string]
1796 msg = _(
'ignored explicit argument %r')
1801 elif arg_count == 1:
1802 stop = start_index + 1
1803 args = [explicit_arg]
1804 action_tuples.append((action, args, option_string))
1810 msg = _(
'ignored explicit argument %r')
1817 start = start_index + 1
1818 selected_patterns = arg_strings_pattern[start:]
1819 arg_count = match_argument(action, selected_patterns)
1820 stop = start + arg_count
1821 args = arg_strings[start:stop]
1822 action_tuples.append((action, args, option_string))
1827 assert action_tuples
1828 for action, args, option_string
in action_tuples:
1829 take_action(action, args, option_string)
1837 def consume_positionals(start_index):
1840 selected_pattern = arg_strings_pattern[start_index:]
1841 arg_counts = match_partial(positionals, selected_pattern)
1845 for action, arg_count
in zip(positionals, arg_counts):
1846 args = arg_strings[start_index: start_index + arg_count]
1847 start_index += arg_count
1848 take_action(action, args)
1852 positionals[:] = positionals[len(arg_counts):]
1859 if option_string_indices:
1860 max_option_string_index =
max(option_string_indices)
1862 max_option_string_index = -1
1863 while start_index <= max_option_string_index:
1866 next_option_string_index =
min([
1868 for index
in option_string_indices
1869 if index >= start_index])
1870 if start_index != next_option_string_index:
1871 positionals_end_index = consume_positionals(start_index)
1875 if positionals_end_index > start_index:
1876 start_index = positionals_end_index
1879 start_index = positionals_end_index
1883 if start_index
not in option_string_indices:
1884 strings = arg_strings[start_index:next_option_string_index]
1885 extras.extend(strings)
1886 start_index = next_option_string_index
1889 start_index = consume_optional(start_index)
1892 stop_index = consume_positionals(start_index)
1895 extras.extend(arg_strings[stop_index:])
1900 self.
error(_(
'too few arguments'))
1905 if action
not in seen_actions:
1907 self.
error(_(
'argument %s is required') % name)
1912 for action
in group._group_actions:
1913 if action
in seen_non_default_actions:
1919 for action
in group._group_actions
1920 if action.help
is not SUPPRESS]
1921 msg = _(
'one of the arguments %s is required')
1925 return namespace, extras
1929 new_arg_strings = []
1930 for arg_string
in arg_strings:
1934 new_arg_strings.append(arg_string)
1939 args_file = open(arg_string[1:])
1941 arg_strings = args_file.read().splitlines()
1943 new_arg_strings.extend(arg_strings)
1947 err = _sys.exc_info()[1]
1948 self.
error(str(err))
1951 return new_arg_strings
1956 match = _re.match(nargs_pattern, arg_strings_pattern)
1961 None: _(
'expected one argument'),
1962 OPTIONAL: _(
'expected at most one argument'),
1963 ONE_OR_MORE: _(
'expected at least one argument'),
1965 default = _(
'expected %s argument(s)') % action.nargs
1966 msg = nargs_errors.get(action.nargs, default)
1970 return len(match.group(1))
1976 for i
in range(len(actions), 0, -1):
1977 actions_slice = actions[:i]
1979 for action
in actions_slice])
1980 match = _re.match(pattern, arg_strings_pattern)
1981 if match
is not None:
1982 result.extend([len(string)
for string
in match.groups()])
1998 if not arg_string.strip(
'-'):
2004 return action, arg_string,
None
2011 if len(option_tuples) > 1:
2012 options =
', '.
join([option_string
2013 for action, option_string, explicit_arg
in option_tuples])
2014 tup = arg_string, options
2015 self.
error(_(
'ambiguous option: %s could match %s') % tup)
2019 elif len(option_tuples) == 1:
2020 option_tuple, = option_tuples
2026 if self._negative_number_matcher.match(arg_string):
2031 if ' ' in arg_string:
2036 return None, arg_string,
None
2044 if option_string[0]
in chars
and option_string[1]
in chars:
2045 if '=' in option_string:
2046 option_prefix, explicit_arg = option_string.split(
'=', 1)
2048 option_prefix = option_string
2051 if option_string.startswith(option_prefix):
2053 tup = action, option_string, explicit_arg
2059 elif option_string[0]
in chars
and option_string[1]
not in chars:
2060 option_prefix = option_string
2062 short_option_prefix = option_string[:2]
2063 short_explicit_arg = option_string[2:]
2066 if option_string == short_option_prefix:
2068 tup = action, option_string, short_explicit_arg
2070 elif option_string.startswith(option_prefix):
2072 tup = action, option_string, explicit_arg
2077 self.
error(_(
'unexpected option string: %s') % option_string)
2085 nargs = action.nargs
2089 nargs_pattern =
'(-*A-*)'
2092 elif nargs == OPTIONAL:
2093 nargs_pattern =
'(-*A?-*)'
2096 elif nargs == ZERO_OR_MORE:
2097 nargs_pattern =
'(-*[A-]*)'
2100 elif nargs == ONE_OR_MORE:
2101 nargs_pattern =
'(-*A[A-]*)'
2104 elif nargs
is PARSER:
2105 nargs_pattern =
'(-*A[-AO]*)'
2109 nargs_pattern =
'(-*%s-*)' %
'-*'.
join(
'A' * nargs)
2112 if action.option_strings:
2113 nargs_pattern = nargs_pattern.replace(
'-*',
'')
2114 nargs_pattern = nargs_pattern.replace(
'-',
'')
2117 return nargs_pattern
2124 if action.nargs
is not PARSER:
2125 arg_strings = [s
for s
in arg_strings
if s !=
'--']
2128 if not arg_strings
and action.nargs == OPTIONAL:
2129 if action.option_strings:
2130 value = action.const
2132 value = action.default
2133 if isinstance(value, _basestring):
2139 elif (
not arg_strings
and action.nargs == ZERO_OR_MORE
and
2140 not action.option_strings):
2141 if action.default
is not None:
2142 value = action.default
2148 elif len(arg_strings) == 1
and action.nargs
in [
None, OPTIONAL]:
2149 arg_string, = arg_strings
2154 elif action.nargs
is PARSER:
2155 value = [self.
_get_value(action, v)
for v
in arg_strings]
2160 value = [self.
_get_value(action, v)
for v
in arg_strings]
2168 type_func = self.
_registry_get(
'type', action.type, action.type)
2169 if not hasattr(type_func,
'__call__'):
2170 if not hasattr(type_func,
'__bases__'):
2171 msg = _(
'%r is not callable')
2176 result = type_func(arg_string)
2179 except (TypeError, ValueError):
2180 name = getattr(action.type,
'__name__', repr(action.type))
2181 msg = _(
'invalid %s value: %r')
2189 if action.choices
is not None and value
not in action.choices:
2190 tup = value,
', '.
join(
map(repr, action.choices))
2191 msg = _(
'invalid choice: %r (choose from %s)') % tup
2201 return formatter.format_help()
2215 formatter.start_section(action_group.title)
2216 formatter.add_text(action_group.description)
2217 formatter.add_arguments(action_group._group_actions)
2218 formatter.end_section()
2221 formatter.add_text(self.
epilog)
2224 return formatter.format_help()
2228 formatter.add_text(self.
version)
2229 return formatter.format_help()
2255 def exit(self, status=0, message=None):
2257 _sys.stderr.write(message)
2261 """error(message: string)
2263 Prints a usage message incorporating the message to stderr and
2266 If you override this in a subclass, it should not return -- it
2267 should either exit or raise an exception.
2270 self.
exit(2, _(
'%s: error: %s\n') % (self.
prog, message))
def _handle_conflict_resolve
def add_mutually_exclusive_group
def _get_positional_actions
def _match_arguments_partial
string format
Some error handling for the usage.
_mutually_exclusive_groups
def _get_positional_kwargs
def _read_args_from_files
def _add_container_actions
def _get_optional_actions
static std::string join(char **cmd)
_has_negative_number_optionals
def _handle_conflict_error
T get(const Candidate &c)
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