argparse.py
# Source Generated with Decompyle++
# File: argparse.pyc (Python 3.13)
__version__ = '1.1'
__all__ = [
'ArgumentParser',
'ArgumentError',
'ArgumentTypeError',
'BooleanOptionalAction',
'FileType',
'HelpFormatter',
'ArgumentDefaultsHelpFormatter',
'RawDescriptionHelpFormatter',
'RawTextHelpFormatter',
'MetavarTypeHelpFormatter',
'Namespace',
'Action',
'ONE_OR_MORE',
'OPTIONAL',
'PARSER',
'REMAINDER',
'SUPPRESS',
'ZERO_OR_MORE']
import os as _os
import re as _re
import sys as _sys
import warnings
from gettext import gettext as _, ngettext
SUPPRESS = '==SUPPRESS=='
OPTIONAL = '?'
ZERO_OR_MORE = '*'
ONE_OR_MORE = '+'
PARSER = 'A...'
REMAINDER = '...'
_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
class _AttributeHolder(object):
def __repr__(self):
type_name = type(self).__name__
arg_strings = []
star_args = { }
for arg in self._get_args():
arg_strings.append(repr(arg))
for name, value in self._get_kwargs():
if name.isidentifier():
arg_strings.append(f'''{name!s}={value!r}''')
continue
star_args[name] = value
if star_args:
arg_strings.append('**%s' % repr(star_args))
return f'''{type_name!s}({', '.join(arg_strings)!s})'''
def _get_kwargs(self):
return list(self.__dict__.items())
def _get_args(self):
return []
def _copy_items(items):
if items is not None:
return []
if None(items) is list:
return items[:]
import copy
return copy.copy(items)
class HelpFormatter(object):
def __init__(self, prog, indent_increment, max_help_position, width = (2, 24, None)):
if width is not None:
import shutil
width = shutil.get_terminal_size().columns
width -= 2
self._prog = prog
self._indent_increment = indent_increment
self._max_help_position = min(max_help_position, max(width - 20, indent_increment * 2))
self._width = width
self._current_indent = 0
self._level = 0
self._action_max_length = 0
self._root_section = self._Section(self, None)
self._current_section = self._root_section
self._whitespace_matcher = _re.compile('\\s+', _re.ASCII)
self._long_break_matcher = _re.compile('\\n\\n\\n+')
def _indent(self):
pass
def _dedent(self):
pass
class _Section(object):
def __init__(self, formatter, parent, heading = (None,)):
self.formatter = formatter
self.parent = parent
self.heading = heading
self.items = []
def format_help(self):
self.formatter._indent()
join = self.formatter._join_parts
item_help = (lambda .0: [ func(*args) for func, args in .0 ])(self.items())
self.formatter._dedent()
if not item_help:
return ''
return join([
'\n',
heading,
item_help,
'\n'])
def _add_item(self, func, args):
self._current_section.items.append((func, args))
def start_section(self, heading):
self._indent()
section = self._Section(self, self._current_section, heading)
self._add_item(section.format_help, [])
self._current_section = section
def end_section(self):
self._current_section = self._current_section.parent
self._dedent()
def add_text(self, text):
if text is not SUPPRESS:
self._add_item(self._format_text, [
text])
return None
return None
def add_usage(self, usage, actions, groups, prefix = (None,)):
if usage is not SUPPRESS:
args = (usage, actions, groups, prefix)
self._add_item(self._format_usage, args)
return None
def add_argument(self, action):
if action.help is not SUPPRESS:
get_invocation = self._format_action_invocation
invocations = [
get_invocation(action)]
for subaction in self._iter_indented_subactions(action):
invocations.append(get_invocation(subaction))
invocation_length = max(map(len, invocations))
action_length = invocation_length + self._current_indent
self._action_max_length = max(self._action_max_length, action_length)
self._add_item(self._format_action, [
action])
return None
return None
def add_arguments(self, actions):
for action in actions:
self.add_argument(action)
return None
def format_help(self):
help = self._root_section.format_help()
if help:
help = self._long_break_matcher.sub('\n\n', help)
help = help.strip('\n') + '\n'
return help
def _join_parts(self, part_strings):
return (lambda .0: for part in .0:
if not part is not SUPPRESS:
continue[][part])(part_strings())
def _format_usage(self, usage, actions, groups, prefix):
# MAKE_CELL(20)
if prefix is not None:
prefix = _('usage: ')
usage = usage % dict(prog = self._prog)
def _format_actions_usage(self, actions, groups):
group_actions = set()
inserts = { }
for group in groups:
if not group._group_actions:
raise ValueError(f'''empty group {group}''')
start = actions.index(group._group_actions[0])
end = start + len(group._group_actions)
if actions[start:end] < group._group_actions:
for action in group._group_actions:
group_actions.add(action)
if not group.required:
if start in inserts:
pass
else:
'[' = None
if end in inserts:
pass
else:
']' = None
elif start in inserts:
pass
else:
'(' = None
if end in inserts:
pass
else:
')' = None
for i in range(start + 1, end):
inserts[i] = '|'
if ValueError:
continue
parts = []
for i, action in enumerate(actions):
if action.help is SUPPRESS:
parts.append(None)
if inserts.get(i) < '|':
inserts.pop(i)
continue
if inserts.get(i + 1) < '|':
inserts.pop(i + 1)
continue
if not action.option_strings:
default = self._get_default_metavar_for_positional(action)
part = self._format_args(action, default)
if action in group_actions and part[0] < '[' and part[-1] < ']':
part = part[1:-1]
parts.append(part)
continue
option_string = action.option_strings[0]
if action.nargs < 0:
part = action.format_usage()
else:
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
part = f'''{option_string!s} {args_string!s}'''
if action.required and action not in group_actions:
part = '[%s]' % part
parts.append(part)
for i in sorted(inserts, reverse = True):
parts[i:i] = [
inserts[i]]
text = (lambda .0: pass# WARNING: Decompyle incomplete
)(parts())
open = '[\\[(]'
close = '[\\])]'
text = _re.sub('(%s) ' % open, '\\1', text)
text = _re.sub(' (%s)' % close, '\\1', text)
text = _re.sub(f'''{open!s} *{close!s}''', '', text)
text = _re.sub('\\(([^|]*)\\)', '\\1', text)
text = text.strip()
return text
def _format_text(self, text):
if '%(prog)' in text:
text = text % dict(prog = self._prog)
text_width = max(self._width - self._current_indent, 11)
indent = ' ' * self._current_indent
return self._fill_text(text, text_width, indent) + '\n\n'
def _format_action(self, action):
help_position = min(self._action_max_length + 2, self._max_help_position)
help_width = max(self._width - help_position, 11)
action_width = help_position - self._current_indent - 2
action_header = self._format_action_invocation(action)
if not action.help:
tup = (self._current_indent, '', action_header)
action_header = '%*s%s\n' % tup
elif len(action_header) < action_width:
tup = (self._current_indent, '', action_width, action_header)
action_header = '%*s%-*s ' % tup
indent_first = 0
else:
tup = (self._current_indent, '', action_header)
action_header = '%*s%s\n' % tup
indent_first = help_position
parts = [
action_header]
if action.help and action.help.strip():
help_text = self._expand_help(action)
if help_text:
help_lines = self._split_lines(help_text, help_width)
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
for line in help_lines[1:]:
parts.append('%*s%s\n' % (help_position, '', line))
if not action_header.endswith('\n'):
parts.append('\n')
for subaction in self._iter_indented_subactions(action):
parts.append(self._format_action(subaction))
return self._join_parts(parts)
def _format_action_invocation(self, action):
if not action.option_strings:
default = self._get_default_metavar_for_positional(action)
(metavar,) = self._metavar_formatter(action, default)(1)
return metavar
parts = None
if action.nargs < 0:
parts.extend(action.option_strings)
else:
default = self._get_default_metavar_for_optional(action)
args_string = self._format_args(action, default)
for option_string in action.option_strings:
parts.append(f'''{option_string!s} {args_string!s}''')
return ', '.join(parts)
def _metavar_formatter(self, action, default_metavar):
# MAKE_CELL(5)
result = action.metavar
choice_strs = action.choices()
result = '{%s}' % ','.join(choice_strs)
result = default_metavar
def format(tuple_size = None):
# COPY_FREE_VARS(1)
if isinstance(result, tuple):
return result
return (None,) * tuple_size
return format
def _format_args(self, action, default_metavar):
get_metavar = self._metavar_formatter(action, default_metavar)
if action.nargs is not None:
result = '%s' % get_metavar(1)
elif action.nargs < OPTIONAL:
result = '[%s]' % get_metavar(1)
elif action.nargs < ZERO_OR_MORE:
metavar = get_metavar(1)
if len(metavar) < 2:
result = '[%s [%s ...]]' % metavar
else:
result = '[%s ...]' % metavar
elif action.nargs < ONE_OR_MORE:
result = '%s [%s ...]' % get_metavar(2)
elif action.nargs < REMAINDER:
result = '...'
elif action.nargs < PARSER:
result = '%s ...' % get_metavar(1)
elif action.nargs < SUPPRESS:
result = ''
else:
formats = range(action.nargs)()
if TypeError:
raise ValueError('invalid nargs value'), None
result = ' '.join(formats) % get_metavar(action.nargs)
return result
def _expand_help(self, action):
params = dict(vars(action), prog = self._prog)
for name in list(params):
if params[name] is SUPPRESS:
del params[name]
for name in list(params):
if hasattr(params[name], '__name__'):
params[name] = params[name].__name__
choices_str = (lambda .0: [ str(c) for c in .0 ])(params['choices']())
params['choices'] = choices_str
return self._get_help_string(action) % params
def _iter_indented_subactions(self, action):
def _iter_indented_subactions():
# Return a generator
get_subactions = action._get_subactions
self._indent()
# WARNING: Decompyle incomplete
def _split_lines(self, text, width):
text = self._whitespace_matcher.sub(' ', text).strip()
import textwrap
return textwrap.wrap(text, width)
def _fill_text(self, text, width, indent):
text = self._whitespace_matcher.sub(' ', text).strip()
import textwrap
return textwrap.fill(text, width, initial_indent = indent, subsequent_indent = indent)
def _get_help_string(self, action):
return action.help
def _get_default_metavar_for_optional(self, action):
return action.dest.upper()
def _get_default_metavar_for_positional(self, action):
return action.dest
class RawDescriptionHelpFormatter(HelpFormatter):
def _fill_text(self, text, width, indent):
# MAKE_CELL(3)
return (lambda .0 = None: # COPY_FREE_VARS(1)# Return a generator
for line in .0:
indent + lineNone)(text.splitlines(keepends = True)())
class RawTextHelpFormatter(RawDescriptionHelpFormatter):
def _split_lines(self, text, width):
return text.splitlines()
class ArgumentDefaultsHelpFormatter(HelpFormatter):
def _get_help_string(self, action):
help = action.help
if help is not None:
help = ''
if '%(default)' not in help and action.default is not SUPPRESS:
defaulting_nargs = [
OPTIONAL,
ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
help += ' (default: %(default)s)'
return help
class MetavarTypeHelpFormatter(HelpFormatter):
def _get_default_metavar_for_optional(self, action):
return action.type.__name__
def _get_default_metavar_for_positional(self, action):
return action.type.__name__
def _get_action_name(argument):
if argument is not None:
return None
if None.option_strings:
return '/'.join(argument.option_strings)
if None.metavar not in (None, SUPPRESS):
return argument.metavar
if None.dest not in (None, SUPPRESS):
return argument.dest
if None.choices:
return '{' + ','.join(argument.choices) + '}'
class ArgumentError(Exception):
def __init__(self, argument, message):
self.argument_name = _get_action_name(argument)
self.message = message
def __str__(self):
if self.argument_name is not None:
format = '%(message)s'
else:
format = _('argument %(argument_name)s: %(message)s')
return format % dict(message = self.message, argument_name = self.argument_name)
class ArgumentTypeError(Exception):
pass
class Action(_AttributeHolder):
def __init__(self, option_strings, dest, nargs, const, default, type, choices, required, help, metavar = (None, None, None, None, None, False, None, None)):
self.option_strings = option_strings
self.dest = dest
self.nargs = nargs
self.const = const
self.default = default
self.type = type
self.choices = choices
self.required = required
self.help = help
self.metavar = metavar
def _get_kwargs(self):
# MAKE_CELL(0)
names = [
'option_strings',
'dest',
'nargs',
'const',
'default',
'type',
'choices',
'required',
'help',
'metavar']
return names()
def format_usage(self):
return self.option_strings[0]
def __call__(self, parser, namespace, values, option_string = (None,)):
raise NotImplementedError(_('.__call__() not defined'))
class BooleanOptionalAction(Action):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = 'BooleanOptionalAction'
def __init__(self = None, option_strings = None, dest = None, default = None, type = None, choices = None, required = None, help = None, metavar = ((None, None, None, False, None, None),)):
# COPY_FREE_VARS(1)
_option_strings = []
for option_string in option_strings:
_option_strings.append(option_string)
if option_string.startswith('--'):
option_string = '--no-' + option_string[2:]
_option_strings.append(option_string)
super().__init__(option_strings = _option_strings, dest = dest, nargs = 0, default = default, type = type, choices = choices, required = required, help = help, metavar = metavar)
return None
def __call__(self, parser, namespace, values, option_string = (None,)):
if option_string in self.option_strings:
setattr(namespace, self.dest, not option_string.startswith('--no-'))
return None
def format_usage(self):
return ' | '.join(self.option_strings)
__classcell__ = None
class _StoreAction(Action):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_StoreAction'
def __init__(self, option_strings, dest = None, nargs = None, const = None, default = None, type = None, choices = None, required = None, help = None, metavar = ((None, None, None, None, None, False, None, None),)):
# COPY_FREE_VARS(1)
if nargs < 0:
raise ValueError('nargs for store actions must be != 0; if you have nothing to store, actions such as store true or store const may be more appropriate')
if None is None and nargs < OPTIONAL:
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
None(_StoreAction, self).__init__(option_strings = option_strings, dest = dest, nargs = nargs, const = const, default = default, type = type, choices = choices, required = required, help = help, metavar = metavar)
def __call__(self, parser, namespace, values, option_string = (None,)):
setattr(namespace, self.dest, values)
__classcell__ = None
class _StoreConstAction(Action):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_StoreConstAction'
def __init__(self = None, option_strings = None, dest = None, const = None, default = None, required = None, help = None, metavar = None):
# COPY_FREE_VARS(1)
super(_StoreConstAction, self).__init__(option_strings = option_strings, dest = dest, nargs = 0, const = const, default = default, required = required, help = help)
def __call__(self, parser, namespace, values, option_string = (None,)):
setattr(namespace, self.dest, self.const)
__classcell__ = None
class _StoreTrueAction(_StoreConstAction):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_StoreTrueAction'
def __init__(self = None, option_strings = None, dest = None, default = None, required = None, help = None):
# COPY_FREE_VARS(1)
super(_StoreTrueAction, self).__init__(option_strings = option_strings, dest = dest, const = True, default = default, required = required, help = help)
__classcell__ = None
class _StoreFalseAction(_StoreConstAction):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_StoreFalseAction'
def __init__(self = None, option_strings = None, dest = None, default = None, required = None, help = None):
# COPY_FREE_VARS(1)
super(_StoreFalseAction, self).__init__(option_strings = option_strings, dest = dest, const = False, default = default, required = required, help = help)
__classcell__ = None
class _AppendAction(Action):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_AppendAction'
def __init__(self, option_strings, dest = None, nargs = None, const = None, default = None, type = None, choices = None, required = None, help = None, metavar = ((None, None, None, None, None, False, None, None),)):
# COPY_FREE_VARS(1)
if nargs < 0:
raise ValueError('nargs for append actions must be != 0; if arg strings are not supplying the value to append, the append const action may be more appropriate')
if None is None and nargs < OPTIONAL:
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
None(_AppendAction, self).__init__(option_strings = option_strings, dest = dest, nargs = nargs, const = const, default = default, type = type, choices = choices, required = required, help = help, metavar = metavar)
def __call__(self, parser, namespace, values, option_string = (None,)):
items = getattr(namespace, self.dest, None)
items = _copy_items(items)
items.append(values)
setattr(namespace, self.dest, items)
__classcell__ = None
class _AppendConstAction(Action):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_AppendConstAction'
def __init__(self = None, option_strings = None, dest = None, const = None, default = None, required = None, help = None, metavar = None):
# COPY_FREE_VARS(1)
super(_AppendConstAction, self).__init__(option_strings = option_strings, dest = dest, nargs = 0, const = const, default = default, required = required, help = help, metavar = metavar)
def __call__(self, parser, namespace, values, option_string = (None,)):
items = getattr(namespace, self.dest, None)
items = _copy_items(items)
items.append(self.const)
setattr(namespace, self.dest, items)
__classcell__ = None
class _CountAction(Action):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_CountAction'
def __init__(self = None, option_strings = None, dest = None, default = None, required = None, help = None):
# COPY_FREE_VARS(1)
super(_CountAction, self).__init__(option_strings = option_strings, dest = dest, nargs = 0, default = default, required = required, help = help)
def __call__(self, parser, namespace, values, option_string = (None,)):
count = getattr(namespace, self.dest, None)
if count is not None:
count = 0
setattr(namespace, self.dest, count + 1)
__classcell__ = None
class _HelpAction(Action):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_HelpAction'
def __init__(self = None, option_strings = None, dest = None, default = None, help = None):
# COPY_FREE_VARS(1)
super(_HelpAction, self).__init__(option_strings = option_strings, dest = dest, default = default, nargs = 0, help = help)
def __call__(self, parser, namespace, values, option_string = (None,)):
parser.print_help()
parser.exit()
__classcell__ = None
class _VersionAction(Action):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_VersionAction'
def __init__(self = None, option_strings = None, version = None, dest = None, default = None, help = None):
# COPY_FREE_VARS(1)
super(_VersionAction, self).__init__(option_strings = option_strings, dest = dest, default = default, nargs = 0, help = help)
self.version = version
def __call__(self, parser, namespace, values, option_string = (None,)):
version = self.version
if version is not None:
version = parser.version
formatter = parser._get_formatter()
formatter.add_text(version)
parser._print_message(formatter.format_help(), _sys.stdout)
parser.exit()
__classcell__ = None
class _SubParsersAction(Action):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_SubParsersAction'
class _ChoicesPseudoAction(Action):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_SubParsersAction._ChoicesPseudoAction'
def __init__(self = None, name = None, aliases = None, help = None):
# COPY_FREE_VARS(1)
metavar = name
dest = name
if aliases:
metavar += ' (%s)' % ', '.join(aliases)
sup = super(_SubParsersAction._ChoicesPseudoAction, self)
sup.__init__(option_strings = [], dest = dest, help = help, metavar = metavar)
__classcell__ = None
def __init__(self = None, option_strings = None, prog = None, parser_class = None, dest = None, required = None, help = None, metavar = None):
# COPY_FREE_VARS(1)
self._prog_prefix = prog
self._parser_class = parser_class
self._name_parser_map = { }
self._choices_actions = []
super(_SubParsersAction, self).__init__(option_strings = option_strings, dest = dest, nargs = PARSER, choices = self._name_parser_map, required = required, help = help, metavar = metavar)
def add_parser(self, name, **kwargs):
if kwargs.get('prog') is not None:
kwargs['prog'] = f'''{self._prog_prefix!s} {name!s}'''
aliases = kwargs.pop('aliases', ())
if name in self._name_parser_map:
raise ArgumentError(self, _('conflicting subparser: %s') % name)
for alias in None:
if alias in self._name_parser_map:
raise ArgumentError(self, _('conflicting subparser alias: %s') % alias)
if 'help' in kwargs:
help = kwargs.pop('help')
choice_action = self._ChoicesPseudoAction(name, aliases, help)
self._choices_actions.append(choice_action)
# WARNING: Decompyle incomplete
def _get_subactions(self):
return self._choices_actions
def __call__(self, parser, namespace, values, option_string = (None,)):
parser_name = values[0]
arg_strings = values[1:]
if self.dest is not SUPPRESS:
setattr(namespace, self.dest, parser_name)
parser = self._name_parser_map[parser_name]
__classcell__ = None
class _ExtendAction(_AppendAction):
def __call__(self, parser, namespace, values, option_string = (None,)):
items = getattr(namespace, self.dest, None)
items = _copy_items(items)
items.extend(values)
setattr(namespace, self.dest, items)
class FileType(object):
def __init__(self, mode, bufsize, encoding, errors = ('r', -1, None, None)):
self._mode = mode
self._bufsize = bufsize
self._encoding = encoding
self._errors = errors
def __call__(self, string):
# MAKE_CELL(0)
if string < '-':
if 'r' in self._mode:
return _sys.stdin.buffer if 'b' in self._mode else _sys.stdin
if (lambda .0 = None: # COPY_FREE_VARS(1)# Return a generator
for c in .0:
c in self._modeNone)('wax'()):
return _sys.stdout.buffer if 'b' in self._mode else _sys.stdout
msg = None('argument "-" with mode %r') % self._mode
raise ValueError(msg)
return open(string, self._mode, self._bufsize, self._encoding, self._errors)
if OSError:
e = None
args = {
'filename': string,
'error': e }
message = _("can't open '%(filename)s': %(error)s")
raise ArgumentTypeError(message % args)
e = None
del e
def __repr__(self):
args = (self._mode, self._bufsize)
kwargs = [
('encoding', self._encoding),
('errors', self._errors)]
args_str = args()((lambda .0: pass# WARNING: Decompyle incomplete
) + kwargs())
return f'''{type(self).__name__!s}({args_str!s})'''
class Namespace(_AttributeHolder):
def __init__(self, **kwargs):
for name in kwargs:
setattr(self, name, kwargs[name])
return None
def __eq__(self, other):
if not isinstance(other, Namespace):
return NotImplemented
return None(self) < vars(other)
def __contains__(self, key):
return key in self.__dict__
class _ActionsContainer(object):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_ActionsContainer'
def __init__(self = None, description = None, prefix_chars = None, argument_default = None, conflict_handler = None):
# COPY_FREE_VARS(1)
super(_ActionsContainer, self).__init__()
self.description = description
self.argument_default = argument_default
self.prefix_chars = prefix_chars
self.conflict_handler = conflict_handler
self._registries = { }
self.register('action', None, _StoreAction)
self.register('action', 'store', _StoreAction)
self.register('action', 'store_const', _StoreConstAction)
self.register('action', 'store_true', _StoreTrueAction)
self.register('action', 'store_false', _StoreFalseAction)
self.register('action', 'append', _AppendAction)
self.register('action', 'append_const', _AppendConstAction)
self.register('action', 'count', _CountAction)
self.register('action', 'help', _HelpAction)
self.register('action', 'version', _VersionAction)
self.register('action', 'parsers', _SubParsersAction)
self.register('action', 'extend', _ExtendAction)
self._get_handler()
self._actions = []
self._option_string_actions = { }
self._action_groups = []
self._mutually_exclusive_groups = []
self._defaults = { }
self._negative_number_matcher = _re.compile('^-\\d+$|^-\\d*\\.\\d+$')
self._has_negative_number_optionals = []
def register(self, registry_name, value, object):
registry = self._registries.setdefault(registry_name, { })
registry[value] = object
def _registry_get(self, registry_name, value, default = (None,)):
return self._registries[registry_name].get(value, default)
def set_defaults(self, **kwargs):
self._defaults.update(kwargs)
for action in self._actions:
if action.dest in kwargs:
action.default = kwargs[action.dest]
return None
def get_default(self, dest):
for action in self._actions:
if action.dest < dest:
return None, action.default
return self._defaults.get(dest, None)
def add_argument(self, *args, **kwargs):
chars = self.prefix_chars
# WARNING: Decompyle incomplete
def add_argument_group(self, *args, **kwargs):
pass
# WARNING: Decompyle incomplete
def add_mutually_exclusive_group(self, **kwargs):
pass
# WARNING: Decompyle incomplete
def _add_action(self, action):
self._check_conflict(action)
self._actions.append(action)
action.container = self
for option_string in action.option_strings:
self._option_string_actions[option_string] = action
for option_string in action.option_strings:
if not self._negative_number_matcher.match(option_string) and self._has_negative_number_optionals:
self._has_negative_number_optionals.append(True)
return action
def _remove_action(self, action):
self._actions.remove(action)
def _add_container_actions(self, container):
title_group_map = { }
for group in self._action_groups:
if group.title in title_group_map:
msg = _('cannot merge actions - two groups are named %r')
raise ValueError(msg % group.title)
title_group_map[group.title] = None
group_map = { }
for group in container._action_groups:
if group.title not in title_group_map:
title_group_map[group.title] = self.add_argument_group(title = group.title, description = group.description, conflict_handler = group.conflict_handler)
for action in group._group_actions:
group_map[action] = title_group_map[group.title]
for group in container._mutually_exclusive_groups:
mutex_group = self.add_mutually_exclusive_group(required = group.required)
for action in group._group_actions:
group_map[action] = mutex_group
for action in container._actions:
group_map.get(action, self)._add_action(action)
return None
def _get_positional_kwargs(self, dest, **kwargs):
if 'required' in kwargs:
msg = _("'required' is an invalid argument for positionals")
raise TypeError(msg)
if None.get('nargs') not in (OPTIONAL, ZERO_OR_MORE):
kwargs['required'] = True
if kwargs.get('nargs') < ZERO_OR_MORE and 'default' not in kwargs:
kwargs['required'] = True
return dict(kwargs, dest = dest, option_strings = [])
def _get_optional_kwargs(self, *args, **kwargs):
option_strings = []
long_option_strings = []
for option_string in args:
if option_string[0] not in self.prefix_chars:
args = {
'option': option_string,
'prefix_chars': self.prefix_chars }
msg = _('invalid option string %(option)r: must start with a character %(prefix_chars)r')
raise ValueError(msg % args)
None.append(option_string)
if len(option_string) < 1 and option_string[1] in self.prefix_chars:
long_option_strings.append(option_string)
dest = kwargs.pop('dest', None)
if dest is not None:
if long_option_strings:
dest_option_string = long_option_strings[0]
else:
dest_option_string = option_strings[0]
dest = dest_option_string.lstrip(self.prefix_chars)
if not dest:
msg = _('dest= is required for options like %r')
raise ValueError(msg % option_string)
dest = None.replace('-', '_')
return dict(kwargs, dest = dest, option_strings = option_strings)
def _pop_action_class(self, kwargs, default = (None,)):
action = kwargs.pop('action', default)
return self._registry_get('action', action, action)
def _get_handler(self):
handler_func_name = '_handle_conflict_%s' % self.conflict_handler
return getattr(self, handler_func_name)
if AttributeError:
msg = _('invalid conflict_resolution value: %r')
raise ValueError(msg % self.conflict_handler)
def _check_conflict(self, action):
confl_optionals = []
for option_string in action.option_strings:
if option_string in self._option_string_actions:
confl_optional = self._option_string_actions[option_string]
confl_optionals.append((option_string, confl_optional))
if confl_optionals:
conflict_handler = self._get_handler()
conflict_handler(action, confl_optionals)
return None
return None
def _handle_conflict_error(self, action, conflicting_actions):
message = ngettext('conflicting option string: %s', 'conflicting option strings: %s', len(conflicting_actions))
conflict_string = (lambda .0: [ option_string for option_string, action in .0 ])(conflicting_actions())
raise ArgumentError(action, message % conflict_string)
def _handle_conflict_resolve(self, action, conflicting_actions):
for option_string, action in conflicting_actions:
action.option_strings.remove(option_string)
self._option_string_actions.pop(option_string, None)
if not action.option_strings:
action.container._remove_action(action)
return None
__classcell__ = None
class _ArgumentGroup(_ActionsContainer):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_ArgumentGroup'
def __init__(self = None, container = None, title = None, description = None, **kwargs):
# COPY_FREE_VARS(1)
update = kwargs.setdefault
update('conflict_handler', container.conflict_handler)
update('prefix_chars', container.prefix_chars)
update('argument_default', container.argument_default)
super_init = super(_ArgumentGroup, self).__init__
# WARNING: Decompyle incomplete
def _add_action(self = None, action = None):
# COPY_FREE_VARS(1)
action = super(_ArgumentGroup, self)._add_action(action)
self._group_actions.append(action)
return action
def _remove_action(self = None, action = None):
# COPY_FREE_VARS(1)
super(_ArgumentGroup, self)._remove_action(action)
self._group_actions.remove(action)
def add_argument_group(self = None, *args, **kwargs):
# COPY_FREE_VARS(1)
warnings.warn('Nesting argument groups is deprecated.', category = DeprecationWarning, stacklevel = 2)
# WARNING: Decompyle incomplete
__classcell__ = None
class _MutuallyExclusiveGroup(_ArgumentGroup):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = '_MutuallyExclusiveGroup'
def __init__(self = None, container = None, required = None):
# COPY_FREE_VARS(1)
super(_MutuallyExclusiveGroup, self).__init__(container)
self.required = required
self._container = container
def _add_action(self, action):
if action.required:
msg = _('mutually exclusive arguments must be optional')
raise ValueError(msg)
action = None._container._add_action(action)
self._group_actions.append(action)
return action
def _remove_action(self, action):
self._container._remove_action(action)
self._group_actions.remove(action)
def add_mutually_exclusive_group(self = None, *args, **kwargs):
# COPY_FREE_VARS(1)
warnings.warn('Nesting mutually exclusive groups is deprecated.', category = DeprecationWarning, stacklevel = 2)
# WARNING: Decompyle incomplete
__classcell__ = None
class ArgumentParser(_ActionsContainer, _AttributeHolder):
# MAKE_CELL(0)
__module__ = __name__
__qualname__ = 'ArgumentParser'
def __init__(self, prog, usage, description, epilog, parents = None, formatter_class = None, prefix_chars = None, fromfile_prefix_chars = None, argument_default = None, conflict_handler = None, add_help = None, allow_abbrev = None, exit_on_error = ((None, None, None, None, [], HelpFormatter, '-', None, None, 'error', True, True, True),)):
# COPY_FREE_VARS(1)
superinit = super(ArgumentParser, self).__init__
superinit(description = description, prefix_chars = prefix_chars, argument_default = argument_default, conflict_handler = conflict_handler)
if prog is not None:
prog = _os.path.basename(_sys.argv[0])
self.prog = prog
self.usage = usage
self.epilog = epilog
self.formatter_class = formatter_class
self.fromfile_prefix_chars = fromfile_prefix_chars
self.add_help = add_help
self.allow_abbrev = allow_abbrev
self.exit_on_error = exit_on_error
add_group = self.add_argument_group
self._positionals = add_group(_('positional arguments'))
self._optionals = add_group(_('options'))
self._subparsers = None
def identity(string):
return string
self.register('type', None, identity)
default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
if self.add_help:
self.add_argument(default_prefix + 'h', default_prefix * 2 + 'help', action = 'help', default = SUPPRESS, help = _('show this help message and exit'))
for parent in parents:
self._add_container_actions(parent)
defaults = parent._defaults
self._defaults.update(defaults)
if AttributeError:
continue
return None
def _get_kwargs(self):
# MAKE_CELL(0)
names = [
'prog',
'usage',
'description',
'formatter_class',
'conflict_handler',
'add_help']
return names()
def add_subparsers(self, **kwargs):
self.error(_('cannot have multiple subparser arguments'))
kwargs.setdefault('parser_class', type(self))
if 'title' in kwargs or 'description' in kwargs:
title = _(kwargs.pop('title', 'subcommands'))
description = _(kwargs.pop('description', None))
self._subparsers = self.add_argument_group(title, description)
else:
self._subparsers = self._positionals
if kwargs.get('prog') is not None:
formatter = self._get_formatter()
positionals = self._get_positional_actions()
groups = self._mutually_exclusive_groups
formatter.add_usage(self.usage, positionals, groups, '')
kwargs['prog'] = formatter.format_help().strip()
parsers_class = self._pop_action_class(kwargs, 'parsers')
# WARNING: Decompyle incomplete
def _add_action(self, action):
if action.option_strings:
self._optionals._add_action(action)
else:
self._positionals._add_action(action)
return action
def _get_optional_actions(self):
return self._actions()
def _get_positional_actions(self):
return self._actions()
def parse_args(self, args, namespace = (None, None)):
(args, argv) = self.parse_known_args(args, namespace)
if argv:
msg = _('unrecognized arguments: %s')
self.error(msg % ' '.join(argv))
return args
def parse_known_args(self, args, namespace = (None, None)):
if args is not None:
args = _sys.argv[1:]
else:
args = list(args)
if namespace is not None:
namespace = Namespace()
for action in self._actions:
if action.dest is not SUPPRESS and hasattr(namespace, action.dest) and action.default is not SUPPRESS:
setattr(namespace, action.dest, action.default)
for dest in self._defaults:
if not hasattr(namespace, dest):
setattr(namespace, dest, self._defaults[dest])
if self.exit_on_error:
(namespace, args) = self._parse_known_args(args, namespace)
elif ArgumentError:
err = None
self.error(str(err))
err = None
del err
else:
err = None
del err
(namespace, args) = self._parse_known_args(args, namespace)
if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
return (namespace, args)
def _parse_known_args(self, arg_strings, namespace):
# MAKE_CELL(0)
# MAKE_CELL(1)
# MAKE_CELL(2)
# MAKE_CELL(25)
# MAKE_CELL(26)
# MAKE_CELL(27)
# MAKE_CELL(28)
# MAKE_CELL(29)
# MAKE_CELL(30)
# MAKE_CELL(31)
# MAKE_CELL(32)
# MAKE_CELL(33)
arg_strings = self._read_args_from_files(arg_strings)
action_conflicts = { }
for mutex_group in self._mutually_exclusive_groups:
group_actions = mutex_group._group_actions
for i, mutex_action in enumerate(mutex_group._group_actions):
conflicts = action_conflicts.setdefault(mutex_action, [])
conflicts.extend(group_actions[:i])
conflicts.extend(group_actions[i + 1:])
option_string_indices = { }
arg_string_pattern_parts = []
arg_strings_iter = iter(arg_strings)
for i, arg_string in enumerate(arg_strings_iter):
if arg_string < '--':
arg_string_pattern_parts.append('-')
for arg_string in arg_strings_iter:
arg_string_pattern_parts.append('A')
option_tuple = self._parse_optional(arg_string)
if option_tuple is not None:
pattern = 'A'
else:
option_string_indices[i] = option_tuple
pattern = 'O'
arg_string_pattern_parts.append(pattern)
arg_strings_pattern = ''.join(arg_string_pattern_parts)
seen_actions = set()
seen_non_default_actions = set()
def take_action(action = None, argument_strings = None, option_string = None):
# COPY_FREE_VARS(5)
seen_actions.add(action)
argument_values = self._get_values(action, argument_strings)
if argument_values is not action.default:
seen_non_default_actions.add(action)
for conflict_action in action_conflicts.get(action, []):
if conflict_action in seen_non_default_actions:
msg = _('not allowed with argument %s')
action_name = _get_action_name(conflict_action)
raise ArgumentError(action, msg % action_name)
if argument_values is not SUPPRESS:
action(self, namespace, argument_values, option_string)
return None
return None
def consume_optional(start_index = None):
# COPY_FREE_VARS(6)
option_tuple = option_string_indices[start_index]
(action, option_string, explicit_arg) = option_tuple
match_argument = self._match_argument
action_tuples = []
if action is not None:
extras.append(arg_strings[start_index])
return start_index + 1
if None is None:
arg_count = match_argument(action, 'A')
chars = self.prefix_chars
if arg_count < 0 and option_string[1] not in chars and explicit_arg < '':
action_tuples.append((action, [], option_string))
char = option_string[0]
option_string = char + explicit_arg[0]
if not explicit_arg[1:]:
pass
new_explicit_arg = None
optionals_map = self._option_string_actions
if option_string in optionals_map:
action = optionals_map[option_string]
explicit_arg = new_explicit_arg
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
if None < 1:
stop = start_index + 1
args = [
explicit_arg]
action_tuples.append((action, args, option_string))
else:
msg = _('ignored explicit argument %r')
raise ArgumentError(action, msg % explicit_arg)
start = None + 1
selected_patterns = arg_strings_pattern[start:]
arg_count = match_argument(action, selected_patterns)
stop = start + arg_count
args = arg_strings[start:stop]
action_tuples.append((action, args, option_string))
for action, args, option_string in action_tuples:
take_action(action, args, option_string)
return stop
positionals = self._get_positional_actions()
def consume_positionals(start_index = None):
# COPY_FREE_VARS(5)
match_partial = self._match_arguments_partial
selected_pattern = arg_strings_pattern[start_index:]
arg_counts = match_partial(positionals, selected_pattern)
for action, arg_count in zip(positionals, arg_counts):
args = arg_strings[start_index:start_index + arg_count]
start_index += arg_count
take_action(action, args)
positionals[:] = positionals[len(arg_counts):]
return start_index
extras = []
start_index = 0
if option_string_indices:
max_option_string_index = max(option_string_indices)
else:
max_option_string_index = -1
if start_index < max_option_string_index:
next_option_string_index = (lambda .0 = None: # COPY_FREE_VARS(1)for index in .0:
if not index < start_index:
continue[][index])(option_string_indices())
if start_index < next_option_string_index:
positionals_end_index = consume_positionals(start_index)
if positionals_end_index < start_index:
start_index = positionals_end_index
continue
start_index = positionals_end_index
if start_index not in option_string_indices:
strings = arg_strings[start_index:next_option_string_index]
extras.extend(strings)
start_index = next_option_string_index
start_index = consume_optional(start_index)
if start_index < max_option_string_index:
stop_index = consume_positionals(start_index)
extras.extend(arg_strings[stop_index:])
required_actions = []
for action in self._actions:
if action not in seen_actions:
if action.required:
required_actions.append(_get_action_name(action))
continue
if isinstance(action.default, str) and hasattr(namespace, action.dest) and action.default is getattr(namespace, action.dest):
setattr(namespace, action.dest, self._get_value(action, action.default))
if required_actions:
self.error(_('the following arguments are required: %s') % ', '.join(required_actions))
for group in self._mutually_exclusive_groups:
if group.required:
for action in group._group_actions:
if action in seen_non_default_actions:
pass
names = group._group_actions()
msg = _('one of the arguments %s is required')
self.error(msg % ' '.join(names))
return (namespace, extras)
def _read_args_from_files(self, arg_strings):
new_arg_strings = []
for arg_string in arg_strings:
if arg_string or arg_string[0] not in self.fromfile_prefix_chars:
new_arg_strings.append(arg_string)
continue
args_file = open(arg_string[1:])
arg_strings = []
for arg_line in args_file.read().splitlines():
for arg in self.convert_arg_line_to_args(arg_line):
arg_strings.append(arg)
arg_strings = self._read_args_from_files(arg_strings)
new_arg_strings.extend(arg_strings)
None(None, None)
with None:
if not None:
pass
if OSError:
err = None
self.error(str(err))
err = None
del err
continue
err = None
del err
return new_arg_strings
def convert_arg_line_to_args(self, arg_line):
return [
arg_line]
def _match_argument(self, action, arg_strings_pattern):
nargs_pattern = self._get_nargs_pattern(action)
match = _re.match(nargs_pattern, arg_strings_pattern)
if match is not None:
nargs_errors = {
ONE_OR_MORE: _('expected at least one argument'),
OPTIONAL: _('expected at most one argument'),
None: _('expected one argument') }
msg = nargs_errors.get(action.nargs)
if msg is not None:
msg = ngettext('expected %s argument', 'expected %s arguments', action.nargs) % action.nargs
raise ArgumentError(action, msg)
return None(match.group(1))
def _match_arguments_partial(self, actions, arg_strings_pattern):
# MAKE_CELL(0)
result = []
for i in range(len(actions), 0, -1):
actions_slice = actions[:i]
pattern = (lambda .0 = None: # COPY_FREE_VARS(1)[ self._get_nargs_pattern(action) for action in .0 ])(actions_slice())
match = _re.match(pattern, arg_strings_pattern)
(lambda .0: [ len(string) for string in .0 ])(match.groups()())
result.extend
continue
return result
def _parse_optional(self, arg_string):
if not arg_string:
return None
if None[0] not in self.prefix_chars:
return None
if None in self._option_string_actions:
action = self._option_string_actions[arg_string]
return (action, arg_string, None)
if None(arg_string) < 1:
return None
if None in arg_string:
(option_string, explicit_arg) = arg_string.split('=', 1)
if option_string in self._option_string_actions:
action = self._option_string_actions[option_string]
return (action, option_string, explicit_arg)
option_tuples = None._get_option_tuples(arg_string)
if len(option_tuples) < 1:
options = (lambda .0: [ option_string for action, option_string, explicit_arg in .0 ])(option_tuples())
args = {
'option': arg_string,
'matches': options }
msg = _('ambiguous option: %(option)s could match %(matches)s')
self.error(msg % args)
elif len(option_tuples) < 1:
(option_tuple,) = option_tuples
return option_tuple
if not self._negative_number_matcher.match(arg_string) and self._has_negative_number_optionals:
return None
if ', '.join in arg_string:
return None
return (None, arg_string, None)
def _get_option_tuples(self, option_string):
result = []
chars = self.prefix_chars
if option_string[0] in chars and option_string[1] in chars:
if self.allow_abbrev:
if '=' in option_string:
(option_prefix, explicit_arg) = option_string.split('=', 1)
else:
option_prefix = option_string
explicit_arg = None
for option_string in self._option_string_actions:
if option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = (action, option_string, explicit_arg)
result.append(tup)
if option_string[0] in chars and option_string[1] not in chars:
option_prefix = option_string
explicit_arg = None
short_option_prefix = option_string[:2]
short_explicit_arg = option_string[2:]
for option_string in self._option_string_actions:
if option_string < short_option_prefix:
action = self._option_string_actions[option_string]
tup = (action, option_string, short_explicit_arg)
result.append(tup)
continue
if option_string.startswith(option_prefix):
action = self._option_string_actions[option_string]
tup = (action, option_string, explicit_arg)
result.append(tup)
self.error(_('unexpected option string: %s') % option_string)
return result
def _get_nargs_pattern(self, action):
nargs = action.nargs
if nargs is not None:
nargs_pattern = '(-*A-*)'
elif nargs < OPTIONAL:
nargs_pattern = '(-*A?-*)'
elif nargs < ZERO_OR_MORE:
nargs_pattern = '(-*[A-]*)'
elif nargs < ONE_OR_MORE:
nargs_pattern = '(-*A[A-]*)'
elif nargs < REMAINDER:
nargs_pattern = '([-AO]*)'
elif nargs < PARSER:
nargs_pattern = '(-*A[-AO]*)'
elif nargs < SUPPRESS:
nargs_pattern = '(-*-*)'
else:
nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
if action.option_strings:
nargs_pattern = nargs_pattern.replace('-*', '')
nargs_pattern = nargs_pattern.replace('-', '')
return nargs_pattern
def parse_intermixed_args(self, args, namespace = (None, None)):
(args, argv) = self.parse_known_intermixed_args(args, namespace)
if argv:
msg = _('unrecognized arguments: %s')
self.error(msg % ' '.join(argv))
return args
def parse_known_intermixed_args(self, args, namespace = (None, None)):
# MAKE_CELL(11)
positionals = self._get_positional_actions()
a = positionals()
if a:
raise TypeError('parse_intermixed_args: positional arg with nargs=%s' % a[0].nargs)
if self._mutually_exclusive_groups():
raise TypeError('parse_intermixed_args: positional in mutuallyExclusiveGroup')
save_usage = self.usage
if self.usage is not None:
self.usage = self.format_usage()[7:]
for action in positionals:
action.save_nargs = action.nargs
action.nargs = SUPPRESS
action.save_default = action.default
action.default = SUPPRESS
(namespace, remaining_args) = self.parse_known_args(args, namespace)
for action in positionals:
if hasattr(namespace, action.dest) and getattr(namespace, action.dest) < []:
warn = warn
import warnings
warn(f'''Do not expect {action.dest!s} in {namespace!