sawine@0: # Author: Steven J. Bethard . sawine@0: sawine@0: """Command-line parsing library sawine@0: sawine@0: This module is an optparse-inspired command-line parsing library that: sawine@0: sawine@0: - handles both optional and positional arguments sawine@0: - produces highly informative usage messages sawine@0: - supports parsers that dispatch to sub-parsers sawine@0: sawine@0: The following is a simple usage example that sums integers from the sawine@0: command-line and writes the result to a file:: sawine@0: sawine@0: parser = argparse.ArgumentParser( sawine@0: description='sum the integers at the command line') sawine@0: parser.add_argument( sawine@0: 'integers', metavar='int', nargs='+', type=int, sawine@0: help='an integer to be summed') sawine@0: parser.add_argument( sawine@0: '--log', default=sys.stdout, type=argparse.FileType('w'), sawine@0: help='the file where the sum should be written') sawine@0: args = parser.parse_args() sawine@0: args.log.write('%s' % sum(args.integers)) sawine@0: args.log.close() sawine@0: sawine@0: The module contains the following public classes: sawine@0: sawine@0: - ArgumentParser -- The main entry point for command-line parsing. As the sawine@0: example above shows, the add_argument() method is used to populate sawine@0: the parser with actions for optional and positional arguments. Then sawine@0: the parse_args() method is invoked to convert the args at the sawine@0: command-line into an object with attributes. sawine@0: sawine@0: - ArgumentError -- The exception raised by ArgumentParser objects when sawine@0: there are errors with the parser's actions. Errors raised while sawine@0: parsing the command-line are caught by ArgumentParser and emitted sawine@0: as command-line messages. sawine@0: sawine@0: - FileType -- A factory for defining types of files to be created. As the sawine@0: example above shows, instances of FileType are typically passed as sawine@0: the type= argument of add_argument() calls. sawine@0: sawine@0: - Action -- The base class for parser actions. Typically actions are sawine@0: selected by passing strings like 'store_true' or 'append_const' to sawine@0: the action= argument of add_argument(). However, for greater sawine@0: customization of ArgumentParser actions, subclasses of Action may sawine@0: be defined and passed as the action= argument. sawine@0: sawine@0: - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, sawine@0: ArgumentDefaultsHelpFormatter -- Formatter classes which sawine@0: may be passed as the formatter_class= argument to the sawine@0: ArgumentParser constructor. HelpFormatter is the default, sawine@0: RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser sawine@0: not to change the formatting for help text, and sawine@0: ArgumentDefaultsHelpFormatter adds information about argument defaults sawine@0: to the help. sawine@0: sawine@0: All other classes in this module are considered implementation details. sawine@0: (Also note that HelpFormatter and RawDescriptionHelpFormatter are only sawine@0: considered public as object names -- the API of the formatter objects is sawine@0: still considered an implementation detail.) sawine@0: """ sawine@0: sawine@0: __version__ = '1.1' sawine@0: __all__ = [ sawine@0: 'ArgumentParser', sawine@0: 'ArgumentError', sawine@0: 'Namespace', sawine@0: 'Action', sawine@0: 'FileType', sawine@0: 'HelpFormatter', sawine@0: 'RawDescriptionHelpFormatter', sawine@0: 'RawTextHelpFormatter', sawine@0: 'ArgumentDefaultsHelpFormatter', sawine@0: ] sawine@0: sawine@0: sawine@0: import copy as _copy sawine@0: import os as _os sawine@0: import re as _re sawine@0: import sys as _sys sawine@0: import textwrap as _textwrap sawine@0: sawine@0: from gettext import gettext as _ sawine@0: sawine@0: sawine@0: def _callable(obj): sawine@0: return hasattr(obj, '__call__') or hasattr(obj, '__bases__') sawine@0: sawine@0: sawine@0: SUPPRESS = '==SUPPRESS==' sawine@0: sawine@0: OPTIONAL = '?' sawine@0: ZERO_OR_MORE = '*' sawine@0: ONE_OR_MORE = '+' sawine@0: PARSER = 'A...' sawine@0: REMAINDER = '...' sawine@0: sawine@0: # ============================= sawine@0: # Utility functions and classes sawine@0: # ============================= sawine@0: sawine@0: class _AttributeHolder(object): sawine@0: """Abstract base class that provides __repr__. sawine@0: sawine@0: The __repr__ method returns a string in the format:: sawine@0: ClassName(attr=name, attr=name, ...) sawine@0: The attributes are determined either by a class-level attribute, sawine@0: '_kwarg_names', or by inspecting the instance __dict__. sawine@0: """ sawine@0: sawine@0: def __repr__(self): sawine@0: type_name = type(self).__name__ sawine@0: arg_strings = [] sawine@0: for arg in self._get_args(): sawine@0: arg_strings.append(repr(arg)) sawine@0: for name, value in self._get_kwargs(): sawine@0: arg_strings.append('%s=%r' % (name, value)) sawine@0: return '%s(%s)' % (type_name, ', '.join(arg_strings)) sawine@0: sawine@0: def _get_kwargs(self): sawine@0: return sorted(self.__dict__.items()) sawine@0: sawine@0: def _get_args(self): sawine@0: return [] sawine@0: sawine@0: sawine@0: def _ensure_value(namespace, name, value): sawine@0: if getattr(namespace, name, None) is None: sawine@0: setattr(namespace, name, value) sawine@0: return getattr(namespace, name) sawine@0: sawine@0: sawine@0: # =============== sawine@0: # Formatting Help sawine@0: # =============== sawine@0: sawine@0: class HelpFormatter(object): sawine@0: """Formatter for generating usage messages and argument help strings. sawine@0: sawine@0: Only the name of this class is considered a public API. All the methods sawine@0: provided by the class are considered an implementation detail. sawine@0: """ sawine@0: sawine@0: def __init__(self, sawine@0: prog, sawine@0: indent_increment=2, sawine@0: max_help_position=24, sawine@0: width=None): sawine@0: sawine@0: # default setting for width sawine@0: if width is None: sawine@0: try: sawine@0: width = int(_os.environ['COLUMNS']) sawine@0: except (KeyError, ValueError): sawine@0: width = 80 sawine@0: width -= 2 sawine@0: sawine@0: self._prog = prog sawine@0: self._indent_increment = indent_increment sawine@0: self._max_help_position = max_help_position sawine@0: self._width = width sawine@0: sawine@0: self._current_indent = 0 sawine@0: self._level = 0 sawine@0: self._action_max_length = 0 sawine@0: sawine@0: self._root_section = self._Section(self, None) sawine@0: self._current_section = self._root_section sawine@0: sawine@0: self._whitespace_matcher = _re.compile(r'\s+') sawine@0: self._long_break_matcher = _re.compile(r'\n\n\n+') sawine@0: sawine@0: # =============================== sawine@0: # Section and indentation methods sawine@0: # =============================== sawine@0: def _indent(self): sawine@0: self._current_indent += self._indent_increment sawine@0: self._level += 1 sawine@0: sawine@0: def _dedent(self): sawine@0: self._current_indent -= self._indent_increment sawine@0: assert self._current_indent >= 0, 'Indent decreased below 0.' sawine@0: self._level -= 1 sawine@0: sawine@0: class _Section(object): sawine@0: sawine@0: def __init__(self, formatter, parent, heading=None): sawine@0: self.formatter = formatter sawine@0: self.parent = parent sawine@0: self.heading = heading sawine@0: self.items = [] sawine@0: sawine@0: def format_help(self): sawine@0: # format the indented section sawine@0: if self.parent is not None: sawine@0: self.formatter._indent() sawine@0: join = self.formatter._join_parts sawine@0: for func, args in self.items: sawine@0: func(*args) sawine@0: item_help = join([func(*args) for func, args in self.items]) sawine@0: if self.parent is not None: sawine@0: self.formatter._dedent() sawine@0: sawine@0: # return nothing if the section was empty sawine@0: if not item_help: sawine@0: return '' sawine@0: sawine@0: # add the heading if the section was non-empty sawine@0: if self.heading is not SUPPRESS and self.heading is not None: sawine@0: current_indent = self.formatter._current_indent sawine@0: heading = '%*s%s:\n' % (current_indent, '', self.heading) sawine@0: else: sawine@0: heading = '' sawine@0: sawine@0: # join the section-initial newline, the heading and the help sawine@0: return join(['\n', heading, item_help, '\n']) sawine@0: sawine@0: def _add_item(self, func, args): sawine@0: self._current_section.items.append((func, args)) sawine@0: sawine@0: # ======================== sawine@0: # Message building methods sawine@0: # ======================== sawine@0: def start_section(self, heading): sawine@0: self._indent() sawine@0: section = self._Section(self, self._current_section, heading) sawine@0: self._add_item(section.format_help, []) sawine@0: self._current_section = section sawine@0: sawine@0: def end_section(self): sawine@0: self._current_section = self._current_section.parent sawine@0: self._dedent() sawine@0: sawine@0: def add_text(self, text): sawine@0: if text is not SUPPRESS and text is not None: sawine@0: self._add_item(self._format_text, [text]) sawine@0: sawine@0: def add_usage(self, usage, actions, groups, prefix=None): sawine@0: if usage is not SUPPRESS: sawine@0: args = usage, actions, groups, prefix sawine@0: self._add_item(self._format_usage, args) sawine@0: sawine@0: def add_argument(self, action): sawine@0: if action.help is not SUPPRESS: sawine@0: sawine@0: # find all invocations sawine@0: get_invocation = self._format_action_invocation sawine@0: invocations = [get_invocation(action)] sawine@0: for subaction in self._iter_indented_subactions(action): sawine@0: invocations.append(get_invocation(subaction)) sawine@0: sawine@0: # update the maximum item length sawine@0: invocation_length = max([len(s) for s in invocations]) sawine@0: action_length = invocation_length + self._current_indent sawine@0: self._action_max_length = max(self._action_max_length, sawine@0: action_length) sawine@0: sawine@0: # add the item to the list sawine@0: self._add_item(self._format_action, [action]) sawine@0: sawine@0: def add_arguments(self, actions): sawine@0: for action in actions: sawine@0: self.add_argument(action) sawine@0: sawine@0: # ======================= sawine@0: # Help-formatting methods sawine@0: # ======================= sawine@0: def format_help(self): sawine@0: help = self._root_section.format_help() sawine@0: if help: sawine@0: help = self._long_break_matcher.sub('\n\n', help) sawine@0: help = help.strip('\n') + '\n' sawine@0: return help sawine@0: sawine@0: def _join_parts(self, part_strings): sawine@0: return ''.join([part sawine@0: for part in part_strings sawine@0: if part and part is not SUPPRESS]) sawine@0: sawine@0: def _format_usage(self, usage, actions, groups, prefix): sawine@0: if prefix is None: sawine@0: prefix = _('usage: ') sawine@0: sawine@0: # if usage is specified, use that sawine@0: if usage is not None: sawine@0: usage = usage % dict(prog=self._prog) sawine@0: sawine@0: # if no optionals or positionals are available, usage is just prog sawine@0: elif usage is None and not actions: sawine@0: usage = '%(prog)s' % dict(prog=self._prog) sawine@0: sawine@0: # if optionals and positionals are available, calculate usage sawine@0: elif usage is None: sawine@0: prog = '%(prog)s' % dict(prog=self._prog) sawine@0: sawine@0: # split optionals from positionals sawine@0: optionals = [] sawine@0: positionals = [] sawine@0: for action in actions: sawine@0: if action.option_strings: sawine@0: optionals.append(action) sawine@0: else: sawine@0: positionals.append(action) sawine@0: sawine@0: # build full usage string sawine@0: format = self._format_actions_usage sawine@0: action_usage = format(optionals + positionals, groups) sawine@0: usage = ' '.join([s for s in [prog, action_usage] if s]) sawine@0: sawine@0: # wrap the usage parts if it's too long sawine@0: text_width = self._width - self._current_indent sawine@0: if len(prefix) + len(usage) > text_width: sawine@0: sawine@0: # break usage into wrappable parts sawine@0: part_regexp = r'\(.*?\)+|\[.*?\]+|\S+' sawine@0: opt_usage = format(optionals, groups) sawine@0: pos_usage = format(positionals, groups) sawine@0: opt_parts = _re.findall(part_regexp, opt_usage) sawine@0: pos_parts = _re.findall(part_regexp, pos_usage) sawine@0: assert ' '.join(opt_parts) == opt_usage sawine@0: assert ' '.join(pos_parts) == pos_usage sawine@0: sawine@0: # helper for wrapping lines sawine@0: def get_lines(parts, indent, prefix=None): sawine@0: lines = [] sawine@0: line = [] sawine@0: if prefix is not None: sawine@0: line_len = len(prefix) - 1 sawine@0: else: sawine@0: line_len = len(indent) - 1 sawine@0: for part in parts: sawine@0: if line_len + 1 + len(part) > text_width: sawine@0: lines.append(indent + ' '.join(line)) sawine@0: line = [] sawine@0: line_len = len(indent) - 1 sawine@0: line.append(part) sawine@0: line_len += len(part) + 1 sawine@0: if line: sawine@0: lines.append(indent + ' '.join(line)) sawine@0: if prefix is not None: sawine@0: lines[0] = lines[0][len(indent):] sawine@0: return lines sawine@0: sawine@0: # if prog is short, follow it with optionals or positionals sawine@0: if len(prefix) + len(prog) <= 0.75 * text_width: sawine@0: indent = ' ' * (len(prefix) + len(prog) + 1) sawine@0: if opt_parts: sawine@0: lines = get_lines([prog] + opt_parts, indent, prefix) sawine@0: lines.extend(get_lines(pos_parts, indent)) sawine@0: elif pos_parts: sawine@0: lines = get_lines([prog] + pos_parts, indent, prefix) sawine@0: else: sawine@0: lines = [prog] sawine@0: sawine@0: # if prog is long, put it on its own line sawine@0: else: sawine@0: indent = ' ' * len(prefix) sawine@0: parts = opt_parts + pos_parts sawine@0: lines = get_lines(parts, indent) sawine@0: if len(lines) > 1: sawine@0: lines = [] sawine@0: lines.extend(get_lines(opt_parts, indent)) sawine@0: lines.extend(get_lines(pos_parts, indent)) sawine@0: lines = [prog] + lines sawine@0: sawine@0: # join lines into usage sawine@0: usage = '\n'.join(lines) sawine@0: sawine@0: # prefix with 'usage:' sawine@0: return '%s%s\n\n' % (prefix, usage) sawine@0: sawine@0: def _format_actions_usage(self, actions, groups): sawine@0: # find group indices and identify actions in groups sawine@0: group_actions = set() sawine@0: inserts = {} sawine@0: for group in groups: sawine@0: try: sawine@0: start = actions.index(group._group_actions[0]) sawine@0: except ValueError: sawine@0: continue sawine@0: else: sawine@0: end = start + len(group._group_actions) sawine@0: if actions[start:end] == group._group_actions: sawine@0: for action in group._group_actions: sawine@0: group_actions.add(action) sawine@0: if not group.required: sawine@0: inserts[start] = '[' sawine@0: inserts[end] = ']' sawine@0: else: sawine@0: inserts[start] = '(' sawine@0: inserts[end] = ')' sawine@0: for i in range(start + 1, end): sawine@0: inserts[i] = '|' sawine@0: sawine@0: # collect all actions format strings sawine@0: parts = [] sawine@0: for i, action in enumerate(actions): sawine@0: sawine@0: # suppressed arguments are marked with None sawine@0: # remove | separators for suppressed arguments sawine@0: if action.help is SUPPRESS: sawine@0: parts.append(None) sawine@0: if inserts.get(i) == '|': sawine@0: inserts.pop(i) sawine@0: elif inserts.get(i + 1) == '|': sawine@0: inserts.pop(i + 1) sawine@0: sawine@0: # produce all arg strings sawine@0: elif not action.option_strings: sawine@0: part = self._format_args(action, action.dest) sawine@0: sawine@0: # if it's in a group, strip the outer [] sawine@0: if action in group_actions: sawine@0: if part[0] == '[' and part[-1] == ']': sawine@0: part = part[1:-1] sawine@0: sawine@0: # add the action string to the list sawine@0: parts.append(part) sawine@0: sawine@0: # produce the first way to invoke the option in brackets sawine@0: else: sawine@0: option_string = action.option_strings[0] sawine@0: sawine@0: # if the Optional doesn't take a value, format is: sawine@0: # -s or --long sawine@0: if action.nargs == 0: sawine@0: part = '%s' % option_string sawine@0: sawine@0: # if the Optional takes a value, format is: sawine@0: # -s ARGS or --long ARGS sawine@0: else: sawine@0: default = action.dest.upper() sawine@0: args_string = self._format_args(action, default) sawine@0: part = '%s %s' % (option_string, args_string) sawine@0: sawine@0: # make it look optional if it's not required or in a group sawine@0: if not action.required and action not in group_actions: sawine@0: part = '[%s]' % part sawine@0: sawine@0: # add the action string to the list sawine@0: parts.append(part) sawine@0: sawine@0: # insert things at the necessary indices sawine@0: for i in sorted(inserts, reverse=True): sawine@0: parts[i:i] = [inserts[i]] sawine@0: sawine@0: # join all the action items with spaces sawine@0: text = ' '.join([item for item in parts if item is not None]) sawine@0: sawine@0: # clean up separators for mutually exclusive groups sawine@0: open = r'[\[(]' sawine@0: close = r'[\])]' sawine@0: text = _re.sub(r'(%s) ' % open, r'\1', text) sawine@0: text = _re.sub(r' (%s)' % close, r'\1', text) sawine@0: text = _re.sub(r'%s *%s' % (open, close), r'', text) sawine@0: text = _re.sub(r'\(([^|]*)\)', r'\1', text) sawine@0: text = text.strip() sawine@0: sawine@0: # return the text sawine@0: return text sawine@0: sawine@0: def _format_text(self, text): sawine@0: if '%(prog)' in text: sawine@0: text = text % dict(prog=self._prog) sawine@0: text_width = self._width - self._current_indent sawine@0: indent = ' ' * self._current_indent sawine@0: return self._fill_text(text, text_width, indent) + '\n\n' sawine@0: sawine@0: def _format_action(self, action): sawine@0: # determine the required width and the entry label sawine@0: help_position = min(self._action_max_length + 2, sawine@0: self._max_help_position) sawine@0: help_width = self._width - help_position sawine@0: action_width = help_position - self._current_indent - 2 sawine@0: action_header = self._format_action_invocation(action) sawine@0: sawine@0: # ho nelp; start on same line and add a final newline sawine@0: if not action.help: sawine@0: tup = self._current_indent, '', action_header sawine@0: action_header = '%*s%s\n' % tup sawine@0: sawine@0: # short action name; start on the same line and pad two spaces sawine@0: elif len(action_header) <= action_width: sawine@0: tup = self._current_indent, '', action_width, action_header sawine@0: action_header = '%*s%-*s ' % tup sawine@0: indent_first = 0 sawine@0: sawine@0: # long action name; start on the next line sawine@0: else: sawine@0: tup = self._current_indent, '', action_header sawine@0: action_header = '%*s%s\n' % tup sawine@0: indent_first = help_position sawine@0: sawine@0: # collect the pieces of the action help sawine@0: parts = [action_header] sawine@0: sawine@0: # if there was help for the action, add lines of help text sawine@0: if action.help: sawine@0: help_text = self._expand_help(action) sawine@0: help_lines = self._split_lines(help_text, help_width) sawine@0: parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) sawine@0: for line in help_lines[1:]: sawine@0: parts.append('%*s%s\n' % (help_position, '', line)) sawine@0: sawine@0: # or add a newline if the description doesn't end with one sawine@0: elif not action_header.endswith('\n'): sawine@0: parts.append('\n') sawine@0: sawine@0: # if there are any sub-actions, add their help as well sawine@0: for subaction in self._iter_indented_subactions(action): sawine@0: parts.append(self._format_action(subaction)) sawine@0: sawine@0: # return a single string sawine@0: return self._join_parts(parts) sawine@0: sawine@0: def _format_action_invocation(self, action): sawine@0: if not action.option_strings: sawine@0: metavar, = self._metavar_formatter(action, action.dest)(1) sawine@0: return metavar sawine@0: sawine@0: else: sawine@0: parts = [] sawine@0: sawine@0: # if the Optional doesn't take a value, format is: sawine@0: # -s, --long sawine@0: if action.nargs == 0: sawine@0: parts.extend(action.option_strings) sawine@0: sawine@0: # if the Optional takes a value, format is: sawine@0: # -s ARGS, --long ARGS sawine@0: else: sawine@0: default = action.dest.upper() sawine@0: args_string = self._format_args(action, default) sawine@0: for option_string in action.option_strings: sawine@0: parts.append('%s %s' % (option_string, args_string)) sawine@0: sawine@0: return ', '.join(parts) sawine@0: sawine@0: def _metavar_formatter(self, action, default_metavar): sawine@0: if action.metavar is not None: sawine@0: result = action.metavar sawine@0: elif action.choices is not None: sawine@0: choice_strs = [str(choice) for choice in action.choices] sawine@0: result = '{%s}' % ','.join(choice_strs) sawine@0: else: sawine@0: result = default_metavar sawine@0: sawine@0: def format(tuple_size): sawine@0: if isinstance(result, tuple): sawine@0: return result sawine@0: else: sawine@0: return (result, ) * tuple_size sawine@0: return format sawine@0: sawine@0: def _format_args(self, action, default_metavar): sawine@0: get_metavar = self._metavar_formatter(action, default_metavar) sawine@0: if action.nargs is None: sawine@0: result = '%s' % get_metavar(1) sawine@0: elif action.nargs == OPTIONAL: sawine@0: result = '[%s]' % get_metavar(1) sawine@0: elif action.nargs == ZERO_OR_MORE: sawine@0: result = '[%s [%s ...]]' % get_metavar(2) sawine@0: elif action.nargs == ONE_OR_MORE: sawine@0: result = '%s [%s ...]' % get_metavar(2) sawine@0: elif action.nargs == REMAINDER: sawine@0: result = '...' sawine@0: elif action.nargs == PARSER: sawine@0: result = '%s ...' % get_metavar(1) sawine@0: else: sawine@0: formats = ['%s' for _ in range(action.nargs)] sawine@0: result = ' '.join(formats) % get_metavar(action.nargs) sawine@0: return result sawine@0: sawine@0: def _expand_help(self, action): sawine@0: params = dict(vars(action), prog=self._prog) sawine@0: for name in list(params): sawine@0: if params[name] is SUPPRESS: sawine@0: del params[name] sawine@0: for name in list(params): sawine@0: if hasattr(params[name], '__name__'): sawine@0: params[name] = params[name].__name__ sawine@0: if params.get('choices') is not None: sawine@0: choices_str = ', '.join([str(c) for c in params['choices']]) sawine@0: params['choices'] = choices_str sawine@0: return self._get_help_string(action) % params sawine@0: sawine@0: def _iter_indented_subactions(self, action): sawine@0: try: sawine@0: get_subactions = action._get_subactions sawine@0: except AttributeError: sawine@0: pass sawine@0: else: sawine@0: self._indent() sawine@0: for subaction in get_subactions(): sawine@0: yield subaction sawine@0: self._dedent() sawine@0: sawine@0: def _split_lines(self, text, width): sawine@0: text = self._whitespace_matcher.sub(' ', text).strip() sawine@0: return _textwrap.wrap(text, width) sawine@0: sawine@0: def _fill_text(self, text, width, indent): sawine@0: text = self._whitespace_matcher.sub(' ', text).strip() sawine@0: return _textwrap.fill(text, width, initial_indent=indent, sawine@0: subsequent_indent=indent) sawine@0: sawine@0: def _get_help_string(self, action): sawine@0: return action.help sawine@0: sawine@0: sawine@0: class RawDescriptionHelpFormatter(HelpFormatter): sawine@0: """Help message formatter which retains any formatting in descriptions. sawine@0: sawine@0: Only the name of this class is considered a public API. All the methods sawine@0: provided by the class are considered an implementation detail. sawine@0: """ sawine@0: sawine@0: def _fill_text(self, text, width, indent): sawine@0: return ''.join([indent + line for line in text.splitlines(True)]) sawine@0: sawine@0: sawine@0: class RawTextHelpFormatter(RawDescriptionHelpFormatter): sawine@0: """Help message formatter which retains formatting of all help text. sawine@0: sawine@0: Only the name of this class is considered a public API. All the methods sawine@0: provided by the class are considered an implementation detail. sawine@0: """ sawine@0: sawine@0: def _split_lines(self, text, width): sawine@0: return text.splitlines() sawine@0: sawine@0: sawine@0: class ArgumentDefaultsHelpFormatter(HelpFormatter): sawine@0: """Help message formatter which adds default values to argument help. sawine@0: sawine@0: Only the name of this class is considered a public API. All the methods sawine@0: provided by the class are considered an implementation detail. sawine@0: """ sawine@0: sawine@0: def _get_help_string(self, action): sawine@0: help = action.help sawine@0: if '%(default)' not in action.help: sawine@0: if action.default is not SUPPRESS: sawine@0: defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] sawine@0: if action.option_strings or action.nargs in defaulting_nargs: sawine@0: help += ' (default: %(default)s)' sawine@0: return help sawine@0: sawine@0: sawine@0: # ===================== sawine@0: # Options and Arguments sawine@0: # ===================== sawine@0: sawine@0: def _get_action_name(argument): sawine@0: if argument is None: sawine@0: return None sawine@0: elif argument.option_strings: sawine@0: return '/'.join(argument.option_strings) sawine@0: elif argument.metavar not in (None, SUPPRESS): sawine@0: return argument.metavar sawine@0: elif argument.dest not in (None, SUPPRESS): sawine@0: return argument.dest sawine@0: else: sawine@0: return None sawine@0: sawine@0: sawine@0: class ArgumentError(Exception): sawine@0: """An error from creating or using an argument (optional or positional). sawine@0: sawine@0: The string value of this exception is the message, augmented with sawine@0: information about the argument that caused it. sawine@0: """ sawine@0: sawine@0: def __init__(self, argument, message): sawine@0: self.argument_name = _get_action_name(argument) sawine@0: self.message = message sawine@0: sawine@0: def __str__(self): sawine@0: if self.argument_name is None: sawine@0: format = '%(message)s' sawine@0: else: sawine@0: format = 'argument %(argument_name)s: %(message)s' sawine@0: return format % dict(message=self.message, sawine@0: argument_name=self.argument_name) sawine@0: sawine@0: sawine@0: class ArgumentTypeError(Exception): sawine@0: """An error from trying to convert a command line string to a type.""" sawine@0: pass sawine@0: sawine@0: sawine@0: # ============== sawine@0: # Action classes sawine@0: # ============== sawine@0: sawine@0: class Action(_AttributeHolder): sawine@0: """Information about how to convert command line strings to Python objects. sawine@0: sawine@0: Action objects are used by an ArgumentParser to represent the information sawine@0: needed to parse a single argument from one or more strings from the sawine@0: command line. The keyword arguments to the Action constructor are also sawine@0: all attributes of Action instances. sawine@0: sawine@0: Keyword Arguments: sawine@0: sawine@0: - option_strings -- A list of command-line option strings which sawine@0: should be associated with this action. sawine@0: sawine@0: - dest -- The name of the attribute to hold the created object(s) sawine@0: sawine@0: - nargs -- The number of command-line arguments that should be sawine@0: consumed. By default, one argument will be consumed and a single sawine@0: value will be produced. Other values include: sawine@0: - N (an integer) consumes N arguments (and produces a list) sawine@0: - '?' consumes zero or one arguments sawine@0: - '*' consumes zero or more arguments (and produces a list) sawine@0: - '+' consumes one or more arguments (and produces a list) sawine@0: Note that the difference between the default and nargs=1 is that sawine@0: with the default, a single value will be produced, while with sawine@0: nargs=1, a list containing a single value will be produced. sawine@0: sawine@0: - const -- The value to be produced if the option is specified and the sawine@0: option uses an action that takes no values. sawine@0: sawine@0: - default -- The value to be produced if the option is not specified. sawine@0: sawine@0: - type -- The type which the command-line arguments should be converted sawine@0: to, should be one of 'string', 'int', 'float', 'complex' or a sawine@0: callable object that accepts a single string argument. If None, sawine@0: 'string' is assumed. sawine@0: sawine@0: - choices -- A container of values that should be allowed. If not None, sawine@0: after a command-line argument has been converted to the appropriate sawine@0: type, an exception will be raised if it is not a member of this sawine@0: collection. sawine@0: sawine@0: - required -- True if the action must always be specified at the sawine@0: command line. This is only meaningful for optional command-line sawine@0: arguments. sawine@0: sawine@0: - help -- The help string describing the argument. sawine@0: sawine@0: - metavar -- The name to be used for the option's argument with the sawine@0: help string. If None, the 'dest' value will be used as the name. sawine@0: """ sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: dest, sawine@0: nargs=None, sawine@0: const=None, sawine@0: default=None, sawine@0: type=None, sawine@0: choices=None, sawine@0: required=False, sawine@0: help=None, sawine@0: metavar=None): sawine@0: self.option_strings = option_strings sawine@0: self.dest = dest sawine@0: self.nargs = nargs sawine@0: self.const = const sawine@0: self.default = default sawine@0: self.type = type sawine@0: self.choices = choices sawine@0: self.required = required sawine@0: self.help = help sawine@0: self.metavar = metavar sawine@0: sawine@0: def _get_kwargs(self): sawine@0: names = [ sawine@0: 'option_strings', sawine@0: 'dest', sawine@0: 'nargs', sawine@0: 'const', sawine@0: 'default', sawine@0: 'type', sawine@0: 'choices', sawine@0: 'help', sawine@0: 'metavar', sawine@0: ] sawine@0: return [(name, getattr(self, name)) for name in names] sawine@0: sawine@0: def __call__(self, parser, namespace, values, option_string=None): sawine@0: raise NotImplementedError(_('.__call__() not defined')) sawine@0: sawine@0: sawine@0: class _StoreAction(Action): sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: dest, sawine@0: nargs=None, sawine@0: const=None, sawine@0: default=None, sawine@0: type=None, sawine@0: choices=None, sawine@0: required=False, sawine@0: help=None, sawine@0: metavar=None): sawine@0: if nargs == 0: sawine@0: raise ValueError('nargs for store actions must be > 0; if you ' sawine@0: 'have nothing to store, actions such as store ' sawine@0: 'true or store const may be more appropriate') sawine@0: if const is not None and nargs != OPTIONAL: sawine@0: raise ValueError('nargs must be %r to supply const' % OPTIONAL) sawine@0: super(_StoreAction, self).__init__( sawine@0: option_strings=option_strings, sawine@0: dest=dest, sawine@0: nargs=nargs, sawine@0: const=const, sawine@0: default=default, sawine@0: type=type, sawine@0: choices=choices, sawine@0: required=required, sawine@0: help=help, sawine@0: metavar=metavar) sawine@0: sawine@0: def __call__(self, parser, namespace, values, option_string=None): sawine@0: setattr(namespace, self.dest, values) sawine@0: sawine@0: sawine@0: class _StoreConstAction(Action): sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: dest, sawine@0: const, sawine@0: default=None, sawine@0: required=False, sawine@0: help=None, sawine@0: metavar=None): sawine@0: super(_StoreConstAction, self).__init__( sawine@0: option_strings=option_strings, sawine@0: dest=dest, sawine@0: nargs=0, sawine@0: const=const, sawine@0: default=default, sawine@0: required=required, sawine@0: help=help) sawine@0: sawine@0: def __call__(self, parser, namespace, values, option_string=None): sawine@0: setattr(namespace, self.dest, self.const) sawine@0: sawine@0: sawine@0: class _StoreTrueAction(_StoreConstAction): sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: dest, sawine@0: default=False, sawine@0: required=False, sawine@0: help=None): sawine@0: super(_StoreTrueAction, self).__init__( sawine@0: option_strings=option_strings, sawine@0: dest=dest, sawine@0: const=True, sawine@0: default=default, sawine@0: required=required, sawine@0: help=help) sawine@0: sawine@0: sawine@0: class _StoreFalseAction(_StoreConstAction): sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: dest, sawine@0: default=True, sawine@0: required=False, sawine@0: help=None): sawine@0: super(_StoreFalseAction, self).__init__( sawine@0: option_strings=option_strings, sawine@0: dest=dest, sawine@0: const=False, sawine@0: default=default, sawine@0: required=required, sawine@0: help=help) sawine@0: sawine@0: sawine@0: class _AppendAction(Action): sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: dest, sawine@0: nargs=None, sawine@0: const=None, sawine@0: default=None, sawine@0: type=None, sawine@0: choices=None, sawine@0: required=False, sawine@0: help=None, sawine@0: metavar=None): sawine@0: if nargs == 0: sawine@0: raise ValueError('nargs for append actions must be > 0; if arg ' sawine@0: 'strings are not supplying the value to append, ' sawine@0: 'the append const action may be more appropriate') sawine@0: if const is not None and nargs != OPTIONAL: sawine@0: raise ValueError('nargs must be %r to supply const' % OPTIONAL) sawine@0: super(_AppendAction, self).__init__( sawine@0: option_strings=option_strings, sawine@0: dest=dest, sawine@0: nargs=nargs, sawine@0: const=const, sawine@0: default=default, sawine@0: type=type, sawine@0: choices=choices, sawine@0: required=required, sawine@0: help=help, sawine@0: metavar=metavar) sawine@0: sawine@0: def __call__(self, parser, namespace, values, option_string=None): sawine@0: items = _copy.copy(_ensure_value(namespace, self.dest, [])) sawine@0: items.append(values) sawine@0: setattr(namespace, self.dest, items) sawine@0: sawine@0: sawine@0: class _AppendConstAction(Action): sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: dest, sawine@0: const, sawine@0: default=None, sawine@0: required=False, sawine@0: help=None, sawine@0: metavar=None): sawine@0: super(_AppendConstAction, self).__init__( sawine@0: option_strings=option_strings, sawine@0: dest=dest, sawine@0: nargs=0, sawine@0: const=const, sawine@0: default=default, sawine@0: required=required, sawine@0: help=help, sawine@0: metavar=metavar) sawine@0: sawine@0: def __call__(self, parser, namespace, values, option_string=None): sawine@0: items = _copy.copy(_ensure_value(namespace, self.dest, [])) sawine@0: items.append(self.const) sawine@0: setattr(namespace, self.dest, items) sawine@0: sawine@0: sawine@0: class _CountAction(Action): sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: dest, sawine@0: default=None, sawine@0: required=False, sawine@0: help=None): sawine@0: super(_CountAction, self).__init__( sawine@0: option_strings=option_strings, sawine@0: dest=dest, sawine@0: nargs=0, sawine@0: default=default, sawine@0: required=required, sawine@0: help=help) sawine@0: sawine@0: def __call__(self, parser, namespace, values, option_string=None): sawine@0: new_count = _ensure_value(namespace, self.dest, 0) + 1 sawine@0: setattr(namespace, self.dest, new_count) sawine@0: sawine@0: sawine@0: class _HelpAction(Action): sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: dest=SUPPRESS, sawine@0: default=SUPPRESS, sawine@0: help=None): sawine@0: super(_HelpAction, self).__init__( sawine@0: option_strings=option_strings, sawine@0: dest=dest, sawine@0: default=default, sawine@0: nargs=0, sawine@0: help=help) sawine@0: sawine@0: def __call__(self, parser, namespace, values, option_string=None): sawine@0: parser.print_help() sawine@0: parser.exit() sawine@0: sawine@0: sawine@0: class _VersionAction(Action): sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: version=None, sawine@0: dest=SUPPRESS, sawine@0: default=SUPPRESS, sawine@0: help="show program's version number and exit"): sawine@0: super(_VersionAction, self).__init__( sawine@0: option_strings=option_strings, sawine@0: dest=dest, sawine@0: default=default, sawine@0: nargs=0, sawine@0: help=help) sawine@0: self.version = version sawine@0: sawine@0: def __call__(self, parser, namespace, values, option_string=None): sawine@0: version = self.version sawine@0: if version is None: sawine@0: version = parser.version sawine@0: formatter = parser._get_formatter() sawine@0: formatter.add_text(version) sawine@0: parser.exit(message=formatter.format_help()) sawine@0: sawine@0: sawine@0: class _SubParsersAction(Action): sawine@0: sawine@0: class _ChoicesPseudoAction(Action): sawine@0: sawine@0: def __init__(self, name, help): sawine@0: sup = super(_SubParsersAction._ChoicesPseudoAction, self) sawine@0: sup.__init__(option_strings=[], dest=name, help=help) sawine@0: sawine@0: def __init__(self, sawine@0: option_strings, sawine@0: prog, sawine@0: parser_class, sawine@0: dest=SUPPRESS, sawine@0: help=None, sawine@0: metavar=None): sawine@0: sawine@0: self._prog_prefix = prog sawine@0: self._parser_class = parser_class sawine@0: self._name_parser_map = {} sawine@0: self._choices_actions = [] sawine@0: sawine@0: super(_SubParsersAction, self).__init__( sawine@0: option_strings=option_strings, sawine@0: dest=dest, sawine@0: nargs=PARSER, sawine@0: choices=self._name_parser_map, sawine@0: help=help, sawine@0: metavar=metavar) sawine@0: sawine@0: def add_parser(self, name, **kwargs): sawine@0: # set prog from the existing prefix sawine@0: if kwargs.get('prog') is None: sawine@0: kwargs['prog'] = '%s %s' % (self._prog_prefix, name) sawine@0: sawine@0: # create a pseudo-action to hold the choice help sawine@0: if 'help' in kwargs: sawine@0: help = kwargs.pop('help') sawine@0: choice_action = self._ChoicesPseudoAction(name, help) sawine@0: self._choices_actions.append(choice_action) sawine@0: sawine@0: # create the parser and add it to the map sawine@0: parser = self._parser_class(**kwargs) sawine@0: self._name_parser_map[name] = parser sawine@0: return parser sawine@0: sawine@0: def _get_subactions(self): sawine@0: return self._choices_actions sawine@0: sawine@0: def __call__(self, parser, namespace, values, option_string=None): sawine@0: parser_name = values[0] sawine@0: arg_strings = values[1:] sawine@0: sawine@0: # set the parser name if requested sawine@0: if self.dest is not SUPPRESS: sawine@0: setattr(namespace, self.dest, parser_name) sawine@0: sawine@0: # select the parser sawine@0: try: sawine@0: parser = self._name_parser_map[parser_name] sawine@0: except KeyError: sawine@0: tup = parser_name, ', '.join(self._name_parser_map) sawine@0: msg = _('unknown parser %r (choices: %s)' % tup) sawine@0: raise ArgumentError(self, msg) sawine@0: sawine@0: # parse all the remaining options into the namespace sawine@0: parser.parse_args(arg_strings, namespace) sawine@0: sawine@0: sawine@0: # ============== sawine@0: # Type classes sawine@0: # ============== sawine@0: sawine@0: class FileType(object): sawine@0: """Factory for creating file object types sawine@0: sawine@0: Instances of FileType are typically passed as type= arguments to the sawine@0: ArgumentParser add_argument() method. sawine@0: sawine@0: Keyword Arguments: sawine@0: - mode -- A string indicating how the file is to be opened. Accepts the sawine@0: same values as the builtin open() function. sawine@0: - bufsize -- The file's desired buffer size. Accepts the same values as sawine@0: the builtin open() function. sawine@0: """ sawine@0: sawine@0: def __init__(self, mode='r', bufsize=None): sawine@0: self._mode = mode sawine@0: self._bufsize = bufsize sawine@0: sawine@0: def __call__(self, string): sawine@0: # the special argument "-" means sys.std{in,out} sawine@0: if string == '-': sawine@0: if 'r' in self._mode: sawine@0: return _sys.stdin sawine@0: elif 'w' in self._mode: sawine@0: return _sys.stdout sawine@0: else: sawine@0: msg = _('argument "-" with mode %r' % self._mode) sawine@0: raise ValueError(msg) sawine@0: sawine@0: # all other arguments are used as file names sawine@0: if self._bufsize: sawine@0: return open(string, self._mode, self._bufsize) sawine@0: else: sawine@0: return open(string, self._mode) sawine@0: sawine@0: def __repr__(self): sawine@0: args = [self._mode, self._bufsize] sawine@0: args_str = ', '.join([repr(arg) for arg in args if arg is not None]) sawine@0: return '%s(%s)' % (type(self).__name__, args_str) sawine@0: sawine@0: # =========================== sawine@0: # Optional and Positional Parsing sawine@0: # =========================== sawine@0: sawine@0: class Namespace(_AttributeHolder): sawine@0: """Simple object for storing attributes. sawine@0: sawine@0: Implements equality by attribute names and values, and provides a simple sawine@0: string representation. sawine@0: """ sawine@0: sawine@0: def __init__(self, **kwargs): sawine@0: for name in kwargs: sawine@0: setattr(self, name, kwargs[name]) sawine@0: sawine@0: def __eq__(self, other): sawine@0: return vars(self) == vars(other) sawine@0: sawine@0: def __ne__(self, other): sawine@0: return not (self == other) sawine@0: sawine@0: def __contains__(self, key): sawine@0: return key in self.__dict__ sawine@0: sawine@0: sawine@0: class _ActionsContainer(object): sawine@0: sawine@0: def __init__(self, sawine@0: description, sawine@0: prefix_chars, sawine@0: argument_default, sawine@0: conflict_handler): sawine@0: super(_ActionsContainer, self).__init__() sawine@0: sawine@0: self.description = description sawine@0: self.argument_default = argument_default sawine@0: self.prefix_chars = prefix_chars sawine@0: self.conflict_handler = conflict_handler sawine@0: sawine@0: # set up registries sawine@0: self._registries = {} sawine@0: sawine@0: # register actions sawine@0: self.register('action', None, _StoreAction) sawine@0: self.register('action', 'store', _StoreAction) sawine@0: self.register('action', 'store_const', _StoreConstAction) sawine@0: self.register('action', 'store_true', _StoreTrueAction) sawine@0: self.register('action', 'store_false', _StoreFalseAction) sawine@0: self.register('action', 'append', _AppendAction) sawine@0: self.register('action', 'append_const', _AppendConstAction) sawine@0: self.register('action', 'count', _CountAction) sawine@0: self.register('action', 'help', _HelpAction) sawine@0: self.register('action', 'version', _VersionAction) sawine@0: self.register('action', 'parsers', _SubParsersAction) sawine@0: sawine@0: # raise an exception if the conflict handler is invalid sawine@0: self._get_handler() sawine@0: sawine@0: # action storage sawine@0: self._actions = [] sawine@0: self._option_string_actions = {} sawine@0: sawine@0: # groups sawine@0: self._action_groups = [] sawine@0: self._mutually_exclusive_groups = [] sawine@0: sawine@0: # defaults storage sawine@0: self._defaults = {} sawine@0: sawine@0: # determines whether an "option" looks like a negative number sawine@0: self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$') sawine@0: sawine@0: # whether or not there are any optionals that look like negative sawine@0: # numbers -- uses a list so it can be shared and edited sawine@0: self._has_negative_number_optionals = [] sawine@0: sawine@0: # ==================== sawine@0: # Registration methods sawine@0: # ==================== sawine@0: def register(self, registry_name, value, object): sawine@0: registry = self._registries.setdefault(registry_name, {}) sawine@0: registry[value] = object sawine@0: sawine@0: def _registry_get(self, registry_name, value, default=None): sawine@0: return self._registries[registry_name].get(value, default) sawine@0: sawine@0: # ================================== sawine@0: # Namespace default accessor methods sawine@0: # ================================== sawine@0: def set_defaults(self, **kwargs): sawine@0: self._defaults.update(kwargs) sawine@0: sawine@0: # if these defaults match any existing arguments, replace sawine@0: # the previous default on the object with the new one sawine@0: for action in self._actions: sawine@0: if action.dest in kwargs: sawine@0: action.default = kwargs[action.dest] sawine@0: sawine@0: def get_default(self, dest): sawine@0: for action in self._actions: sawine@0: if action.dest == dest and action.default is not None: sawine@0: return action.default sawine@0: return self._defaults.get(dest, None) sawine@0: sawine@0: sawine@0: # ======================= sawine@0: # Adding argument actions sawine@0: # ======================= sawine@0: def add_argument(self, *args, **kwargs): sawine@0: """ sawine@0: add_argument(dest, ..., name=value, ...) sawine@0: add_argument(option_string, option_string, ..., name=value, ...) sawine@0: """ sawine@0: sawine@0: # if no positional args are supplied or only one is supplied and sawine@0: # it doesn't look like an option string, parse a positional sawine@0: # argument sawine@0: chars = self.prefix_chars sawine@0: if not args or len(args) == 1 and args[0][0] not in chars: sawine@0: if args and 'dest' in kwargs: sawine@0: raise ValueError('dest supplied twice for positional argument') sawine@0: kwargs = self._get_positional_kwargs(*args, **kwargs) sawine@0: sawine@0: # otherwise, we're adding an optional argument sawine@0: else: sawine@0: kwargs = self._get_optional_kwargs(*args, **kwargs) sawine@0: sawine@0: # if no default was supplied, use the parser-level default sawine@0: if 'default' not in kwargs: sawine@0: dest = kwargs['dest'] sawine@0: if dest in self._defaults: sawine@0: kwargs['default'] = self._defaults[dest] sawine@0: elif self.argument_default is not None: sawine@0: kwargs['default'] = self.argument_default sawine@0: sawine@0: # create the action object, and add it to the parser sawine@0: action_class = self._pop_action_class(kwargs) sawine@0: if not _callable(action_class): sawine@0: raise ValueError('unknown action "%s"' % action_class) sawine@0: action = action_class(**kwargs) sawine@0: sawine@0: # raise an error if the action type is not callable sawine@0: type_func = self._registry_get('type', action.type, action.type) sawine@0: if not _callable(type_func): sawine@0: raise ValueError('%r is not callable' % type_func) sawine@0: sawine@0: return self._add_action(action) sawine@0: sawine@0: def add_argument_group(self, *args, **kwargs): sawine@0: group = _ArgumentGroup(self, *args, **kwargs) sawine@0: self._action_groups.append(group) sawine@0: return group sawine@0: sawine@0: def add_mutually_exclusive_group(self, **kwargs): sawine@0: group = _MutuallyExclusiveGroup(self, **kwargs) sawine@0: self._mutually_exclusive_groups.append(group) sawine@0: return group sawine@0: sawine@0: def _add_action(self, action): sawine@0: # resolve any conflicts sawine@0: self._check_conflict(action) sawine@0: sawine@0: # add to actions list sawine@0: self._actions.append(action) sawine@0: action.container = self sawine@0: sawine@0: # index the action by any option strings it has sawine@0: for option_string in action.option_strings: sawine@0: self._option_string_actions[option_string] = action sawine@0: sawine@0: # set the flag if any option strings look like negative numbers sawine@0: for option_string in action.option_strings: sawine@0: if self._negative_number_matcher.match(option_string): sawine@0: if not self._has_negative_number_optionals: sawine@0: self._has_negative_number_optionals.append(True) sawine@0: sawine@0: # return the created action sawine@0: return action sawine@0: sawine@0: def _remove_action(self, action): sawine@0: self._actions.remove(action) sawine@0: sawine@0: def _add_container_actions(self, container): sawine@0: # collect groups by titles sawine@0: title_group_map = {} sawine@0: for group in self._action_groups: sawine@0: if group.title in title_group_map: sawine@0: msg = _('cannot merge actions - two groups are named %r') sawine@0: raise ValueError(msg % (group.title)) sawine@0: title_group_map[group.title] = group sawine@0: sawine@0: # map each action to its group sawine@0: group_map = {} sawine@0: for group in container._action_groups: sawine@0: sawine@0: # if a group with the title exists, use that, otherwise sawine@0: # create a new group matching the container's group sawine@0: if group.title not in title_group_map: sawine@0: title_group_map[group.title] = self.add_argument_group( sawine@0: title=group.title, sawine@0: description=group.description, sawine@0: conflict_handler=group.conflict_handler) sawine@0: sawine@0: # map the actions to their new group sawine@0: for action in group._group_actions: sawine@0: group_map[action] = title_group_map[group.title] sawine@0: sawine@0: # add container's mutually exclusive groups sawine@0: # NOTE: if add_mutually_exclusive_group ever gains title= and sawine@0: # description= then this code will need to be expanded as above sawine@0: for group in container._mutually_exclusive_groups: sawine@0: mutex_group = self.add_mutually_exclusive_group( sawine@0: required=group.required) sawine@0: sawine@0: # map the actions to their new mutex group sawine@0: for action in group._group_actions: sawine@0: group_map[action] = mutex_group sawine@0: sawine@0: # add all actions to this container or their group sawine@0: for action in container._actions: sawine@0: group_map.get(action, self)._add_action(action) sawine@0: sawine@0: def _get_positional_kwargs(self, dest, **kwargs): sawine@0: # make sure required is not specified sawine@0: if 'required' in kwargs: sawine@0: msg = _("'required' is an invalid argument for positionals") sawine@0: raise TypeError(msg) sawine@0: sawine@0: # mark positional arguments as required if at least one is sawine@0: # always required sawine@0: if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]: sawine@0: kwargs['required'] = True sawine@0: if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs: sawine@0: kwargs['required'] = True sawine@0: sawine@0: # return the keyword arguments with no option strings sawine@0: return dict(kwargs, dest=dest, option_strings=[]) sawine@0: sawine@0: def _get_optional_kwargs(self, *args, **kwargs): sawine@0: # determine short and long option strings sawine@0: option_strings = [] sawine@0: long_option_strings = [] sawine@0: for option_string in args: sawine@0: # error on strings that don't start with an appropriate prefix sawine@0: if not option_string[0] in self.prefix_chars: sawine@0: msg = _('invalid option string %r: ' sawine@0: 'must start with a character %r') sawine@0: tup = option_string, self.prefix_chars sawine@0: raise ValueError(msg % tup) sawine@0: sawine@0: # strings starting with two prefix characters are long options sawine@0: option_strings.append(option_string) sawine@0: if option_string[0] in self.prefix_chars: sawine@0: if len(option_string) > 1: sawine@0: if option_string[1] in self.prefix_chars: sawine@0: long_option_strings.append(option_string) sawine@0: sawine@0: # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' sawine@0: dest = kwargs.pop('dest', None) sawine@0: if dest is None: sawine@0: if long_option_strings: sawine@0: dest_option_string = long_option_strings[0] sawine@0: else: sawine@0: dest_option_string = option_strings[0] sawine@0: dest = dest_option_string.lstrip(self.prefix_chars) sawine@0: if not dest: sawine@0: msg = _('dest= is required for options like %r') sawine@0: raise ValueError(msg % option_string) sawine@0: dest = dest.replace('-', '_') sawine@0: sawine@0: # return the updated keyword arguments sawine@0: return dict(kwargs, dest=dest, option_strings=option_strings) sawine@0: sawine@0: def _pop_action_class(self, kwargs, default=None): sawine@0: action = kwargs.pop('action', default) sawine@0: return self._registry_get('action', action, action) sawine@0: sawine@0: def _get_handler(self): sawine@0: # determine function from conflict handler string sawine@0: handler_func_name = '_handle_conflict_%s' % self.conflict_handler sawine@0: try: sawine@0: return getattr(self, handler_func_name) sawine@0: except AttributeError: sawine@0: msg = _('invalid conflict_resolution value: %r') sawine@0: raise ValueError(msg % self.conflict_handler) sawine@0: sawine@0: def _check_conflict(self, action): sawine@0: sawine@0: # find all options that conflict with this option sawine@0: confl_optionals = [] sawine@0: for option_string in action.option_strings: sawine@0: if option_string in self._option_string_actions: sawine@0: confl_optional = self._option_string_actions[option_string] sawine@0: confl_optionals.append((option_string, confl_optional)) sawine@0: sawine@0: # resolve any conflicts sawine@0: if confl_optionals: sawine@0: conflict_handler = self._get_handler() sawine@0: conflict_handler(action, confl_optionals) sawine@0: sawine@0: def _handle_conflict_error(self, action, conflicting_actions): sawine@0: message = _('conflicting option string(s): %s') sawine@0: conflict_string = ', '.join([option_string sawine@0: for option_string, action sawine@0: in conflicting_actions]) sawine@0: raise ArgumentError(action, message % conflict_string) sawine@0: sawine@0: def _handle_conflict_resolve(self, action, conflicting_actions): sawine@0: sawine@0: # remove all conflicting options sawine@0: for option_string, action in conflicting_actions: sawine@0: sawine@0: # remove the conflicting option sawine@0: action.option_strings.remove(option_string) sawine@0: self._option_string_actions.pop(option_string, None) sawine@0: sawine@0: # if the option now has no option string, remove it from the sawine@0: # container holding it sawine@0: if not action.option_strings: sawine@0: action.container._remove_action(action) sawine@0: sawine@0: sawine@0: class _ArgumentGroup(_ActionsContainer): sawine@0: sawine@0: def __init__(self, container, title=None, description=None, **kwargs): sawine@0: # add any missing keyword arguments by checking the container sawine@0: update = kwargs.setdefault sawine@0: update('conflict_handler', container.conflict_handler) sawine@0: update('prefix_chars', container.prefix_chars) sawine@0: update('argument_default', container.argument_default) sawine@0: super_init = super(_ArgumentGroup, self).__init__ sawine@0: super_init(description=description, **kwargs) sawine@0: sawine@0: # group attributes sawine@0: self.title = title sawine@0: self._group_actions = [] sawine@0: sawine@0: # share most attributes with the container sawine@0: self._registries = container._registries sawine@0: self._actions = container._actions sawine@0: self._option_string_actions = container._option_string_actions sawine@0: self._defaults = container._defaults sawine@0: self._has_negative_number_optionals = \ sawine@0: container._has_negative_number_optionals sawine@0: sawine@0: def _add_action(self, action): sawine@0: action = super(_ArgumentGroup, self)._add_action(action) sawine@0: self._group_actions.append(action) sawine@0: return action sawine@0: sawine@0: def _remove_action(self, action): sawine@0: super(_ArgumentGroup, self)._remove_action(action) sawine@0: self._group_actions.remove(action) sawine@0: sawine@0: sawine@0: class _MutuallyExclusiveGroup(_ArgumentGroup): sawine@0: sawine@0: def __init__(self, container, required=False): sawine@0: super(_MutuallyExclusiveGroup, self).__init__(container) sawine@0: self.required = required sawine@0: self._container = container sawine@0: sawine@0: def _add_action(self, action): sawine@0: if action.required: sawine@0: msg = _('mutually exclusive arguments must be optional') sawine@0: raise ValueError(msg) sawine@0: action = self._container._add_action(action) sawine@0: self._group_actions.append(action) sawine@0: return action sawine@0: sawine@0: def _remove_action(self, action): sawine@0: self._container._remove_action(action) sawine@0: self._group_actions.remove(action) sawine@0: sawine@0: sawine@0: class ArgumentParser(_AttributeHolder, _ActionsContainer): sawine@0: """Object for parsing command line strings into Python objects. sawine@0: sawine@0: Keyword Arguments: sawine@0: - prog -- The name of the program (default: sys.argv[0]) sawine@0: - usage -- A usage message (default: auto-generated from arguments) sawine@0: - description -- A description of what the program does sawine@0: - epilog -- Text following the argument descriptions sawine@0: - parents -- Parsers whose arguments should be copied into this one sawine@0: - formatter_class -- HelpFormatter class for printing help messages sawine@0: - prefix_chars -- Characters that prefix optional arguments sawine@0: - fromfile_prefix_chars -- Characters that prefix files containing sawine@0: additional arguments sawine@0: - argument_default -- The default value for all arguments sawine@0: - conflict_handler -- String indicating how to handle conflicts sawine@0: - add_help -- Add a -h/-help option sawine@0: """ sawine@0: sawine@0: def __init__(self, sawine@0: prog=None, sawine@0: usage=None, sawine@0: description=None, sawine@0: epilog=None, sawine@0: version=None, sawine@0: parents=[], sawine@0: formatter_class=HelpFormatter, sawine@0: prefix_chars='-', sawine@0: fromfile_prefix_chars=None, sawine@0: argument_default=None, sawine@0: conflict_handler='error', sawine@0: add_help=True): sawine@0: sawine@0: if version is not None: sawine@0: import warnings sawine@0: warnings.warn( sawine@0: """The "version" argument to ArgumentParser is deprecated. """ sawine@0: """Please use """ sawine@0: """"add_argument(..., action='version', version="N", ...)" """ sawine@0: """instead""", DeprecationWarning) sawine@0: sawine@0: superinit = super(ArgumentParser, self).__init__ sawine@0: superinit(description=description, sawine@0: prefix_chars=prefix_chars, sawine@0: argument_default=argument_default, sawine@0: conflict_handler=conflict_handler) sawine@0: sawine@0: # default setting for prog sawine@0: if prog is None: sawine@0: prog = _os.path.basename(_sys.argv[0]) sawine@0: sawine@0: self.prog = prog sawine@0: self.usage = usage sawine@0: self.epilog = epilog sawine@0: self.version = version sawine@0: self.formatter_class = formatter_class sawine@0: self.fromfile_prefix_chars = fromfile_prefix_chars sawine@0: self.add_help = add_help sawine@0: sawine@0: add_group = self.add_argument_group sawine@0: self._positionals = add_group(_('positional arguments')) sawine@0: self._optionals = add_group(_('optional arguments')) sawine@0: self._subparsers = None sawine@0: sawine@0: # register types sawine@0: def identity(string): sawine@0: return string sawine@0: self.register('type', None, identity) sawine@0: sawine@0: # add help and version arguments if necessary sawine@0: # (using explicit default to override global argument_default) sawine@0: default_prefix = '-' if '-' in prefix_chars else prefix_chars[0] sawine@0: if self.add_help: sawine@0: self.add_argument( sawine@0: default_prefix+'h', default_prefix*2+'help', sawine@0: action='help', default=SUPPRESS, sawine@0: help=_('show this help message and exit')) sawine@0: if self.version: sawine@0: self.add_argument( sawine@0: default_prefix+'v', default_prefix*2+'version', sawine@0: action='version', default=SUPPRESS, sawine@0: version=self.version, sawine@0: help=_("show program's version number and exit")) sawine@0: sawine@0: # add parent arguments and defaults sawine@0: for parent in parents: sawine@0: self._add_container_actions(parent) sawine@0: try: sawine@0: defaults = parent._defaults sawine@0: except AttributeError: sawine@0: pass sawine@0: else: sawine@0: self._defaults.update(defaults) sawine@0: sawine@0: # ======================= sawine@0: # Pretty __repr__ methods sawine@0: # ======================= sawine@0: def _get_kwargs(self): sawine@0: names = [ sawine@0: 'prog', sawine@0: 'usage', sawine@0: 'description', sawine@0: 'version', sawine@0: 'formatter_class', sawine@0: 'conflict_handler', sawine@0: 'add_help', sawine@0: ] sawine@0: return [(name, getattr(self, name)) for name in names] sawine@0: sawine@0: # ================================== sawine@0: # Optional/Positional adding methods sawine@0: # ================================== sawine@0: def add_subparsers(self, **kwargs): sawine@0: if self._subparsers is not None: sawine@0: self.error(_('cannot have multiple subparser arguments')) sawine@0: sawine@0: # add the parser class to the arguments if it's not present sawine@0: kwargs.setdefault('parser_class', type(self)) sawine@0: sawine@0: if 'title' in kwargs or 'description' in kwargs: sawine@0: title = _(kwargs.pop('title', 'subcommands')) sawine@0: description = _(kwargs.pop('description', None)) sawine@0: self._subparsers = self.add_argument_group(title, description) sawine@0: else: sawine@0: self._subparsers = self._positionals sawine@0: sawine@0: # prog defaults to the usage message of this parser, skipping sawine@0: # optional arguments and with no "usage:" prefix sawine@0: if kwargs.get('prog') is None: sawine@0: formatter = self._get_formatter() sawine@0: positionals = self._get_positional_actions() sawine@0: groups = self._mutually_exclusive_groups sawine@0: formatter.add_usage(self.usage, positionals, groups, '') sawine@0: kwargs['prog'] = formatter.format_help().strip() sawine@0: sawine@0: # create the parsers action and add it to the positionals list sawine@0: parsers_class = self._pop_action_class(kwargs, 'parsers') sawine@0: action = parsers_class(option_strings=[], **kwargs) sawine@0: self._subparsers._add_action(action) sawine@0: sawine@0: # return the created parsers action sawine@0: return action sawine@0: sawine@0: def _add_action(self, action): sawine@0: if action.option_strings: sawine@0: self._optionals._add_action(action) sawine@0: else: sawine@0: self._positionals._add_action(action) sawine@0: return action sawine@0: sawine@0: def _get_optional_actions(self): sawine@0: return [action sawine@0: for action in self._actions sawine@0: if action.option_strings] sawine@0: sawine@0: def _get_positional_actions(self): sawine@0: return [action sawine@0: for action in self._actions sawine@0: if not action.option_strings] sawine@0: sawine@0: # ===================================== sawine@0: # Command line argument parsing methods sawine@0: # ===================================== sawine@0: def parse_args(self, args=None, namespace=None): sawine@0: args, argv = self.parse_known_args(args, namespace) sawine@0: if argv: sawine@0: msg = _('unrecognized arguments: %s') sawine@0: self.error(msg % ' '.join(argv)) sawine@0: return args sawine@0: sawine@0: def parse_known_args(self, args=None, namespace=None): sawine@0: # args default to the system args sawine@0: if args is None: sawine@0: args = _sys.argv[1:] sawine@0: sawine@0: # default Namespace built from parser defaults sawine@0: if namespace is None: sawine@0: namespace = Namespace() sawine@0: sawine@0: # add any action defaults that aren't present sawine@0: for action in self._actions: sawine@0: if action.dest is not SUPPRESS: sawine@0: if not hasattr(namespace, action.dest): sawine@0: if action.default is not SUPPRESS: sawine@0: default = action.default sawine@0: if isinstance(action.default, str): sawine@0: default = self._get_value(action, default) sawine@0: setattr(namespace, action.dest, default) sawine@0: sawine@0: # add any parser defaults that aren't present sawine@0: for dest in self._defaults: sawine@0: if not hasattr(namespace, dest): sawine@0: setattr(namespace, dest, self._defaults[dest]) sawine@0: sawine@0: # parse the arguments and exit if there are any errors sawine@0: try: sawine@0: return self._parse_known_args(args, namespace) sawine@0: except ArgumentError: sawine@0: err = _sys.exc_info()[1] sawine@0: self.error(str(err)) sawine@0: sawine@0: def _parse_known_args(self, arg_strings, namespace): sawine@0: # replace arg strings that are file references sawine@0: if self.fromfile_prefix_chars is not None: sawine@0: arg_strings = self._read_args_from_files(arg_strings) sawine@0: sawine@0: # map all mutually exclusive arguments to the other arguments sawine@0: # they can't occur with sawine@0: action_conflicts = {} sawine@0: for mutex_group in self._mutually_exclusive_groups: sawine@0: group_actions = mutex_group._group_actions sawine@0: for i, mutex_action in enumerate(mutex_group._group_actions): sawine@0: conflicts = action_conflicts.setdefault(mutex_action, []) sawine@0: conflicts.extend(group_actions[:i]) sawine@0: conflicts.extend(group_actions[i + 1:]) sawine@0: sawine@0: # find all option indices, and determine the arg_string_pattern sawine@0: # which has an 'O' if there is an option at an index, sawine@0: # an 'A' if there is an argument, or a '-' if there is a '--' sawine@0: option_string_indices = {} sawine@0: arg_string_pattern_parts = [] sawine@0: arg_strings_iter = iter(arg_strings) sawine@0: for i, arg_string in enumerate(arg_strings_iter): sawine@0: sawine@0: # all args after -- are non-options sawine@0: if arg_string == '--': sawine@0: arg_string_pattern_parts.append('-') sawine@0: for arg_string in arg_strings_iter: sawine@0: arg_string_pattern_parts.append('A') sawine@0: sawine@0: # otherwise, add the arg to the arg strings sawine@0: # and note the index if it was an option sawine@0: else: sawine@0: option_tuple = self._parse_optional(arg_string) sawine@0: if option_tuple is None: sawine@0: pattern = 'A' sawine@0: else: sawine@0: option_string_indices[i] = option_tuple sawine@0: pattern = 'O' sawine@0: arg_string_pattern_parts.append(pattern) sawine@0: sawine@0: # join the pieces together to form the pattern sawine@0: arg_strings_pattern = ''.join(arg_string_pattern_parts) sawine@0: sawine@0: # converts arg strings to the appropriate and then takes the action sawine@0: seen_actions = set() sawine@0: seen_non_default_actions = set() sawine@0: sawine@0: def take_action(action, argument_strings, option_string=None): sawine@0: seen_actions.add(action) sawine@0: argument_values = self._get_values(action, argument_strings) sawine@0: sawine@0: # error if this argument is not allowed with other previously sawine@0: # seen arguments, assuming that actions that use the default sawine@0: # value don't really count as "present" sawine@0: if argument_values is not action.default: sawine@0: seen_non_default_actions.add(action) sawine@0: for conflict_action in action_conflicts.get(action, []): sawine@0: if conflict_action in seen_non_default_actions: sawine@0: msg = _('not allowed with argument %s') sawine@0: action_name = _get_action_name(conflict_action) sawine@0: raise ArgumentError(action, msg % action_name) sawine@0: sawine@0: # take the action if we didn't receive a SUPPRESS value sawine@0: # (e.g. from a default) sawine@0: if argument_values is not SUPPRESS: sawine@0: action(self, namespace, argument_values, option_string) sawine@0: sawine@0: # function to convert arg_strings into an optional action sawine@0: def consume_optional(start_index): sawine@0: sawine@0: # get the optional identified at this index sawine@0: option_tuple = option_string_indices[start_index] sawine@0: action, option_string, explicit_arg = option_tuple sawine@0: sawine@0: # identify additional optionals in the same arg string sawine@0: # (e.g. -xyz is the same as -x -y -z if no args are required) sawine@0: match_argument = self._match_argument sawine@0: action_tuples = [] sawine@0: while True: sawine@0: sawine@0: # if we found no optional action, skip it sawine@0: if action is None: sawine@0: extras.append(arg_strings[start_index]) sawine@0: return start_index + 1 sawine@0: sawine@0: # if there is an explicit argument, try to match the sawine@0: # optional's string arguments to only this sawine@0: if explicit_arg is not None: sawine@0: arg_count = match_argument(action, 'A') sawine@0: sawine@0: # if the action is a single-dash option and takes no sawine@0: # arguments, try to parse more single-dash options out sawine@0: # of the tail of the option string sawine@0: chars = self.prefix_chars sawine@0: if arg_count == 0 and option_string[1] not in chars: sawine@0: action_tuples.append((action, [], option_string)) sawine@0: for char in self.prefix_chars: sawine@0: option_string = char + explicit_arg[0] sawine@0: explicit_arg = explicit_arg[1:] or None sawine@0: optionals_map = self._option_string_actions sawine@0: if option_string in optionals_map: sawine@0: action = optionals_map[option_string] sawine@0: break sawine@0: else: sawine@0: msg = _('ignored explicit argument %r') sawine@0: raise ArgumentError(action, msg % explicit_arg) sawine@0: sawine@0: # if the action expect exactly one argument, we've sawine@0: # successfully matched the option; exit the loop sawine@0: elif arg_count == 1: sawine@0: stop = start_index + 1 sawine@0: args = [explicit_arg] sawine@0: action_tuples.append((action, args, option_string)) sawine@0: break sawine@0: sawine@0: # error if a double-dash option did not use the sawine@0: # explicit argument sawine@0: else: sawine@0: msg = _('ignored explicit argument %r') sawine@0: raise ArgumentError(action, msg % explicit_arg) sawine@0: sawine@0: # if there is no explicit argument, try to match the sawine@0: # optional's string arguments with the following strings sawine@0: # if successful, exit the loop sawine@0: else: sawine@0: start = start_index + 1 sawine@0: selected_patterns = arg_strings_pattern[start:] sawine@0: arg_count = match_argument(action, selected_patterns) sawine@0: stop = start + arg_count sawine@0: args = arg_strings[start:stop] sawine@0: action_tuples.append((action, args, option_string)) sawine@0: break sawine@0: sawine@0: # add the Optional to the list and return the index at which sawine@0: # the Optional's string args stopped sawine@0: assert action_tuples sawine@0: for action, args, option_string in action_tuples: sawine@0: take_action(action, args, option_string) sawine@0: return stop sawine@0: sawine@0: # the list of Positionals left to be parsed; this is modified sawine@0: # by consume_positionals() sawine@0: positionals = self._get_positional_actions() sawine@0: sawine@0: # function to convert arg_strings into positional actions sawine@0: def consume_positionals(start_index): sawine@0: # match as many Positionals as possible sawine@0: match_partial = self._match_arguments_partial sawine@0: selected_pattern = arg_strings_pattern[start_index:] sawine@0: arg_counts = match_partial(positionals, selected_pattern) sawine@0: sawine@0: # slice off the appropriate arg strings for each Positional sawine@0: # and add the Positional and its args to the list sawine@0: for action, arg_count in zip(positionals, arg_counts): sawine@0: args = arg_strings[start_index: start_index + arg_count] sawine@0: start_index += arg_count sawine@0: take_action(action, args) sawine@0: sawine@0: # slice off the Positionals that we just parsed and return the sawine@0: # index at which the Positionals' string args stopped sawine@0: positionals[:] = positionals[len(arg_counts):] sawine@0: return start_index sawine@0: sawine@0: # consume Positionals and Optionals alternately, until we have sawine@0: # passed the last option string sawine@0: extras = [] sawine@0: start_index = 0 sawine@0: if option_string_indices: sawine@0: max_option_string_index = max(option_string_indices) sawine@0: else: sawine@0: max_option_string_index = -1 sawine@0: while start_index <= max_option_string_index: sawine@0: sawine@0: # consume any Positionals preceding the next option sawine@0: next_option_string_index = min([ sawine@0: index sawine@0: for index in option_string_indices sawine@0: if index >= start_index]) sawine@0: if start_index != next_option_string_index: sawine@0: positionals_end_index = consume_positionals(start_index) sawine@0: sawine@0: # only try to parse the next optional if we didn't consume sawine@0: # the option string during the positionals parsing sawine@0: if positionals_end_index > start_index: sawine@0: start_index = positionals_end_index sawine@0: continue sawine@0: else: sawine@0: start_index = positionals_end_index sawine@0: sawine@0: # if we consumed all the positionals we could and we're not sawine@0: # at the index of an option string, there were extra arguments sawine@0: if start_index not in option_string_indices: sawine@0: strings = arg_strings[start_index:next_option_string_index] sawine@0: extras.extend(strings) sawine@0: start_index = next_option_string_index sawine@0: sawine@0: # consume the next optional and any arguments for it sawine@0: start_index = consume_optional(start_index) sawine@0: sawine@0: # consume any positionals following the last Optional sawine@0: stop_index = consume_positionals(start_index) sawine@0: sawine@0: # if we didn't consume all the argument strings, there were extras sawine@0: extras.extend(arg_strings[stop_index:]) sawine@0: sawine@0: # if we didn't use all the Positional objects, there were too few sawine@0: # arg strings supplied. sawine@0: if positionals: sawine@0: self.error(_('too few arguments')) sawine@0: sawine@0: # make sure all required actions were present sawine@0: for action in self._actions: sawine@0: if action.required: sawine@0: if action not in seen_actions: sawine@0: name = _get_action_name(action) sawine@0: self.error(_('argument %s is required') % name) sawine@0: sawine@0: # make sure all required groups had one option present sawine@0: for group in self._mutually_exclusive_groups: sawine@0: if group.required: sawine@0: for action in group._group_actions: sawine@0: if action in seen_non_default_actions: sawine@0: break sawine@0: sawine@0: # if no actions were used, report the error sawine@0: else: sawine@0: names = [_get_action_name(action) sawine@0: for action in group._group_actions sawine@0: if action.help is not SUPPRESS] sawine@0: msg = _('one of the arguments %s is required') sawine@0: self.error(msg % ' '.join(names)) sawine@0: sawine@0: # return the updated namespace and the extra arguments sawine@0: return namespace, extras sawine@0: sawine@0: def _read_args_from_files(self, arg_strings): sawine@0: # expand arguments referencing files sawine@0: new_arg_strings = [] sawine@0: for arg_string in arg_strings: sawine@0: sawine@0: # for regular arguments, just add them back into the list sawine@0: if arg_string[0] not in self.fromfile_prefix_chars: sawine@0: new_arg_strings.append(arg_string) sawine@0: sawine@0: # replace arguments referencing files with the file content sawine@0: else: sawine@0: try: sawine@0: args_file = open(arg_string[1:]) sawine@0: try: sawine@0: arg_strings = [] sawine@0: for arg_line in args_file.read().splitlines(): sawine@0: for arg in self.convert_arg_line_to_args(arg_line): sawine@0: arg_strings.append(arg) sawine@0: arg_strings = self._read_args_from_files(arg_strings) sawine@0: new_arg_strings.extend(arg_strings) sawine@0: finally: sawine@0: args_file.close() sawine@0: except IOError: sawine@0: err = _sys.exc_info()[1] sawine@0: self.error(str(err)) sawine@0: sawine@0: # return the modified argument list sawine@0: return new_arg_strings sawine@0: sawine@0: def convert_arg_line_to_args(self, arg_line): sawine@0: return [arg_line] sawine@0: sawine@0: def _match_argument(self, action, arg_strings_pattern): sawine@0: # match the pattern for this action to the arg strings sawine@0: nargs_pattern = self._get_nargs_pattern(action) sawine@0: match = _re.match(nargs_pattern, arg_strings_pattern) sawine@0: sawine@0: # raise an exception if we weren't able to find a match sawine@0: if match is None: sawine@0: nargs_errors = { sawine@0: None: _('expected one argument'), sawine@0: OPTIONAL: _('expected at most one argument'), sawine@0: ONE_OR_MORE: _('expected at least one argument'), sawine@0: } sawine@0: default = _('expected %s argument(s)') % action.nargs sawine@0: msg = nargs_errors.get(action.nargs, default) sawine@0: raise ArgumentError(action, msg) sawine@0: sawine@0: # return the number of arguments matched sawine@0: return len(match.group(1)) sawine@0: sawine@0: def _match_arguments_partial(self, actions, arg_strings_pattern): sawine@0: # progressively shorten the actions list by slicing off the sawine@0: # final actions until we find a match sawine@0: result = [] sawine@0: for i in range(len(actions), 0, -1): sawine@0: actions_slice = actions[:i] sawine@0: pattern = ''.join([self._get_nargs_pattern(action) sawine@0: for action in actions_slice]) sawine@0: match = _re.match(pattern, arg_strings_pattern) sawine@0: if match is not None: sawine@0: result.extend([len(string) for string in match.groups()]) sawine@0: break sawine@0: sawine@0: # return the list of arg string counts sawine@0: return result sawine@0: sawine@0: def _parse_optional(self, arg_string): sawine@0: # if it's an empty string, it was meant to be a positional sawine@0: if not arg_string: sawine@0: return None sawine@0: sawine@0: # if it doesn't start with a prefix, it was meant to be positional sawine@0: if not arg_string[0] in self.prefix_chars: sawine@0: return None sawine@0: sawine@0: # if the option string is present in the parser, return the action sawine@0: if arg_string in self._option_string_actions: sawine@0: action = self._option_string_actions[arg_string] sawine@0: return action, arg_string, None sawine@0: sawine@0: # if it's just a single character, it was meant to be positional sawine@0: if len(arg_string) == 1: sawine@0: return None sawine@0: sawine@0: # if the option string before the "=" is present, return the action sawine@0: if '=' in arg_string: sawine@0: option_string, explicit_arg = arg_string.split('=', 1) sawine@0: if option_string in self._option_string_actions: sawine@0: action = self._option_string_actions[option_string] sawine@0: return action, option_string, explicit_arg sawine@0: sawine@0: # search through all possible prefixes of the option string sawine@0: # and all actions in the parser for possible interpretations sawine@0: option_tuples = self._get_option_tuples(arg_string) sawine@0: sawine@0: # if multiple actions match, the option string was ambiguous sawine@0: if len(option_tuples) > 1: sawine@0: options = ', '.join([option_string sawine@0: for action, option_string, explicit_arg in option_tuples]) sawine@0: tup = arg_string, options sawine@0: self.error(_('ambiguous option: %s could match %s') % tup) sawine@0: sawine@0: # if exactly one action matched, this segmentation is good, sawine@0: # so return the parsed action sawine@0: elif len(option_tuples) == 1: sawine@0: option_tuple, = option_tuples sawine@0: return option_tuple sawine@0: sawine@0: # if it was not found as an option, but it looks like a negative sawine@0: # number, it was meant to be positional sawine@0: # unless there are negative-number-like options sawine@0: if self._negative_number_matcher.match(arg_string): sawine@0: if not self._has_negative_number_optionals: sawine@0: return None sawine@0: sawine@0: # if it contains a space, it was meant to be a positional sawine@0: if ' ' in arg_string: sawine@0: return None sawine@0: sawine@0: # it was meant to be an optional but there is no such option sawine@0: # in this parser (though it might be a valid option in a subparser) sawine@0: return None, arg_string, None sawine@0: sawine@0: def _get_option_tuples(self, option_string): sawine@0: result = [] sawine@0: sawine@0: # option strings starting with two prefix characters are only sawine@0: # split at the '=' sawine@0: chars = self.prefix_chars sawine@0: if option_string[0] in chars and option_string[1] in chars: sawine@0: if '=' in option_string: sawine@0: option_prefix, explicit_arg = option_string.split('=', 1) sawine@0: else: sawine@0: option_prefix = option_string sawine@0: explicit_arg = None sawine@0: for option_string in self._option_string_actions: sawine@0: if option_string.startswith(option_prefix): sawine@0: action = self._option_string_actions[option_string] sawine@0: tup = action, option_string, explicit_arg sawine@0: result.append(tup) sawine@0: sawine@0: # single character options can be concatenated with their arguments sawine@0: # but multiple character options always have to have their argument sawine@0: # separate sawine@0: elif option_string[0] in chars and option_string[1] not in chars: sawine@0: option_prefix = option_string sawine@0: explicit_arg = None sawine@0: short_option_prefix = option_string[:2] sawine@0: short_explicit_arg = option_string[2:] sawine@0: sawine@0: for option_string in self._option_string_actions: sawine@0: if option_string == short_option_prefix: sawine@0: action = self._option_string_actions[option_string] sawine@0: tup = action, option_string, short_explicit_arg sawine@0: result.append(tup) sawine@0: elif option_string.startswith(option_prefix): sawine@0: action = self._option_string_actions[option_string] sawine@0: tup = action, option_string, explicit_arg sawine@0: result.append(tup) sawine@0: sawine@0: # shouldn't ever get here sawine@0: else: sawine@0: self.error(_('unexpected option string: %s') % option_string) sawine@0: sawine@0: # return the collected option tuples sawine@0: return result sawine@0: sawine@0: def _get_nargs_pattern(self, action): sawine@0: # in all examples below, we have to allow for '--' args sawine@0: # which are represented as '-' in the pattern sawine@0: nargs = action.nargs sawine@0: sawine@0: # the default (None) is assumed to be a single argument sawine@0: if nargs is None: sawine@0: nargs_pattern = '(-*A-*)' sawine@0: sawine@0: # allow zero or one arguments sawine@0: elif nargs == OPTIONAL: sawine@0: nargs_pattern = '(-*A?-*)' sawine@0: sawine@0: # allow zero or more arguments sawine@0: elif nargs == ZERO_OR_MORE: sawine@0: nargs_pattern = '(-*[A-]*)' sawine@0: sawine@0: # allow one or more arguments sawine@0: elif nargs == ONE_OR_MORE: sawine@0: nargs_pattern = '(-*A[A-]*)' sawine@0: sawine@0: # allow any number of options or arguments sawine@0: elif nargs == REMAINDER: sawine@0: nargs_pattern = '([-AO]*)' sawine@0: sawine@0: # allow one argument followed by any number of options or arguments sawine@0: elif nargs == PARSER: sawine@0: nargs_pattern = '(-*A[-AO]*)' sawine@0: sawine@0: # all others should be integers sawine@0: else: sawine@0: nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs) sawine@0: sawine@0: # if this is an optional action, -- is not allowed sawine@0: if action.option_strings: sawine@0: nargs_pattern = nargs_pattern.replace('-*', '') sawine@0: nargs_pattern = nargs_pattern.replace('-', '') sawine@0: sawine@0: # return the pattern sawine@0: return nargs_pattern sawine@0: sawine@0: # ======================== sawine@0: # Value conversion methods sawine@0: # ======================== sawine@0: def _get_values(self, action, arg_strings): sawine@0: # for everything but PARSER args, strip out '--' sawine@0: if action.nargs not in [PARSER, REMAINDER]: sawine@0: arg_strings = [s for s in arg_strings if s != '--'] sawine@0: sawine@0: # optional argument produces a default when not present sawine@0: if not arg_strings and action.nargs == OPTIONAL: sawine@0: if action.option_strings: sawine@0: value = action.const sawine@0: else: sawine@0: value = action.default sawine@0: if isinstance(value, str): sawine@0: value = self._get_value(action, value) sawine@0: self._check_value(action, value) sawine@0: sawine@0: # when nargs='*' on a positional, if there were no command-line sawine@0: # args, use the default if it is anything other than None sawine@0: elif (not arg_strings and action.nargs == ZERO_OR_MORE and sawine@0: not action.option_strings): sawine@0: if action.default is not None: sawine@0: value = action.default sawine@0: else: sawine@0: value = arg_strings sawine@0: self._check_value(action, value) sawine@0: sawine@0: # single argument or optional argument produces a single value sawine@0: elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]: sawine@0: arg_string, = arg_strings sawine@0: value = self._get_value(action, arg_string) sawine@0: self._check_value(action, value) sawine@0: sawine@0: # REMAINDER arguments convert all values, checking none sawine@0: elif action.nargs == REMAINDER: sawine@0: value = [self._get_value(action, v) for v in arg_strings] sawine@0: sawine@0: # PARSER arguments convert all values, but check only the first sawine@0: elif action.nargs == PARSER: sawine@0: value = [self._get_value(action, v) for v in arg_strings] sawine@0: self._check_value(action, value[0]) sawine@0: sawine@0: # all other types of nargs produce a list sawine@0: else: sawine@0: value = [self._get_value(action, v) for v in arg_strings] sawine@0: for v in value: sawine@0: self._check_value(action, v) sawine@0: sawine@0: # return the converted value sawine@0: return value sawine@0: sawine@0: def _get_value(self, action, arg_string): sawine@0: type_func = self._registry_get('type', action.type, action.type) sawine@0: if not _callable(type_func): sawine@0: msg = _('%r is not callable') sawine@0: raise ArgumentError(action, msg % type_func) sawine@0: sawine@0: # convert the value to the appropriate type sawine@0: try: sawine@0: result = type_func(arg_string) sawine@0: sawine@0: # ArgumentTypeErrors indicate errors sawine@0: except ArgumentTypeError: sawine@0: name = getattr(action.type, '__name__', repr(action.type)) sawine@0: msg = str(_sys.exc_info()[1]) sawine@0: raise ArgumentError(action, msg) sawine@0: sawine@0: # TypeErrors or ValueErrors also indicate errors sawine@0: except (TypeError, ValueError): sawine@0: name = getattr(action.type, '__name__', repr(action.type)) sawine@0: msg = _('invalid %s value: %r') sawine@0: raise ArgumentError(action, msg % (name, arg_string)) sawine@0: sawine@0: # return the converted value sawine@0: return result sawine@0: sawine@0: def _check_value(self, action, value): sawine@0: # converted value must be one of the choices (if specified) sawine@0: if action.choices is not None and value not in action.choices: sawine@0: tup = value, ', '.join(map(repr, action.choices)) sawine@0: msg = _('invalid choice: %r (choose from %s)') % tup sawine@0: raise ArgumentError(action, msg) sawine@0: sawine@0: # ======================= sawine@0: # Help-formatting methods sawine@0: # ======================= sawine@0: def format_usage(self): sawine@0: formatter = self._get_formatter() sawine@0: formatter.add_usage(self.usage, self._actions, sawine@0: self._mutually_exclusive_groups) sawine@0: return formatter.format_help() sawine@0: sawine@0: def format_help(self): sawine@0: formatter = self._get_formatter() sawine@0: sawine@0: # usage sawine@0: formatter.add_usage(self.usage, self._actions, sawine@0: self._mutually_exclusive_groups) sawine@0: sawine@0: # description sawine@0: formatter.add_text(self.description) sawine@0: sawine@0: # positionals, optionals and user-defined groups sawine@0: for action_group in self._action_groups: sawine@0: formatter.start_section(action_group.title) sawine@0: formatter.add_text(action_group.description) sawine@0: formatter.add_arguments(action_group._group_actions) sawine@0: formatter.end_section() sawine@0: sawine@0: # epilog sawine@0: formatter.add_text(self.epilog) sawine@0: sawine@0: # determine help from format above sawine@0: return formatter.format_help() sawine@0: sawine@0: def format_version(self): sawine@0: import warnings sawine@0: warnings.warn( sawine@0: 'The format_version method is deprecated -- the "version" ' sawine@0: 'argument to ArgumentParser is no longer supported.', sawine@0: DeprecationWarning) sawine@0: formatter = self._get_formatter() sawine@0: formatter.add_text(self.version) sawine@0: return formatter.format_help() sawine@0: sawine@0: def _get_formatter(self): sawine@0: return self.formatter_class(prog=self.prog) sawine@0: sawine@0: # ===================== sawine@0: # Help-printing methods sawine@0: # ===================== sawine@0: def print_usage(self, file=None): sawine@0: if file is None: sawine@0: file = _sys.stdout sawine@0: self._print_message(self.format_usage(), file) sawine@0: sawine@0: def print_help(self, file=None): sawine@0: if file is None: sawine@0: file = _sys.stdout sawine@0: self._print_message(self.format_help(), file) sawine@0: sawine@0: def print_version(self, file=None): sawine@0: import warnings sawine@0: warnings.warn( sawine@0: 'The print_version method is deprecated -- the "version" ' sawine@0: 'argument to ArgumentParser is no longer supported.', sawine@0: DeprecationWarning) sawine@0: self._print_message(self.format_version(), file) sawine@0: sawine@0: def _print_message(self, message, file=None): sawine@0: if message: sawine@0: if file is None: sawine@0: file = _sys.stderr sawine@0: file.write(message) sawine@0: sawine@0: # =============== sawine@0: # Exiting methods sawine@0: # =============== sawine@0: def exit(self, status=0, message=None): sawine@0: if message: sawine@0: self._print_message(message, _sys.stderr) sawine@0: _sys.exit(status) sawine@0: sawine@0: def error(self, message): sawine@0: """error(message: string) sawine@0: sawine@0: Prints a usage message incorporating the message to stderr and sawine@0: exits. sawine@0: sawine@0: If you override this in a subclass, it should not return -- it sawine@0: should either exit or raise an exception. sawine@0: """ sawine@0: self.print_usage(_sys.stderr) sawine@0: self.exit(2, _('%s: error: %s\n') % (self.prog, message))