4 """Command-line parsing library 6 This 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 12 The following is a simple usage example that sums integers from the 13 command-line and writes the result to a file:: 15 parser = argparse.ArgumentParser( 16 description='sum the integers at the command line') 18 'integers', metavar='int', nargs='+', type=int, 19 help='an integer to be summed') 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)) 27 The 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 59 All other classes in this module are considered implementation details. 60 (Also note that HelpFormatter and RawDescriptionHelpFormatter are only 61 considered public as object names -- the API of the formatter objects is 62 still considered an implementation detail.) 68 __external_lib__ =
True 77 'ArgumentDefaultsHelpFormatter',
78 'RawDescriptionHelpFormatter',
79 'RawTextHelpFormatter',
95 import textwrap
as _textwrap
97 from gettext
import gettext
as _
103 from sets
import Set
as set
115 result = list(iterable)
123 return hasattr(obj,
'__call__')
or hasattr(obj,
'__bases__')
126 SUPPRESS =
'==SUPPRESS==' 133 _UNRECOGNIZED_ARGS_ATTR =
'_unrecognized_args' 140 """Abstract base class that provides __repr__. 142 The __repr__ method returns a string in the format:: 143 ClassName(attr=name, attr=name, ...) 144 The attributes are determined either by a class-level attribute, 145 '_kwarg_names', or by inspecting the instance __dict__. 149 type_name = type(self).__name__
152 arg_strings.append(repr(arg))
154 arg_strings.append(
'%s=%r' % (name, value))
155 return '%s(%s)' % (type_name,
', '.
join(arg_strings))
157 def _get_kwargs(self):
158 return sorted(self.__dict__.items())
164 def _ensure_value(namespace, name, value):
165 if getattr(namespace, name,
None)
is None:
166 setattr(namespace, name, value)
167 return getattr(namespace, name)
175 """Formatter for generating usage messages and argument help strings. 177 Only the name of this class is considered a public API. All the methods 178 provided by the class are considered an implementation detail. 184 max_help_position=24,
190 width = int(_os.environ[
'COLUMNS'])
191 except (KeyError, ValueError):
224 def __init__(self, formatter, parent, heading=None):
232 if self.
parent is not None:
235 for func, args
in self.
items:
237 item_help =
join([func(*args)
for func, args
in self.
items])
238 if self.
parent is not None:
247 current_indent = self.
formatter._current_indent
248 heading =
'%*s%s:\n' % (current_indent,
'', self.
heading)
253 return join([
'\n', heading, item_help,
'\n'])
255 def _add_item(self, func, args):
256 self._current_section.items.append((func, args))
272 if text
is not SUPPRESS
and text
is not None:
275 def add_usage(self, usage, actions, groups, prefix=None):
276 if usage
is not SUPPRESS:
277 args = usage, actions, groups, prefix
281 if action.help
is not SUPPRESS:
285 invocations = [get_invocation(action)]
287 invocations.append(get_invocation(subaction))
290 invocation_length = max([len(s)
for s
in invocations])
299 for action
in actions:
309 help = help.strip(
'\n') +
'\n' 312 def _join_parts(self, part_strings):
314 for part
in part_strings
315 if part
and part
is not SUPPRESS])
317 def _format_usage(self, usage, actions, groups, prefix):
319 prefix = _(
'usage: ')
322 if usage
is not None:
323 usage = usage % dict(prog=self.
_prog)
326 elif usage
is None and not actions:
327 usage =
'%(prog)s' % dict(prog=self.
_prog)
331 prog =
'%(prog)s' % dict(prog=self.
_prog)
336 for action
in actions:
337 if action.option_strings:
338 optionals.append(action)
340 positionals.append(action)
344 action_usage = format(optionals + positionals, groups)
345 usage =
' '.
join([s
for s
in [prog, action_usage]
if s])
349 if len(prefix) + len(usage) > text_width:
352 part_regexp =
r'\(.*?\)+|\[.*?\]+|\S+' 353 opt_usage = format(optionals, groups)
354 pos_usage = format(positionals, groups)
355 opt_parts = _re.findall(part_regexp, opt_usage)
356 pos_parts = _re.findall(part_regexp, pos_usage)
357 assert ' '.
join(opt_parts) == opt_usage
358 assert ' '.
join(pos_parts) == pos_usage
361 def get_lines(parts, indent, prefix=None):
364 if prefix
is not None:
365 line_len = len(prefix) - 1
367 line_len = len(indent) - 1
369 if line_len + 1 + len(part) > text_width:
370 lines.append(indent +
' '.
join(line))
372 line_len = len(indent) - 1
374 line_len += len(part) + 1
376 lines.append(indent +
' '.
join(line))
377 if prefix
is not None:
378 lines[0] = lines[0][len(indent):]
382 if len(prefix) + len(prog) <= 0.75 * text_width:
383 indent =
' ' * (len(prefix) + len(prog) + 1)
385 lines = get_lines([prog] + opt_parts, indent, prefix)
386 lines.extend(get_lines(pos_parts, indent))
388 lines = get_lines([prog] + pos_parts, indent, prefix)
394 indent =
' ' * len(prefix)
395 parts = opt_parts + pos_parts
396 lines = get_lines(parts, indent)
399 lines.extend(get_lines(opt_parts, indent))
400 lines.extend(get_lines(pos_parts, indent))
401 lines = [prog] + lines
404 usage =
'\n'.
join(lines)
407 return '%s%s\n\n' % (prefix, usage)
409 def _format_actions_usage(self, actions, groups):
411 group_actions = set()
415 start = actions.index(group._group_actions[0])
419 end = start + len(group._group_actions)
420 if actions[start:end] == group._group_actions:
421 for action
in group._group_actions:
422 group_actions.add(action)
423 if not group.required:
425 inserts[start] +=
' [' 431 inserts[start] +=
' (' 435 for i
in range(start + 1, end):
440 for i, action
in enumerate(actions):
444 if action.help
is SUPPRESS:
446 if inserts.get(i) ==
'|':
448 elif inserts.get(i + 1) ==
'|':
452 elif not action.option_strings:
456 if action
in group_actions:
457 if part[0] ==
'[' and part[-1] ==
']':
465 option_string = action.option_strings[0]
469 if action.nargs == 0:
470 part =
'%s' % option_string
475 default = action.dest.upper()
477 part =
'%s %s' % (option_string, args_string)
480 if not action.required
and action
not in group_actions:
487 for i
in sorted(inserts, reverse=
True):
488 parts[i:i] = [inserts[i]]
491 text =
' '.
join([item
for item
in parts
if item
is not None])
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)
505 def _format_text(self, text):
506 if '%(prog)' in text:
507 text = text % dict(prog=self.
_prog)
510 return self.
_fill_text(text, text_width, indent) +
'\n\n' 512 def _format_action(self, action):
516 help_width = self.
_width - help_position
523 action_header =
'%*s%s\n' % tup
526 elif len(action_header) <= action_width:
528 action_header =
'%*s%-*s ' % tup
534 action_header =
'%*s%s\n' % tup
535 indent_first = help_position
538 parts = [action_header]
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))
549 elif not action_header.endswith(
'\n'):
559 def _format_action_invocation(self, action):
560 if not action.option_strings:
569 if action.nargs == 0:
570 parts.extend(action.option_strings)
575 default = action.dest.upper()
577 for option_string
in action.option_strings:
578 parts.append(
'%s %s' % (option_string, args_string))
580 return ', '.
join(parts)
582 def _metavar_formatter(self, action, default_metavar):
583 if action.metavar
is not None:
584 result = action.metavar
585 elif action.choices
is not None:
586 choice_strs = [str(choice)
for choice
in action.choices]
587 result =
'{%s}' %
','.
join(choice_strs)
589 result = default_metavar
591 def format(tuple_size):
592 if isinstance(result, tuple):
595 return (result, ) * tuple_size
598 def _format_args(self, action, default_metavar):
600 if action.nargs
is None:
601 result =
'%s' % get_metavar(1)
602 elif action.nargs == OPTIONAL:
603 result =
'[%s]' % get_metavar(1)
604 elif action.nargs == ZERO_OR_MORE:
605 result =
'[%s [%s ...]]' % get_metavar(2)
606 elif action.nargs == ONE_OR_MORE:
607 result =
'%s [%s ...]' % get_metavar(2)
608 elif action.nargs == REMAINDER:
610 elif action.nargs == PARSER:
611 result =
'%s ...' % get_metavar(1)
613 formats = [
'%s' for _
in range(action.nargs)]
614 result =
' '.
join(formats) % get_metavar(action.nargs)
617 def _expand_help(self, action):
618 params = dict(vars(action), prog=self.
_prog)
619 for name
in list(params):
620 if params[name]
is SUPPRESS:
622 for name
in list(params):
623 if hasattr(params[name],
'__name__'):
624 params[name] = params[name].__name__
625 if params.get(
'choices')
is not None:
626 choices_str =
', '.
join([str(c)
for c
in params[
'choices']])
627 params[
'choices'] = choices_str
630 def _iter_indented_subactions(self, action):
632 get_subactions = action._get_subactions
633 except AttributeError:
637 for subaction
in get_subactions():
641 def _split_lines(self, text, width):
643 return _textwrap.wrap(text, width)
645 def _fill_text(self, text, width, indent):
647 return _textwrap.fill(text, width, initial_indent=indent,
648 subsequent_indent=indent)
650 def _get_help_string(self, action):
655 """Help message formatter which retains any formatting in descriptions. 657 Only the name of this class is considered a public API. All the methods 658 provided by the class are considered an implementation detail. 661 def _fill_text(self, text, width, indent):
662 return ''.
join([indent + line
for line
in text.splitlines(
True)])
666 """Help message formatter which retains formatting of all help text. 668 Only the name of this class is considered a public API. All the methods 669 provided by the class are considered an implementation detail. 672 def _split_lines(self, text, width):
673 return text.splitlines()
677 """Help message formatter which adds default values to argument help. 679 Only the name of this class is considered a public API. All the methods 680 provided by the class are considered an implementation detail. 683 def _get_help_string(self, action):
685 if '%(default)' not in action.help:
686 if action.default
is not SUPPRESS:
687 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
688 if action.option_strings
or action.nargs
in defaulting_nargs:
689 help +=
' (default: %(default)s)' 697 def _get_action_name(argument):
700 elif argument.option_strings:
701 return '/'.
join(argument.option_strings)
702 elif argument.metavar
not in (
None, SUPPRESS):
703 return argument.metavar
704 elif argument.dest
not in (
None, SUPPRESS):
711 """An error from creating or using an argument (optional or positional). 713 The string value of this exception is the message, augmented with 714 information about the argument that caused it. 723 format =
'%(message)s' 725 format =
'argument %(argument_name)s: %(message)s' 726 return format % dict(message=self.
message,
731 """An error from trying to convert a command line string to a type.""" 739 class Action(_AttributeHolder):
740 """Information about how to convert command line strings to Python objects. 742 Action objects are used by an ArgumentParser to represent the information 743 needed to parse a single argument from one or more strings from the 744 command line. The keyword arguments to the Action constructor are also 745 all attributes of Action instances. 749 - option_strings -- A list of command-line option strings which 750 should be associated with this action. 752 - dest -- The name of the attribute to hold the created object(s) 754 - nargs -- The number of command-line arguments that should be 755 consumed. By default, one argument will be consumed and a single 756 value will be produced. Other values include: 757 - N (an integer) consumes N arguments (and produces a list) 758 - '?' consumes zero or one arguments 759 - '*' consumes zero or more arguments (and produces a list) 760 - '+' consumes one or more arguments (and produces a list) 761 Note that the difference between the default and nargs=1 is that 762 with the default, a single value will be produced, while with 763 nargs=1, a list containing a single value will be produced. 765 - const -- The value to be produced if the option is specified and the 766 option uses an action that takes no values. 768 - default -- The value to be produced if the option is not specified. 770 - type -- The type which the command-line arguments should be converted 771 to, should be one of 'string', 'int', 'float', 'complex' or a 772 callable object that accepts a single string argument. If None, 775 - choices -- A container of values that should be allowed. If not None, 776 after a command-line argument has been converted to the appropriate 777 type, an exception will be raised if it is not a member of this 780 - required -- True if the action must always be specified at the 781 command line. This is only meaningful for optional command-line 784 - help -- The help string describing the argument. 786 - metavar -- The name to be used for the option's argument with the 787 help string. If None, the 'dest' value will be used as the name. 812 def _get_kwargs(self):
824 return [(name, getattr(self, name))
for name
in names]
826 def __call__(self, parser, namespace, values, option_string=None):
827 raise NotImplementedError(_(
'.__call__() not defined'))
844 raise ValueError(
'nargs for store actions must be > 0; if you ' 845 'have nothing to store, actions such as store ' 846 'true or store const may be more appropriate')
847 if const
is not None and nargs != OPTIONAL:
848 raise ValueError(
'nargs must be %r to supply const' % OPTIONAL)
850 option_strings=option_strings,
861 def __call__(self, parser, namespace, values, option_string=None):
862 setattr(namespace, self.
dest, values)
875 super(_StoreConstAction, self).
__init__(
876 option_strings=option_strings,
884 def __call__(self, parser, namespace, values, option_string=None):
885 setattr(namespace, self.
dest, self.
const)
896 super(_StoreTrueAction, self).
__init__(
897 option_strings=option_strings,
913 super(_StoreFalseAction, self).
__init__(
914 option_strings=option_strings,
936 raise ValueError(
'nargs for append actions must be > 0; if arg ' 937 'strings are not supplying the value to append, ' 938 'the append const action may be more appropriate')
939 if const
is not None and nargs != OPTIONAL:
940 raise ValueError(
'nargs must be %r to supply const' % OPTIONAL)
941 super(_AppendAction, self).
__init__(
942 option_strings=option_strings,
953 def __call__(self, parser, namespace, values, option_string=None):
954 items = _copy.copy(_ensure_value(namespace, self.
dest, []))
956 setattr(namespace, self.
dest, items)
969 super(_AppendConstAction, self).
__init__(
970 option_strings=option_strings,
979 def __call__(self, parser, namespace, values, option_string=None):
980 items = _copy.copy(_ensure_value(namespace, self.
dest, []))
981 items.append(self.
const)
982 setattr(namespace, self.
dest, items)
994 option_strings=option_strings,
1001 def __call__(self, parser, namespace, values, option_string=None):
1002 new_count = _ensure_value(namespace, self.
dest, 0) + 1
1003 setattr(namespace, self.
dest, new_count)
1014 option_strings=option_strings,
1020 def __call__(self, parser, namespace, values, option_string=None):
1032 help="show program's version number and exit"):
1033 super(_VersionAction, self).
__init__(
1034 option_strings=option_strings,
1041 def __call__(self, parser, namespace, values, option_string=None):
1044 version = parser.version
1045 formatter = parser._get_formatter()
1046 formatter.add_text(version)
1047 parser.exit(message=formatter.format_help())
1055 metavar = dest = name
1057 metavar +=
' (%s)' %
', '.
join(aliases)
1059 sup.__init__(option_strings=[], dest=dest, help=help,
1075 super(_SubParsersAction, self).
__init__(
1076 option_strings=option_strings,
1085 if kwargs.get(
'prog')
is None:
1088 aliases = kwargs.pop(
'aliases', ())
1091 if 'help' in kwargs:
1092 help = kwargs.pop(
'help')
1101 for alias
in aliases:
1106 def _get_subactions(self):
1109 def __call__(self, parser, namespace, values, option_string=None):
1110 parser_name = values[0]
1111 arg_strings = values[1:]
1114 if self.
dest is not SUPPRESS:
1115 setattr(namespace, self.
dest, parser_name)
1122 msg = _(
'unknown parser %r (choices: %s)' % tup)
1128 namespace, arg_strings = parser.parse_known_args(arg_strings, namespace)
1130 vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1131 getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
1139 """Factory for creating file object types 1141 Instances of FileType are typically passed as type= arguments to the 1142 ArgumentParser add_argument() method. 1145 - mode -- A string indicating how the file is to be opened. Accepts the 1146 same values as the builtin open() function. 1147 - bufsize -- The file's desired buffer size. Accepts the same values as 1148 the builtin open() function. 1158 if 'r' in self._mode: 1160 elif 'w' in self.
_mode:
1163 msg = _(
'argument "-" with mode %r' % self.
_mode)
1164 raise ValueError(msg)
1171 return open(string, self.
_mode)
1173 err = _sys.exc_info()[1]
1174 message = _(
"can't open '%s': %s")
1179 args_str =
', '.
join([repr(arg)
for arg
in args
if arg
is not None])
1180 return '%s(%s)' % (type(self).__name__, args_str)
1187 """Simple object for storing attributes. 1189 Implements equality by attribute names and values, and provides a simple 1190 string representation. 1195 setattr(self, name, kwargs[name])
1200 return vars(self) == vars(other)
1203 return not (self == other)
1206 return key
in self.__dict__
1216 super(_ActionsContainer, self).
__init__()
1227 self.
register(
'action',
None, _StoreAction)
1228 self.
register(
'action',
'store', _StoreAction)
1229 self.
register(
'action',
'store_const', _StoreConstAction)
1230 self.
register(
'action',
'store_true', _StoreTrueAction)
1231 self.
register(
'action',
'store_false', _StoreFalseAction)
1232 self.
register(
'action',
'append', _AppendAction)
1233 self.
register(
'action',
'append_const', _AppendConstAction)
1234 self.
register(
'action',
'count', _CountAction)
1235 self.
register(
'action',
'help', _HelpAction)
1236 self.
register(
'action',
'version', _VersionAction)
1237 self.
register(
'action',
'parsers', _SubParsersAction)
1264 registry = self.
_registries.setdefault(registry_name, {})
1265 registry[value] = object
1267 def _registry_get(self, registry_name, value, default=None):
1268 return self.
_registries[registry_name].get(value, default)
1279 if action.dest
in kwargs:
1280 action.default = kwargs[action.dest]
1284 if action.dest == dest
and action.default
is not None:
1285 return action.default
1294 add_argument(dest, ..., name=value, ...) 1295 add_argument(option_string, option_string, ..., name=value, ...) 1302 if not args
or len(args) == 1
and args[0][0]
not in chars:
1303 if args
and 'dest' in kwargs:
1304 raise ValueError(
'dest supplied twice for positional argument')
1312 if 'default' not in kwargs:
1313 dest = kwargs[
'dest']
1315 kwargs[
'default'] = self.
_defaults[dest]
1321 if not _callable(action_class):
1322 raise ValueError(
'unknown action "%s"' % action_class)
1323 action = action_class(**kwargs)
1326 type_func = self.
_registry_get(
'type', action.type, action.type)
1327 if not _callable(type_func):
1328 raise ValueError(
'%r is not callable' % type_func)
1342 def _add_action(self, action):
1348 action.container = self
1351 for option_string
in action.option_strings:
1355 for option_string
in action.option_strings:
1363 def _remove_action(self, action):
1366 def _add_container_actions(self, container):
1368 title_group_map = {}
1370 if group.title
in title_group_map:
1371 msg = _(
'cannot merge actions - two groups are named %r')
1372 raise ValueError(msg % (group.title))
1373 title_group_map[group.title] = group
1377 for group
in container._action_groups:
1381 if group.title
not in title_group_map:
1384 description=group.description,
1385 conflict_handler=group.conflict_handler)
1388 for action
in group._group_actions:
1389 group_map[action] = title_group_map[group.title]
1394 for group
in container._mutually_exclusive_groups:
1396 required=group.required)
1399 for action
in group._group_actions:
1400 group_map[action] = mutex_group
1403 for action
in container._actions:
1404 group_map.get(action, self)._add_action(action)
1406 def _get_positional_kwargs(self, dest, **kwargs):
1408 if 'required' in kwargs:
1409 msg = _(
"'required' is an invalid argument for positionals")
1410 raise TypeError(msg)
1414 if kwargs.get(
'nargs')
not in [OPTIONAL, ZERO_OR_MORE]:
1415 kwargs[
'required'] =
True 1416 if kwargs.get(
'nargs') == ZERO_OR_MORE
and 'default' not in kwargs:
1417 kwargs[
'required'] =
True 1420 return dict(kwargs, dest=dest, option_strings=[])
1422 def _get_optional_kwargs(self, *args, **kwargs):
1425 long_option_strings = []
1426 for option_string
in args:
1429 msg = _(
'invalid option string %r: ' 1430 'must start with a character %r')
1432 raise ValueError(msg % tup)
1435 option_strings.append(option_string)
1437 if len(option_string) > 1:
1439 long_option_strings.append(option_string)
1442 dest = kwargs.pop(
'dest',
None)
1444 if long_option_strings:
1445 dest_option_string = long_option_strings[0]
1447 dest_option_string = option_strings[0]
1450 msg = _(
'dest= is required for options like %r')
1451 raise ValueError(msg % option_string)
1452 dest = dest.replace(
'-',
'_')
1455 return dict(kwargs, dest=dest, option_strings=option_strings)
1457 def _pop_action_class(self, kwargs, default=None):
1458 action = kwargs.pop(
'action', default)
1461 def _get_handler(self):
1465 return getattr(self, handler_func_name)
1466 except AttributeError:
1467 msg = _(
'invalid conflict_resolution value: %r')
1470 def _check_conflict(self, action):
1473 confl_optionals = []
1474 for option_string
in action.option_strings:
1477 confl_optionals.append((option_string, confl_optional))
1484 def _handle_conflict_error(self, action, conflicting_actions):
1485 message = _(
'conflicting option string(s): %s')
1486 conflict_string =
', '.
join([option_string
1487 for option_string, action
1488 in conflicting_actions])
1491 def _handle_conflict_resolve(self, action, conflicting_actions):
1494 for option_string, action
in conflicting_actions:
1497 action.option_strings.remove(option_string)
1502 if not action.option_strings:
1503 action.container._remove_action(action)
1508 def __init__(self, container, title=None, description=None, **kwargs):
1510 update = kwargs.setdefault
1511 update(
'conflict_handler', container.conflict_handler)
1512 update(
'prefix_chars', container.prefix_chars)
1513 update(
'argument_default', container.argument_default)
1514 super_init = super(_ArgumentGroup, self).__init__
1515 super_init(description=description, **kwargs)
1527 container._has_negative_number_optionals
1529 def _add_action(self, action):
1530 action = super(_ArgumentGroup, self)._add_action(action)
1534 def _remove_action(self, action):
1535 super(_ArgumentGroup, self)._remove_action(action)
1542 super(_MutuallyExclusiveGroup, self).
__init__(container)
1546 def _add_action(self, action):
1548 msg = _(
'mutually exclusive arguments must be optional')
1549 raise ValueError(msg)
1554 def _remove_action(self, action):
1560 """Object for parsing command line strings into Python objects. 1563 - prog -- The name of the program (default: sys.argv[0]) 1564 - usage -- A usage message (default: auto-generated from arguments) 1565 - description -- A description of what the program does 1566 - epilog -- Text following the argument descriptions 1567 - parents -- Parsers whose arguments should be copied into this one 1568 - formatter_class -- HelpFormatter class for printing help messages 1569 - prefix_chars -- Characters that prefix optional arguments 1570 - fromfile_prefix_chars -- Characters that prefix files containing 1571 additional arguments 1572 - argument_default -- The default value for all arguments 1573 - conflict_handler -- String indicating how to handle conflicts 1574 - add_help -- Add a -h/-help option 1584 formatter_class=HelpFormatter,
1586 fromfile_prefix_chars=None,
1587 argument_default=None,
1588 conflict_handler='error',
1591 if version
is not None:
1594 """The "version" argument to ArgumentParser is deprecated. """ 1596 """"add_argument(..., action='version', version="N", ...)" """ 1597 """instead""", DeprecationWarning)
1599 superinit = super(ArgumentParser, self).__init__
1600 superinit(description=description,
1601 prefix_chars=prefix_chars,
1602 argument_default=argument_default,
1603 conflict_handler=conflict_handler)
1607 prog = _os.path.basename(_sys.argv[0])
1618 self.
_positionals = add_group(_(
'positional arguments'))
1619 self.
_optionals = add_group(_(
'optional arguments'))
1623 def identity(string):
1625 self.
register(
'type',
None, identity)
1629 if '-' in prefix_chars:
1630 default_prefix =
'-' 1632 default_prefix = prefix_chars[0]
1635 default_prefix+
'h', default_prefix*2+
'help',
1636 action=
'help', default=SUPPRESS,
1637 help=_(
'show this help message and exit'))
1640 default_prefix+
'v', default_prefix*2+
'version',
1641 action=
'version', default=SUPPRESS,
1643 help=_(
"show program's version number and exit"))
1646 for parent
in parents:
1649 defaults = parent._defaults
1650 except AttributeError:
1658 def _get_kwargs(self):
1668 return [(name, getattr(self, name))
for name
in names]
1675 self.
error(_(
'cannot have multiple subparser arguments'))
1678 kwargs.setdefault(
'parser_class', type(self))
1680 if 'title' in kwargs
or 'description' in kwargs:
1681 title = _(kwargs.pop(
'title',
'subcommands'))
1682 description = _(kwargs.pop(
'description',
None))
1689 if kwargs.get(
'prog')
is None:
1693 formatter.add_usage(self.
usage, positionals, groups,
'')
1694 kwargs[
'prog'] = formatter.format_help().strip()
1698 action = parsers_class(option_strings=[], **kwargs)
1704 def _add_action(self, action):
1705 if action.option_strings:
1711 def _get_optional_actions(self):
1714 if action.option_strings]
1716 def _get_positional_actions(self):
1719 if not action.option_strings]
1727 msg = _(
'unrecognized arguments: %s')
1734 args = _sys.argv[1:]
1737 if namespace
is None:
1742 if action.dest
is not SUPPRESS:
1743 if not hasattr(namespace, action.dest):
1744 if action.default
is not SUPPRESS:
1745 setattr(namespace, action.dest, action.default)
1749 if not hasattr(namespace, dest):
1750 setattr(namespace, dest, self.
_defaults[dest])
1755 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1756 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1757 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1758 return namespace, args
1759 except ArgumentError:
1760 err = _sys.exc_info()[1]
1761 self.
error(str(err))
1763 def _parse_known_args(self, arg_strings, namespace):
1770 action_conflicts = {}
1772 group_actions = mutex_group._group_actions
1773 for i, mutex_action
in enumerate(mutex_group._group_actions):
1774 conflicts = action_conflicts.setdefault(mutex_action, [])
1775 conflicts.extend(group_actions[:i])
1776 conflicts.extend(group_actions[i + 1:])
1781 option_string_indices = {}
1782 arg_string_pattern_parts = []
1783 arg_strings_iter = iter(arg_strings)
1784 for i, arg_string
in enumerate(arg_strings_iter):
1787 if arg_string ==
'--':
1788 arg_string_pattern_parts.append(
'-')
1789 for arg_string
in arg_strings_iter:
1790 arg_string_pattern_parts.append(
'A')
1796 if option_tuple
is None:
1799 option_string_indices[i] = option_tuple
1801 arg_string_pattern_parts.append(pattern)
1804 arg_strings_pattern =
''.
join(arg_string_pattern_parts)
1807 seen_actions = set()
1808 seen_non_default_actions = set()
1810 def take_action(action, argument_strings, option_string=None):
1811 seen_actions.add(action)
1812 argument_values = self.
_get_values(action, argument_strings)
1817 if argument_values
is not action.default:
1818 seen_non_default_actions.add(action)
1819 for conflict_action
in action_conflicts.get(action, []):
1820 if conflict_action
in seen_non_default_actions:
1821 msg = _(
'not allowed with argument %s')
1822 action_name = _get_action_name(conflict_action)
1827 if argument_values
is not SUPPRESS:
1828 action(self, namespace, argument_values, option_string)
1831 def consume_optional(start_index):
1834 option_tuple = option_string_indices[start_index]
1835 action, option_string, explicit_arg = option_tuple
1845 extras.append(arg_strings[start_index])
1846 return start_index + 1
1850 if explicit_arg
is not None:
1851 arg_count = match_argument(action,
'A')
1857 if arg_count == 0
and option_string[1]
not in chars:
1858 action_tuples.append((action, [], option_string))
1859 char = option_string[0]
1860 option_string = char + explicit_arg[0]
1861 new_explicit_arg = explicit_arg[1:]
or None 1863 if option_string
in optionals_map:
1864 action = optionals_map[option_string]
1865 explicit_arg = new_explicit_arg
1867 msg = _(
'ignored explicit argument %r')
1872 elif arg_count == 1:
1873 stop = start_index + 1
1874 args = [explicit_arg]
1875 action_tuples.append((action, args, option_string))
1881 msg = _(
'ignored explicit argument %r')
1888 start = start_index + 1
1889 selected_patterns = arg_strings_pattern[start:]
1890 arg_count = match_argument(action, selected_patterns)
1891 stop = start + arg_count
1892 args = arg_strings[start:stop]
1893 action_tuples.append((action, args, option_string))
1898 assert action_tuples
1899 for action, args, option_string
in action_tuples:
1900 take_action(action, args, option_string)
1908 def consume_positionals(start_index):
1911 selected_pattern = arg_strings_pattern[start_index:]
1912 arg_counts = match_partial(positionals, selected_pattern)
1916 for action, arg_count
in zip(positionals, arg_counts):
1917 args = arg_strings[start_index: start_index + arg_count]
1918 start_index += arg_count
1919 take_action(action, args)
1923 positionals[:] = positionals[len(arg_counts):]
1930 if option_string_indices:
1931 max_option_string_index = max(option_string_indices)
1933 max_option_string_index = -1
1934 while start_index <= max_option_string_index:
1937 next_option_string_index = min([
1939 for index
in option_string_indices
1940 if index >= start_index])
1941 if start_index != next_option_string_index:
1942 positionals_end_index = consume_positionals(start_index)
1946 if positionals_end_index > start_index:
1947 start_index = positionals_end_index
1950 start_index = positionals_end_index
1954 if start_index
not in option_string_indices:
1955 strings = arg_strings[start_index:next_option_string_index]
1956 extras.extend(strings)
1957 start_index = next_option_string_index
1960 start_index = consume_optional(start_index)
1963 stop_index = consume_positionals(start_index)
1966 extras.extend(arg_strings[stop_index:])
1971 self.
error(_(
'too few arguments'))
1975 if action
not in seen_actions:
1977 name = _get_action_name(action)
1978 self.
error(_(
'argument %s is required') % name)
1984 if (action.default
is not None and 1985 isinstance(action.default, basestring)
and 1986 hasattr(namespace, action.dest)
and 1987 action.default
is getattr(namespace, action.dest)):
1988 setattr(namespace, action.dest,
1994 for action
in group._group_actions:
1995 if action
in seen_non_default_actions:
2000 names = [_get_action_name(action)
2001 for action
in group._group_actions
2002 if action.help
is not SUPPRESS]
2003 msg = _(
'one of the arguments %s is required')
2007 return namespace, extras
2009 def _read_args_from_files(self, arg_strings):
2011 new_arg_strings = []
2012 for arg_string
in arg_strings:
2016 new_arg_strings.append(arg_string)
2021 args_file = open(arg_string[1:])
2024 for arg_line
in args_file.read().splitlines():
2026 arg_strings.append(arg)
2028 new_arg_strings.extend(arg_strings)
2032 err = _sys.exc_info()[1]
2033 self.
error(str(err))
2036 return new_arg_strings
2041 def _match_argument(self, action, arg_strings_pattern):
2044 match = _re.match(nargs_pattern, arg_strings_pattern)
2049 None: _(
'expected one argument'),
2050 OPTIONAL: _(
'expected at most one argument'),
2051 ONE_OR_MORE: _(
'expected at least one argument'),
2053 default = _(
'expected %s argument(s)') % action.nargs
2054 msg = nargs_errors.get(action.nargs, default)
2058 return len(match.group(1))
2060 def _match_arguments_partial(self, actions, arg_strings_pattern):
2064 for i
in range(len(actions), 0, -1):
2065 actions_slice = actions[:i]
2067 for action
in actions_slice])
2068 match = _re.match(pattern, arg_strings_pattern)
2069 if match
is not None:
2070 result.extend([len(string)
for string
in match.groups()])
2076 def _parse_optional(self, arg_string):
2088 return action, arg_string,
None 2091 if len(arg_string) == 1:
2095 if '=' in arg_string:
2096 option_string, explicit_arg = arg_string.split(
'=', 1)
2099 return action, option_string, explicit_arg
2106 if len(option_tuples) > 1:
2107 options =
', '.
join([option_string
2108 for action, option_string, explicit_arg
in option_tuples])
2109 tup = arg_string, options
2110 self.
error(_(
'ambiguous option: %s could match %s') % tup)
2114 elif len(option_tuples) == 1:
2115 option_tuple, = option_tuples
2126 if ' ' in arg_string:
2131 return None, arg_string,
None 2133 def _get_option_tuples(self, option_string):
2139 if option_string[0]
in chars
and option_string[1]
in chars:
2140 if '=' in option_string:
2141 option_prefix, explicit_arg = option_string.split(
'=', 1)
2143 option_prefix = option_string
2146 if option_string.startswith(option_prefix):
2148 tup = action, option_string, explicit_arg
2154 elif option_string[0]
in chars
and option_string[1]
not in chars:
2155 option_prefix = option_string
2157 short_option_prefix = option_string[:2]
2158 short_explicit_arg = option_string[2:]
2161 if option_string == short_option_prefix:
2163 tup = action, option_string, short_explicit_arg
2165 elif option_string.startswith(option_prefix):
2167 tup = action, option_string, explicit_arg
2172 self.
error(_(
'unexpected option string: %s') % option_string)
2177 def _get_nargs_pattern(self, action):
2180 nargs = action.nargs
2184 nargs_pattern =
'(-*A-*)' 2187 elif nargs == OPTIONAL:
2188 nargs_pattern =
'(-*A?-*)' 2191 elif nargs == ZERO_OR_MORE:
2192 nargs_pattern =
'(-*[A-]*)' 2195 elif nargs == ONE_OR_MORE:
2196 nargs_pattern =
'(-*A[A-]*)' 2199 elif nargs == REMAINDER:
2200 nargs_pattern =
'([-AO]*)' 2203 elif nargs == PARSER:
2204 nargs_pattern =
'(-*A[-AO]*)' 2208 nargs_pattern =
'(-*%s-*)' %
'-*'.
join(
'A' * nargs)
2211 if action.option_strings:
2212 nargs_pattern = nargs_pattern.replace(
'-*',
'')
2213 nargs_pattern = nargs_pattern.replace(
'-',
'')
2216 return nargs_pattern
2221 def _get_values(self, action, arg_strings):
2223 if action.nargs
not in [PARSER, REMAINDER]:
2224 arg_strings = [s
for s
in arg_strings
if s !=
'--']
2227 if not arg_strings
and action.nargs == OPTIONAL:
2228 if action.option_strings:
2229 value = action.const
2231 value = action.default
2232 if isinstance(value, basestring):
2238 elif (
not arg_strings
and action.nargs == ZERO_OR_MORE
and 2239 not action.option_strings):
2240 if action.default
is not None:
2241 value = action.default
2247 elif len(arg_strings) == 1
and action.nargs
in [
None, OPTIONAL]:
2248 arg_string, = arg_strings
2253 elif action.nargs == REMAINDER:
2254 value = [self.
_get_value(action, v)
for v
in arg_strings]
2257 elif action.nargs == PARSER:
2258 value = [self.
_get_value(action, v)
for v
in arg_strings]
2263 value = [self.
_get_value(action, v)
for v
in arg_strings]
2270 def _get_value(self, action, arg_string):
2271 type_func = self.
_registry_get(
'type', action.type, action.type)
2272 if not _callable(type_func):
2273 msg = _(
'%r is not callable')
2278 result = type_func(arg_string)
2281 except ArgumentTypeError:
2282 name = getattr(action.type,
'__name__', repr(action.type))
2283 msg = str(_sys.exc_info()[1])
2287 except (TypeError, ValueError):
2288 name = getattr(action.type,
'__name__', repr(action.type))
2289 msg = _(
'invalid %s value: %r')
2295 def _check_value(self, action, value):
2297 if action.choices
is not None and value
not in action.choices:
2298 tup = value,
', '.
join(map(repr, action.choices))
2299 msg = _(
'invalid choice: %r (choose from %s)') % tup
2309 return formatter.format_help()
2323 formatter.start_section(action_group.title)
2324 formatter.add_text(action_group.description)
2325 formatter.add_arguments(action_group._group_actions)
2326 formatter.end_section()
2329 formatter.add_text(self.
epilog)
2332 return formatter.format_help()
2337 'The format_version method is deprecated -- the "version" ' 2338 'argument to ArgumentParser is no longer supported.',
2341 formatter.add_text(self.
version)
2342 return formatter.format_help()
2344 def _get_formatter(self):
2363 'The print_version method is deprecated -- the "version" ' 2364 'argument to ArgumentParser is no longer supported.',
2368 def _print_message(self, message, file=None):
2377 def exit(self, status=0, message=None):
2383 """error(message: string) 2385 Prints a usage message incorporating the message to stderr and 2388 If you override this in a subclass, it should not return -- it 2389 should either exit or raise an exception. 2392 self.
exit(2, _(
'%s: error: %s\n') % (self.
prog, message))
def add_argument_group(self, args, kwargs)
def __call__(self, parser, namespace, values, option_string=None)
def _check_conflict(self, action)
def __call__(self, parser, namespace, values, option_string=None)
def sorted(iterable, reverse=False)
def register(self, registry_name, value, object)
_has_negative_number_optionals
def __call__(self, parser, namespace, values, option_string=None)
def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
def _match_arguments_partial(self, actions, arg_strings_pattern)
def _get_values(self, action, arg_strings)
def _get_optional_kwargs(self, args, kwargs)
def __init__(self, option_strings, version=None, dest=SUPPRESS, default=SUPPRESS, help="show program's version number and exit")
def __call__(self, parser, namespace, values, option_string=None)
std::string join(const std::string &base, const std::string &path)
Join two paths, e.g., base path and relative path.
def add_mutually_exclusive_group(self, kwargs)
def _add_container_actions(self, container)
def print_usage(self, file=None)
def print_help(self, file=None)
def __call__(self, parser, namespace, values, option_string=None)
def _parse_known_args(self, arg_strings, namespace)
def exit(self, status=0, message=None)
def parse_args(self, args=None, namespace=None)
def parse_known_args(self, args=None, namespace=None)
def __init__(self, prog=None, usage=None, description=None, epilog=None, version=None, parents=[], formatter_class=HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)
def __init__(self, option_strings, dest, default=None, required=False, help=None)
def __init__(self, mode='r', bufsize=None)
def __init__(self, argument, message)
def _print_message(self, message, file=None)
def print_version(self, file=None)
def _get_option_tuples(self, option_string)
def add_argument(self, args, kwargs)
def __init__(self, option_strings, prog, parser_class, dest=SUPPRESS, help=None, metavar=None)
def add_parser(self, name, kwargs)
def __init__(self, option_strings, dest, const, default=None, required=False, help=None, metavar=None)
def convert_arg_line_to_args(self, arg_line)
def __contains__(self, key)
_mutually_exclusive_groups
def _get_positional_actions(self)
def set_defaults(self, kwargs)
def _get_positional_kwargs(self, dest, kwargs)
def __call__(self, parser, namespace, values, option_string=None)
def _get_nargs_pattern(self, action)
def _add_action(self, action)
def _match_argument(self, action, arg_strings_pattern)
def __call__(self, string)
def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
def __init__(self, option_strings, dest, const, default=None, required=False, help=None, metavar=None)
function match(in value, in pattern)
This function implements a more portable way to do pattern matching.
def __init__(self, container, required=False)
def __init__(self, option_strings, dest, default=True, required=False, help=None)
def __call__(self, parser, namespace, values, option_string=None)
def __init__(self, description, prefix_chars, argument_default, conflict_handler)
def _pop_action_class(self, kwargs, default=None)
def _parse_optional(self, arg_string)
def add_subparsers(self, kwargs)
def __init__(self, option_strings, dest=SUPPRESS, default=SUPPRESS, help=None)
def __call__(self, parser, namespace, values, option_string=None)
def __init__(self, option_strings, dest, default=False, required=False, help=None)
def __call__(self, parser, namespace, values, option_string=None)
def __init__(self, option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
def __init__(self, name, aliases, help)
def _read_args_from_files(self, arg_strings)
def _check_value(self, action, value)
def _registry_get(self, registry_name, value, default=None)
def get_default(self, dest)
def __init__(self, container, title=None, description=None, kwargs)
def _get_value(self, action, arg_string)
def __init__(self, kwargs)