Benjamin Peterson | 2b37fc4 | 2010-03-24 22:10:42 +0000 | [diff] [blame] | 1 | # Author: Steven J. Bethard <steven.bethard@gmail.com>. |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2 | |
| 3 | """Command-line parsing library |
| 4 | |
| 5 | This module is an optparse-inspired command-line parsing library that: |
| 6 | |
| 7 | - handles both optional and positional arguments |
| 8 | - produces highly informative usage messages |
| 9 | - supports parsers that dispatch to sub-parsers |
| 10 | |
| 11 | The following is a simple usage example that sums integers from the |
| 12 | command-line and writes the result to a file:: |
| 13 | |
| 14 | parser = argparse.ArgumentParser( |
| 15 | description='sum the integers at the command line') |
| 16 | parser.add_argument( |
| 17 | 'integers', metavar='int', nargs='+', type=int, |
| 18 | help='an integer to be summed') |
| 19 | parser.add_argument( |
| 20 | '--log', default=sys.stdout, type=argparse.FileType('w'), |
| 21 | help='the file where the sum should be written') |
| 22 | args = parser.parse_args() |
| 23 | args.log.write('%s' % sum(args.integers)) |
| 24 | args.log.close() |
| 25 | |
| 26 | The module contains the following public classes: |
| 27 | |
| 28 | - ArgumentParser -- The main entry point for command-line parsing. As the |
| 29 | example above shows, the add_argument() method is used to populate |
| 30 | the parser with actions for optional and positional arguments. Then |
| 31 | the parse_args() method is invoked to convert the args at the |
| 32 | command-line into an object with attributes. |
| 33 | |
| 34 | - ArgumentError -- The exception raised by ArgumentParser objects when |
| 35 | there are errors with the parser's actions. Errors raised while |
| 36 | parsing the command-line are caught by ArgumentParser and emitted |
| 37 | as command-line messages. |
| 38 | |
| 39 | - FileType -- A factory for defining types of files to be created. As the |
| 40 | example above shows, instances of FileType are typically passed as |
| 41 | the type= argument of add_argument() calls. |
| 42 | |
| 43 | - Action -- The base class for parser actions. Typically actions are |
| 44 | selected by passing strings like 'store_true' or 'append_const' to |
| 45 | the action= argument of add_argument(). However, for greater |
| 46 | customization of ArgumentParser actions, subclasses of Action may |
| 47 | be defined and passed as the action= argument. |
| 48 | |
| 49 | - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, |
| 50 | ArgumentDefaultsHelpFormatter -- Formatter classes which |
| 51 | may be passed as the formatter_class= argument to the |
| 52 | ArgumentParser constructor. HelpFormatter is the default, |
| 53 | RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser |
| 54 | not to change the formatting for help text, and |
| 55 | ArgumentDefaultsHelpFormatter adds information about argument defaults |
| 56 | to the help. |
| 57 | |
| 58 | All other classes in this module are considered implementation details. |
| 59 | (Also note that HelpFormatter and RawDescriptionHelpFormatter are only |
| 60 | considered public as object names -- the API of the formatter objects is |
| 61 | still considered an implementation detail.) |
| 62 | """ |
| 63 | |
| 64 | __version__ = '1.1' |
| 65 | __all__ = [ |
| 66 | 'ArgumentParser', |
| 67 | 'ArgumentError', |
Steven Bethard | 72c5538 | 2010-11-01 15:23:12 +0000 | [diff] [blame] | 68 | 'ArgumentTypeError', |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 69 | 'FileType', |
| 70 | 'HelpFormatter', |
Steven Bethard | 72c5538 | 2010-11-01 15:23:12 +0000 | [diff] [blame] | 71 | 'ArgumentDefaultsHelpFormatter', |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 72 | 'RawDescriptionHelpFormatter', |
| 73 | 'RawTextHelpFormatter', |
Steven Bethard | 0331e90 | 2011-03-26 14:48:04 +0100 | [diff] [blame] | 74 | 'MetavarTypeHelpFormatter', |
Steven Bethard | 72c5538 | 2010-11-01 15:23:12 +0000 | [diff] [blame] | 75 | 'Namespace', |
| 76 | 'Action', |
| 77 | 'ONE_OR_MORE', |
| 78 | 'OPTIONAL', |
| 79 | 'PARSER', |
| 80 | 'REMAINDER', |
| 81 | 'SUPPRESS', |
| 82 | 'ZERO_OR_MORE', |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 83 | ] |
| 84 | |
| 85 | |
Steven Bethard | 8a6a198 | 2011-03-27 13:53:53 +0200 | [diff] [blame] | 86 | import collections as _collections |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 87 | import copy as _copy |
| 88 | import os as _os |
| 89 | import re as _re |
| 90 | import sys as _sys |
| 91 | import textwrap as _textwrap |
| 92 | |
Éric Araujo | 1215915 | 2010-12-04 17:31:49 +0000 | [diff] [blame] | 93 | from gettext import gettext as _, ngettext |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 94 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 95 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 96 | SUPPRESS = '==SUPPRESS==' |
| 97 | |
| 98 | OPTIONAL = '?' |
| 99 | ZERO_OR_MORE = '*' |
| 100 | ONE_OR_MORE = '+' |
| 101 | PARSER = 'A...' |
| 102 | REMAINDER = '...' |
Steven Bethard | fca2e8a | 2010-11-02 12:47:22 +0000 | [diff] [blame] | 103 | _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 104 | |
| 105 | # ============================= |
| 106 | # Utility functions and classes |
| 107 | # ============================= |
| 108 | |
| 109 | class _AttributeHolder(object): |
| 110 | """Abstract base class that provides __repr__. |
| 111 | |
| 112 | The __repr__ method returns a string in the format:: |
| 113 | ClassName(attr=name, attr=name, ...) |
| 114 | The attributes are determined either by a class-level attribute, |
| 115 | '_kwarg_names', or by inspecting the instance __dict__. |
| 116 | """ |
| 117 | |
| 118 | def __repr__(self): |
| 119 | type_name = type(self).__name__ |
| 120 | arg_strings = [] |
Berker Peksag | 76b1714 | 2015-07-29 23:51:47 +0300 | [diff] [blame] | 121 | star_args = {} |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 122 | for arg in self._get_args(): |
| 123 | arg_strings.append(repr(arg)) |
| 124 | for name, value in self._get_kwargs(): |
Berker Peksag | 76b1714 | 2015-07-29 23:51:47 +0300 | [diff] [blame] | 125 | if name.isidentifier(): |
| 126 | arg_strings.append('%s=%r' % (name, value)) |
| 127 | else: |
| 128 | star_args[name] = value |
| 129 | if star_args: |
| 130 | arg_strings.append('**%s' % repr(star_args)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 131 | return '%s(%s)' % (type_name, ', '.join(arg_strings)) |
| 132 | |
| 133 | def _get_kwargs(self): |
Benjamin Peterson | 16f2fd0 | 2010-03-02 23:09:38 +0000 | [diff] [blame] | 134 | return sorted(self.__dict__.items()) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 135 | |
| 136 | def _get_args(self): |
| 137 | return [] |
| 138 | |
| 139 | |
| 140 | def _ensure_value(namespace, name, value): |
| 141 | if getattr(namespace, name, None) is None: |
| 142 | setattr(namespace, name, value) |
| 143 | return getattr(namespace, name) |
| 144 | |
| 145 | |
| 146 | # =============== |
| 147 | # Formatting Help |
| 148 | # =============== |
| 149 | |
| 150 | class HelpFormatter(object): |
| 151 | """Formatter for generating usage messages and argument help strings. |
| 152 | |
| 153 | Only the name of this class is considered a public API. All the methods |
| 154 | provided by the class are considered an implementation detail. |
| 155 | """ |
| 156 | |
| 157 | def __init__(self, |
| 158 | prog, |
| 159 | indent_increment=2, |
| 160 | max_help_position=24, |
| 161 | width=None): |
| 162 | |
| 163 | # default setting for width |
| 164 | if width is None: |
| 165 | try: |
| 166 | width = int(_os.environ['COLUMNS']) |
| 167 | except (KeyError, ValueError): |
| 168 | width = 80 |
| 169 | width -= 2 |
| 170 | |
| 171 | self._prog = prog |
| 172 | self._indent_increment = indent_increment |
| 173 | self._max_help_position = max_help_position |
Serhiy Storchaka | f451112 | 2014-01-09 23:14:27 +0200 | [diff] [blame] | 174 | self._max_help_position = min(max_help_position, |
| 175 | max(width - 20, indent_increment * 2)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 176 | self._width = width |
| 177 | |
| 178 | self._current_indent = 0 |
| 179 | self._level = 0 |
| 180 | self._action_max_length = 0 |
| 181 | |
| 182 | self._root_section = self._Section(self, None) |
| 183 | self._current_section = self._root_section |
| 184 | |
Xiang Zhang | 7fe28ad | 2017-01-22 14:37:22 +0800 | [diff] [blame] | 185 | self._whitespace_matcher = _re.compile(r'\s+', _re.ASCII) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 186 | self._long_break_matcher = _re.compile(r'\n\n\n+') |
| 187 | |
| 188 | # =============================== |
| 189 | # Section and indentation methods |
| 190 | # =============================== |
| 191 | def _indent(self): |
| 192 | self._current_indent += self._indent_increment |
| 193 | self._level += 1 |
| 194 | |
| 195 | def _dedent(self): |
| 196 | self._current_indent -= self._indent_increment |
| 197 | assert self._current_indent >= 0, 'Indent decreased below 0.' |
| 198 | self._level -= 1 |
| 199 | |
| 200 | class _Section(object): |
| 201 | |
| 202 | def __init__(self, formatter, parent, heading=None): |
| 203 | self.formatter = formatter |
| 204 | self.parent = parent |
| 205 | self.heading = heading |
| 206 | self.items = [] |
| 207 | |
| 208 | def format_help(self): |
| 209 | # format the indented section |
| 210 | if self.parent is not None: |
| 211 | self.formatter._indent() |
| 212 | join = self.formatter._join_parts |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 213 | item_help = join([func(*args) for func, args in self.items]) |
| 214 | if self.parent is not None: |
| 215 | self.formatter._dedent() |
| 216 | |
| 217 | # return nothing if the section was empty |
| 218 | if not item_help: |
| 219 | return '' |
| 220 | |
| 221 | # add the heading if the section was non-empty |
| 222 | if self.heading is not SUPPRESS and self.heading is not None: |
| 223 | current_indent = self.formatter._current_indent |
| 224 | heading = '%*s%s:\n' % (current_indent, '', self.heading) |
| 225 | else: |
| 226 | heading = '' |
| 227 | |
| 228 | # join the section-initial newline, the heading and the help |
| 229 | return join(['\n', heading, item_help, '\n']) |
| 230 | |
| 231 | def _add_item(self, func, args): |
| 232 | self._current_section.items.append((func, args)) |
| 233 | |
| 234 | # ======================== |
| 235 | # Message building methods |
| 236 | # ======================== |
| 237 | def start_section(self, heading): |
| 238 | self._indent() |
| 239 | section = self._Section(self, self._current_section, heading) |
| 240 | self._add_item(section.format_help, []) |
| 241 | self._current_section = section |
| 242 | |
| 243 | def end_section(self): |
| 244 | self._current_section = self._current_section.parent |
| 245 | self._dedent() |
| 246 | |
| 247 | def add_text(self, text): |
| 248 | if text is not SUPPRESS and text is not None: |
| 249 | self._add_item(self._format_text, [text]) |
| 250 | |
| 251 | def add_usage(self, usage, actions, groups, prefix=None): |
| 252 | if usage is not SUPPRESS: |
| 253 | args = usage, actions, groups, prefix |
| 254 | self._add_item(self._format_usage, args) |
| 255 | |
| 256 | def add_argument(self, action): |
| 257 | if action.help is not SUPPRESS: |
| 258 | |
| 259 | # find all invocations |
| 260 | get_invocation = self._format_action_invocation |
| 261 | invocations = [get_invocation(action)] |
| 262 | for subaction in self._iter_indented_subactions(action): |
| 263 | invocations.append(get_invocation(subaction)) |
| 264 | |
| 265 | # update the maximum item length |
| 266 | invocation_length = max([len(s) for s in invocations]) |
| 267 | action_length = invocation_length + self._current_indent |
| 268 | self._action_max_length = max(self._action_max_length, |
| 269 | action_length) |
| 270 | |
| 271 | # add the item to the list |
| 272 | self._add_item(self._format_action, [action]) |
| 273 | |
| 274 | def add_arguments(self, actions): |
| 275 | for action in actions: |
| 276 | self.add_argument(action) |
| 277 | |
| 278 | # ======================= |
| 279 | # Help-formatting methods |
| 280 | # ======================= |
| 281 | def format_help(self): |
| 282 | help = self._root_section.format_help() |
| 283 | if help: |
| 284 | help = self._long_break_matcher.sub('\n\n', help) |
| 285 | help = help.strip('\n') + '\n' |
| 286 | return help |
| 287 | |
| 288 | def _join_parts(self, part_strings): |
| 289 | return ''.join([part |
| 290 | for part in part_strings |
| 291 | if part and part is not SUPPRESS]) |
| 292 | |
| 293 | def _format_usage(self, usage, actions, groups, prefix): |
| 294 | if prefix is None: |
| 295 | prefix = _('usage: ') |
| 296 | |
| 297 | # if usage is specified, use that |
| 298 | if usage is not None: |
| 299 | usage = usage % dict(prog=self._prog) |
| 300 | |
| 301 | # if no optionals or positionals are available, usage is just prog |
| 302 | elif usage is None and not actions: |
| 303 | usage = '%(prog)s' % dict(prog=self._prog) |
| 304 | |
| 305 | # if optionals and positionals are available, calculate usage |
| 306 | elif usage is None: |
| 307 | prog = '%(prog)s' % dict(prog=self._prog) |
| 308 | |
| 309 | # split optionals from positionals |
| 310 | optionals = [] |
| 311 | positionals = [] |
| 312 | for action in actions: |
| 313 | if action.option_strings: |
| 314 | optionals.append(action) |
| 315 | else: |
| 316 | positionals.append(action) |
| 317 | |
| 318 | # build full usage string |
| 319 | format = self._format_actions_usage |
| 320 | action_usage = format(optionals + positionals, groups) |
| 321 | usage = ' '.join([s for s in [prog, action_usage] if s]) |
| 322 | |
| 323 | # wrap the usage parts if it's too long |
| 324 | text_width = self._width - self._current_indent |
| 325 | if len(prefix) + len(usage) > text_width: |
| 326 | |
| 327 | # break usage into wrappable parts |
| 328 | part_regexp = r'\(.*?\)+|\[.*?\]+|\S+' |
| 329 | opt_usage = format(optionals, groups) |
| 330 | pos_usage = format(positionals, groups) |
| 331 | opt_parts = _re.findall(part_regexp, opt_usage) |
| 332 | pos_parts = _re.findall(part_regexp, pos_usage) |
| 333 | assert ' '.join(opt_parts) == opt_usage |
| 334 | assert ' '.join(pos_parts) == pos_usage |
| 335 | |
| 336 | # helper for wrapping lines |
| 337 | def get_lines(parts, indent, prefix=None): |
| 338 | lines = [] |
| 339 | line = [] |
| 340 | if prefix is not None: |
| 341 | line_len = len(prefix) - 1 |
| 342 | else: |
| 343 | line_len = len(indent) - 1 |
| 344 | for part in parts: |
Serhiy Storchaka | f451112 | 2014-01-09 23:14:27 +0200 | [diff] [blame] | 345 | if line_len + 1 + len(part) > text_width and line: |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 346 | lines.append(indent + ' '.join(line)) |
| 347 | line = [] |
| 348 | line_len = len(indent) - 1 |
| 349 | line.append(part) |
| 350 | line_len += len(part) + 1 |
| 351 | if line: |
| 352 | lines.append(indent + ' '.join(line)) |
| 353 | if prefix is not None: |
| 354 | lines[0] = lines[0][len(indent):] |
| 355 | return lines |
| 356 | |
| 357 | # if prog is short, follow it with optionals or positionals |
| 358 | if len(prefix) + len(prog) <= 0.75 * text_width: |
| 359 | indent = ' ' * (len(prefix) + len(prog) + 1) |
| 360 | if opt_parts: |
| 361 | lines = get_lines([prog] + opt_parts, indent, prefix) |
| 362 | lines.extend(get_lines(pos_parts, indent)) |
| 363 | elif pos_parts: |
| 364 | lines = get_lines([prog] + pos_parts, indent, prefix) |
| 365 | else: |
| 366 | lines = [prog] |
| 367 | |
| 368 | # if prog is long, put it on its own line |
| 369 | else: |
| 370 | indent = ' ' * len(prefix) |
| 371 | parts = opt_parts + pos_parts |
| 372 | lines = get_lines(parts, indent) |
| 373 | if len(lines) > 1: |
| 374 | lines = [] |
| 375 | lines.extend(get_lines(opt_parts, indent)) |
| 376 | lines.extend(get_lines(pos_parts, indent)) |
| 377 | lines = [prog] + lines |
| 378 | |
| 379 | # join lines into usage |
| 380 | usage = '\n'.join(lines) |
| 381 | |
| 382 | # prefix with 'usage:' |
| 383 | return '%s%s\n\n' % (prefix, usage) |
| 384 | |
| 385 | def _format_actions_usage(self, actions, groups): |
| 386 | # find group indices and identify actions in groups |
Benjamin Peterson | 16f2fd0 | 2010-03-02 23:09:38 +0000 | [diff] [blame] | 387 | group_actions = set() |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 388 | inserts = {} |
| 389 | for group in groups: |
| 390 | try: |
| 391 | start = actions.index(group._group_actions[0]) |
| 392 | except ValueError: |
| 393 | continue |
| 394 | else: |
| 395 | end = start + len(group._group_actions) |
| 396 | if actions[start:end] == group._group_actions: |
| 397 | for action in group._group_actions: |
| 398 | group_actions.add(action) |
| 399 | if not group.required: |
Steven Bethard | 49998ee | 2010-11-01 16:29:26 +0000 | [diff] [blame] | 400 | if start in inserts: |
| 401 | inserts[start] += ' [' |
| 402 | else: |
| 403 | inserts[start] = '[' |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 404 | inserts[end] = ']' |
| 405 | else: |
Steven Bethard | 49998ee | 2010-11-01 16:29:26 +0000 | [diff] [blame] | 406 | if start in inserts: |
| 407 | inserts[start] += ' (' |
| 408 | else: |
| 409 | inserts[start] = '(' |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 410 | inserts[end] = ')' |
| 411 | for i in range(start + 1, end): |
| 412 | inserts[i] = '|' |
| 413 | |
| 414 | # collect all actions format strings |
| 415 | parts = [] |
| 416 | for i, action in enumerate(actions): |
| 417 | |
| 418 | # suppressed arguments are marked with None |
| 419 | # remove | separators for suppressed arguments |
| 420 | if action.help is SUPPRESS: |
| 421 | parts.append(None) |
| 422 | if inserts.get(i) == '|': |
| 423 | inserts.pop(i) |
| 424 | elif inserts.get(i + 1) == '|': |
| 425 | inserts.pop(i + 1) |
| 426 | |
| 427 | # produce all arg strings |
| 428 | elif not action.option_strings: |
Steven Bethard | 0331e90 | 2011-03-26 14:48:04 +0100 | [diff] [blame] | 429 | default = self._get_default_metavar_for_positional(action) |
| 430 | part = self._format_args(action, default) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 431 | |
| 432 | # if it's in a group, strip the outer [] |
| 433 | if action in group_actions: |
| 434 | if part[0] == '[' and part[-1] == ']': |
| 435 | part = part[1:-1] |
| 436 | |
| 437 | # add the action string to the list |
| 438 | parts.append(part) |
| 439 | |
| 440 | # produce the first way to invoke the option in brackets |
| 441 | else: |
| 442 | option_string = action.option_strings[0] |
| 443 | |
| 444 | # if the Optional doesn't take a value, format is: |
| 445 | # -s or --long |
| 446 | if action.nargs == 0: |
| 447 | part = '%s' % option_string |
| 448 | |
| 449 | # if the Optional takes a value, format is: |
| 450 | # -s ARGS or --long ARGS |
| 451 | else: |
Steven Bethard | 0331e90 | 2011-03-26 14:48:04 +0100 | [diff] [blame] | 452 | default = self._get_default_metavar_for_optional(action) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 453 | args_string = self._format_args(action, default) |
| 454 | part = '%s %s' % (option_string, args_string) |
| 455 | |
| 456 | # make it look optional if it's not required or in a group |
| 457 | if not action.required and action not in group_actions: |
| 458 | part = '[%s]' % part |
| 459 | |
| 460 | # add the action string to the list |
| 461 | parts.append(part) |
| 462 | |
| 463 | # insert things at the necessary indices |
Benjamin Peterson | 16f2fd0 | 2010-03-02 23:09:38 +0000 | [diff] [blame] | 464 | for i in sorted(inserts, reverse=True): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 465 | parts[i:i] = [inserts[i]] |
| 466 | |
| 467 | # join all the action items with spaces |
| 468 | text = ' '.join([item for item in parts if item is not None]) |
| 469 | |
| 470 | # clean up separators for mutually exclusive groups |
| 471 | open = r'[\[(]' |
| 472 | close = r'[\])]' |
| 473 | text = _re.sub(r'(%s) ' % open, r'\1', text) |
| 474 | text = _re.sub(r' (%s)' % close, r'\1', text) |
| 475 | text = _re.sub(r'%s *%s' % (open, close), r'', text) |
| 476 | text = _re.sub(r'\(([^|]*)\)', r'\1', text) |
| 477 | text = text.strip() |
| 478 | |
| 479 | # return the text |
| 480 | return text |
| 481 | |
| 482 | def _format_text(self, text): |
| 483 | if '%(prog)' in text: |
| 484 | text = text % dict(prog=self._prog) |
Serhiy Storchaka | f451112 | 2014-01-09 23:14:27 +0200 | [diff] [blame] | 485 | text_width = max(self._width - self._current_indent, 11) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 486 | indent = ' ' * self._current_indent |
| 487 | return self._fill_text(text, text_width, indent) + '\n\n' |
| 488 | |
| 489 | def _format_action(self, action): |
| 490 | # determine the required width and the entry label |
| 491 | help_position = min(self._action_max_length + 2, |
| 492 | self._max_help_position) |
Serhiy Storchaka | f451112 | 2014-01-09 23:14:27 +0200 | [diff] [blame] | 493 | help_width = max(self._width - help_position, 11) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 494 | action_width = help_position - self._current_indent - 2 |
| 495 | action_header = self._format_action_invocation(action) |
| 496 | |
Georg Brandl | 2514f52 | 2014-10-20 08:36:02 +0200 | [diff] [blame] | 497 | # no help; start on same line and add a final newline |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 498 | if not action.help: |
| 499 | tup = self._current_indent, '', action_header |
| 500 | action_header = '%*s%s\n' % tup |
| 501 | |
| 502 | # short action name; start on the same line and pad two spaces |
| 503 | elif len(action_header) <= action_width: |
| 504 | tup = self._current_indent, '', action_width, action_header |
| 505 | action_header = '%*s%-*s ' % tup |
| 506 | indent_first = 0 |
| 507 | |
| 508 | # long action name; start on the next line |
| 509 | else: |
| 510 | tup = self._current_indent, '', action_header |
| 511 | action_header = '%*s%s\n' % tup |
| 512 | indent_first = help_position |
| 513 | |
| 514 | # collect the pieces of the action help |
| 515 | parts = [action_header] |
| 516 | |
| 517 | # if there was help for the action, add lines of help text |
| 518 | if action.help: |
| 519 | help_text = self._expand_help(action) |
| 520 | help_lines = self._split_lines(help_text, help_width) |
| 521 | parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) |
| 522 | for line in help_lines[1:]: |
| 523 | parts.append('%*s%s\n' % (help_position, '', line)) |
| 524 | |
| 525 | # or add a newline if the description doesn't end with one |
| 526 | elif not action_header.endswith('\n'): |
| 527 | parts.append('\n') |
| 528 | |
| 529 | # if there are any sub-actions, add their help as well |
| 530 | for subaction in self._iter_indented_subactions(action): |
| 531 | parts.append(self._format_action(subaction)) |
| 532 | |
| 533 | # return a single string |
| 534 | return self._join_parts(parts) |
| 535 | |
| 536 | def _format_action_invocation(self, action): |
| 537 | if not action.option_strings: |
Steven Bethard | 0331e90 | 2011-03-26 14:48:04 +0100 | [diff] [blame] | 538 | default = self._get_default_metavar_for_positional(action) |
| 539 | metavar, = self._metavar_formatter(action, default)(1) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 540 | return metavar |
| 541 | |
| 542 | else: |
| 543 | parts = [] |
| 544 | |
| 545 | # if the Optional doesn't take a value, format is: |
| 546 | # -s, --long |
| 547 | if action.nargs == 0: |
| 548 | parts.extend(action.option_strings) |
| 549 | |
| 550 | # if the Optional takes a value, format is: |
| 551 | # -s ARGS, --long ARGS |
| 552 | else: |
Steven Bethard | 0331e90 | 2011-03-26 14:48:04 +0100 | [diff] [blame] | 553 | default = self._get_default_metavar_for_optional(action) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 554 | args_string = self._format_args(action, default) |
| 555 | for option_string in action.option_strings: |
| 556 | parts.append('%s %s' % (option_string, args_string)) |
| 557 | |
| 558 | return ', '.join(parts) |
| 559 | |
| 560 | def _metavar_formatter(self, action, default_metavar): |
| 561 | if action.metavar is not None: |
| 562 | result = action.metavar |
| 563 | elif action.choices is not None: |
| 564 | choice_strs = [str(choice) for choice in action.choices] |
| 565 | result = '{%s}' % ','.join(choice_strs) |
| 566 | else: |
| 567 | result = default_metavar |
| 568 | |
| 569 | def format(tuple_size): |
| 570 | if isinstance(result, tuple): |
| 571 | return result |
| 572 | else: |
| 573 | return (result, ) * tuple_size |
| 574 | return format |
| 575 | |
| 576 | def _format_args(self, action, default_metavar): |
| 577 | get_metavar = self._metavar_formatter(action, default_metavar) |
| 578 | if action.nargs is None: |
| 579 | result = '%s' % get_metavar(1) |
| 580 | elif action.nargs == OPTIONAL: |
| 581 | result = '[%s]' % get_metavar(1) |
| 582 | elif action.nargs == ZERO_OR_MORE: |
| 583 | result = '[%s [%s ...]]' % get_metavar(2) |
| 584 | elif action.nargs == ONE_OR_MORE: |
| 585 | result = '%s [%s ...]' % get_metavar(2) |
| 586 | elif action.nargs == REMAINDER: |
| 587 | result = '...' |
| 588 | elif action.nargs == PARSER: |
| 589 | result = '%s ...' % get_metavar(1) |
R. David Murray | 0f6b9d2 | 2017-09-06 20:25:40 -0400 | [diff] [blame] | 590 | elif action.nargs == SUPPRESS: |
| 591 | result = '' |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 592 | else: |
| 593 | formats = ['%s' for _ in range(action.nargs)] |
| 594 | result = ' '.join(formats) % get_metavar(action.nargs) |
| 595 | return result |
| 596 | |
| 597 | def _expand_help(self, action): |
| 598 | params = dict(vars(action), prog=self._prog) |
| 599 | for name in list(params): |
| 600 | if params[name] is SUPPRESS: |
| 601 | del params[name] |
| 602 | for name in list(params): |
| 603 | if hasattr(params[name], '__name__'): |
| 604 | params[name] = params[name].__name__ |
| 605 | if params.get('choices') is not None: |
| 606 | choices_str = ', '.join([str(c) for c in params['choices']]) |
| 607 | params['choices'] = choices_str |
| 608 | return self._get_help_string(action) % params |
| 609 | |
| 610 | def _iter_indented_subactions(self, action): |
| 611 | try: |
| 612 | get_subactions = action._get_subactions |
| 613 | except AttributeError: |
| 614 | pass |
| 615 | else: |
| 616 | self._indent() |
Philip Jenvey | 4993cc0 | 2012-10-01 12:53:43 -0700 | [diff] [blame] | 617 | yield from get_subactions() |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 618 | self._dedent() |
| 619 | |
| 620 | def _split_lines(self, text, width): |
| 621 | text = self._whitespace_matcher.sub(' ', text).strip() |
| 622 | return _textwrap.wrap(text, width) |
| 623 | |
| 624 | def _fill_text(self, text, width, indent): |
| 625 | text = self._whitespace_matcher.sub(' ', text).strip() |
| 626 | return _textwrap.fill(text, width, initial_indent=indent, |
| 627 | subsequent_indent=indent) |
| 628 | |
| 629 | def _get_help_string(self, action): |
| 630 | return action.help |
| 631 | |
Steven Bethard | 0331e90 | 2011-03-26 14:48:04 +0100 | [diff] [blame] | 632 | def _get_default_metavar_for_optional(self, action): |
| 633 | return action.dest.upper() |
| 634 | |
| 635 | def _get_default_metavar_for_positional(self, action): |
| 636 | return action.dest |
| 637 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 638 | |
| 639 | class RawDescriptionHelpFormatter(HelpFormatter): |
| 640 | """Help message formatter which retains any formatting in descriptions. |
| 641 | |
| 642 | Only the name of this class is considered a public API. All the methods |
| 643 | provided by the class are considered an implementation detail. |
| 644 | """ |
| 645 | |
| 646 | def _fill_text(self, text, width, indent): |
Ezio Melotti | d8b509b | 2011-09-28 17:37:55 +0300 | [diff] [blame] | 647 | return ''.join(indent + line for line in text.splitlines(keepends=True)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 648 | |
| 649 | |
| 650 | class RawTextHelpFormatter(RawDescriptionHelpFormatter): |
| 651 | """Help message formatter which retains formatting of all help text. |
| 652 | |
| 653 | Only the name of this class is considered a public API. All the methods |
| 654 | provided by the class are considered an implementation detail. |
| 655 | """ |
| 656 | |
| 657 | def _split_lines(self, text, width): |
| 658 | return text.splitlines() |
| 659 | |
| 660 | |
| 661 | class ArgumentDefaultsHelpFormatter(HelpFormatter): |
| 662 | """Help message formatter which adds default values to argument help. |
| 663 | |
| 664 | Only the name of this class is considered a public API. All the methods |
| 665 | provided by the class are considered an implementation detail. |
| 666 | """ |
| 667 | |
| 668 | def _get_help_string(self, action): |
| 669 | help = action.help |
| 670 | if '%(default)' not in action.help: |
| 671 | if action.default is not SUPPRESS: |
| 672 | defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] |
| 673 | if action.option_strings or action.nargs in defaulting_nargs: |
| 674 | help += ' (default: %(default)s)' |
| 675 | return help |
| 676 | |
| 677 | |
Steven Bethard | 0331e90 | 2011-03-26 14:48:04 +0100 | [diff] [blame] | 678 | class MetavarTypeHelpFormatter(HelpFormatter): |
| 679 | """Help message formatter which uses the argument 'type' as the default |
| 680 | metavar value (instead of the argument 'dest') |
| 681 | |
| 682 | Only the name of this class is considered a public API. All the methods |
| 683 | provided by the class are considered an implementation detail. |
| 684 | """ |
| 685 | |
| 686 | def _get_default_metavar_for_optional(self, action): |
| 687 | return action.type.__name__ |
| 688 | |
| 689 | def _get_default_metavar_for_positional(self, action): |
| 690 | return action.type.__name__ |
| 691 | |
| 692 | |
| 693 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 694 | # ===================== |
| 695 | # Options and Arguments |
| 696 | # ===================== |
| 697 | |
| 698 | def _get_action_name(argument): |
| 699 | if argument is None: |
| 700 | return None |
| 701 | elif argument.option_strings: |
| 702 | return '/'.join(argument.option_strings) |
| 703 | elif argument.metavar not in (None, SUPPRESS): |
| 704 | return argument.metavar |
| 705 | elif argument.dest not in (None, SUPPRESS): |
| 706 | return argument.dest |
| 707 | else: |
| 708 | return None |
| 709 | |
| 710 | |
| 711 | class ArgumentError(Exception): |
| 712 | """An error from creating or using an argument (optional or positional). |
| 713 | |
| 714 | The string value of this exception is the message, augmented with |
| 715 | information about the argument that caused it. |
| 716 | """ |
| 717 | |
| 718 | def __init__(self, argument, message): |
| 719 | self.argument_name = _get_action_name(argument) |
| 720 | self.message = message |
| 721 | |
| 722 | def __str__(self): |
| 723 | if self.argument_name is None: |
| 724 | format = '%(message)s' |
| 725 | else: |
| 726 | format = 'argument %(argument_name)s: %(message)s' |
| 727 | return format % dict(message=self.message, |
| 728 | argument_name=self.argument_name) |
| 729 | |
| 730 | |
| 731 | class ArgumentTypeError(Exception): |
| 732 | """An error from trying to convert a command line string to a type.""" |
| 733 | pass |
| 734 | |
| 735 | |
| 736 | # ============== |
| 737 | # Action classes |
| 738 | # ============== |
| 739 | |
| 740 | class Action(_AttributeHolder): |
| 741 | """Information about how to convert command line strings to Python objects. |
| 742 | |
| 743 | Action objects are used by an ArgumentParser to represent the information |
| 744 | needed to parse a single argument from one or more strings from the |
| 745 | command line. The keyword arguments to the Action constructor are also |
| 746 | all attributes of Action instances. |
| 747 | |
| 748 | Keyword Arguments: |
| 749 | |
| 750 | - option_strings -- A list of command-line option strings which |
| 751 | should be associated with this action. |
| 752 | |
| 753 | - dest -- The name of the attribute to hold the created object(s) |
| 754 | |
| 755 | - nargs -- The number of command-line arguments that should be |
| 756 | consumed. By default, one argument will be consumed and a single |
| 757 | value will be produced. Other values include: |
| 758 | - N (an integer) consumes N arguments (and produces a list) |
| 759 | - '?' consumes zero or one arguments |
| 760 | - '*' consumes zero or more arguments (and produces a list) |
| 761 | - '+' consumes one or more arguments (and produces a list) |
| 762 | Note that the difference between the default and nargs=1 is that |
| 763 | with the default, a single value will be produced, while with |
| 764 | nargs=1, a list containing a single value will be produced. |
| 765 | |
| 766 | - const -- The value to be produced if the option is specified and the |
| 767 | option uses an action that takes no values. |
| 768 | |
| 769 | - default -- The value to be produced if the option is not specified. |
| 770 | |
R David Murray | 15cd9a0 | 2012-07-21 17:04:25 -0400 | [diff] [blame] | 771 | - type -- A callable that accepts a single string argument, and |
| 772 | returns the converted value. The standard Python types str, int, |
| 773 | float, and complex are useful examples of such callables. If None, |
| 774 | str is used. |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 775 | |
| 776 | - choices -- A container of values that should be allowed. If not None, |
| 777 | after a command-line argument has been converted to the appropriate |
| 778 | type, an exception will be raised if it is not a member of this |
| 779 | collection. |
| 780 | |
| 781 | - required -- True if the action must always be specified at the |
| 782 | command line. This is only meaningful for optional command-line |
| 783 | arguments. |
| 784 | |
| 785 | - help -- The help string describing the argument. |
| 786 | |
| 787 | - metavar -- The name to be used for the option's argument with the |
| 788 | help string. If None, the 'dest' value will be used as the name. |
| 789 | """ |
| 790 | |
| 791 | def __init__(self, |
| 792 | option_strings, |
| 793 | dest, |
| 794 | nargs=None, |
| 795 | const=None, |
| 796 | default=None, |
| 797 | type=None, |
| 798 | choices=None, |
| 799 | required=False, |
| 800 | help=None, |
| 801 | metavar=None): |
| 802 | self.option_strings = option_strings |
| 803 | self.dest = dest |
| 804 | self.nargs = nargs |
| 805 | self.const = const |
| 806 | self.default = default |
| 807 | self.type = type |
| 808 | self.choices = choices |
| 809 | self.required = required |
| 810 | self.help = help |
| 811 | self.metavar = metavar |
| 812 | |
| 813 | def _get_kwargs(self): |
| 814 | names = [ |
| 815 | 'option_strings', |
| 816 | 'dest', |
| 817 | 'nargs', |
| 818 | 'const', |
| 819 | 'default', |
| 820 | 'type', |
| 821 | 'choices', |
| 822 | 'help', |
| 823 | 'metavar', |
| 824 | ] |
| 825 | return [(name, getattr(self, name)) for name in names] |
| 826 | |
| 827 | def __call__(self, parser, namespace, values, option_string=None): |
| 828 | raise NotImplementedError(_('.__call__() not defined')) |
| 829 | |
| 830 | |
| 831 | class _StoreAction(Action): |
| 832 | |
| 833 | def __init__(self, |
| 834 | option_strings, |
| 835 | dest, |
| 836 | nargs=None, |
| 837 | const=None, |
| 838 | default=None, |
| 839 | type=None, |
| 840 | choices=None, |
| 841 | required=False, |
| 842 | help=None, |
| 843 | metavar=None): |
| 844 | if nargs == 0: |
| 845 | raise ValueError('nargs for store actions must be > 0; if you ' |
| 846 | 'have nothing to store, actions such as store ' |
| 847 | 'true or store const may be more appropriate') |
| 848 | if const is not None and nargs != OPTIONAL: |
| 849 | raise ValueError('nargs must be %r to supply const' % OPTIONAL) |
| 850 | super(_StoreAction, self).__init__( |
| 851 | option_strings=option_strings, |
| 852 | dest=dest, |
| 853 | nargs=nargs, |
| 854 | const=const, |
| 855 | default=default, |
| 856 | type=type, |
| 857 | choices=choices, |
| 858 | required=required, |
| 859 | help=help, |
| 860 | metavar=metavar) |
| 861 | |
| 862 | def __call__(self, parser, namespace, values, option_string=None): |
| 863 | setattr(namespace, self.dest, values) |
| 864 | |
| 865 | |
| 866 | class _StoreConstAction(Action): |
| 867 | |
| 868 | def __init__(self, |
| 869 | option_strings, |
| 870 | dest, |
| 871 | const, |
| 872 | default=None, |
| 873 | required=False, |
| 874 | help=None, |
| 875 | metavar=None): |
| 876 | super(_StoreConstAction, self).__init__( |
| 877 | option_strings=option_strings, |
| 878 | dest=dest, |
| 879 | nargs=0, |
| 880 | const=const, |
| 881 | default=default, |
| 882 | required=required, |
| 883 | help=help) |
| 884 | |
| 885 | def __call__(self, parser, namespace, values, option_string=None): |
| 886 | setattr(namespace, self.dest, self.const) |
| 887 | |
| 888 | |
| 889 | class _StoreTrueAction(_StoreConstAction): |
| 890 | |
| 891 | def __init__(self, |
| 892 | option_strings, |
| 893 | dest, |
| 894 | default=False, |
| 895 | required=False, |
| 896 | help=None): |
| 897 | super(_StoreTrueAction, self).__init__( |
| 898 | option_strings=option_strings, |
| 899 | dest=dest, |
| 900 | const=True, |
| 901 | default=default, |
| 902 | required=required, |
| 903 | help=help) |
| 904 | |
| 905 | |
| 906 | class _StoreFalseAction(_StoreConstAction): |
| 907 | |
| 908 | def __init__(self, |
| 909 | option_strings, |
| 910 | dest, |
| 911 | default=True, |
| 912 | required=False, |
| 913 | help=None): |
| 914 | super(_StoreFalseAction, self).__init__( |
| 915 | option_strings=option_strings, |
| 916 | dest=dest, |
| 917 | const=False, |
| 918 | default=default, |
| 919 | required=required, |
| 920 | help=help) |
| 921 | |
| 922 | |
| 923 | class _AppendAction(Action): |
| 924 | |
| 925 | def __init__(self, |
| 926 | option_strings, |
| 927 | dest, |
| 928 | nargs=None, |
| 929 | const=None, |
| 930 | default=None, |
| 931 | type=None, |
| 932 | choices=None, |
| 933 | required=False, |
| 934 | help=None, |
| 935 | metavar=None): |
| 936 | if nargs == 0: |
| 937 | raise ValueError('nargs for append actions must be > 0; if arg ' |
| 938 | 'strings are not supplying the value to append, ' |
| 939 | 'the append const action may be more appropriate') |
| 940 | if const is not None and nargs != OPTIONAL: |
| 941 | raise ValueError('nargs must be %r to supply const' % OPTIONAL) |
| 942 | super(_AppendAction, self).__init__( |
| 943 | option_strings=option_strings, |
| 944 | dest=dest, |
| 945 | nargs=nargs, |
| 946 | const=const, |
| 947 | default=default, |
| 948 | type=type, |
| 949 | choices=choices, |
| 950 | required=required, |
| 951 | help=help, |
| 952 | metavar=metavar) |
| 953 | |
| 954 | def __call__(self, parser, namespace, values, option_string=None): |
| 955 | items = _copy.copy(_ensure_value(namespace, self.dest, [])) |
| 956 | items.append(values) |
| 957 | setattr(namespace, self.dest, items) |
| 958 | |
| 959 | |
| 960 | class _AppendConstAction(Action): |
| 961 | |
| 962 | def __init__(self, |
| 963 | option_strings, |
| 964 | dest, |
| 965 | const, |
| 966 | default=None, |
| 967 | required=False, |
| 968 | help=None, |
| 969 | metavar=None): |
| 970 | super(_AppendConstAction, self).__init__( |
| 971 | option_strings=option_strings, |
| 972 | dest=dest, |
| 973 | nargs=0, |
| 974 | const=const, |
| 975 | default=default, |
| 976 | required=required, |
| 977 | help=help, |
| 978 | metavar=metavar) |
| 979 | |
| 980 | def __call__(self, parser, namespace, values, option_string=None): |
| 981 | items = _copy.copy(_ensure_value(namespace, self.dest, [])) |
| 982 | items.append(self.const) |
| 983 | setattr(namespace, self.dest, items) |
| 984 | |
| 985 | |
| 986 | class _CountAction(Action): |
| 987 | |
| 988 | def __init__(self, |
| 989 | option_strings, |
| 990 | dest, |
| 991 | default=None, |
| 992 | required=False, |
| 993 | help=None): |
| 994 | super(_CountAction, self).__init__( |
| 995 | option_strings=option_strings, |
| 996 | dest=dest, |
| 997 | nargs=0, |
| 998 | default=default, |
| 999 | required=required, |
| 1000 | help=help) |
| 1001 | |
| 1002 | def __call__(self, parser, namespace, values, option_string=None): |
| 1003 | new_count = _ensure_value(namespace, self.dest, 0) + 1 |
| 1004 | setattr(namespace, self.dest, new_count) |
| 1005 | |
| 1006 | |
| 1007 | class _HelpAction(Action): |
| 1008 | |
| 1009 | def __init__(self, |
| 1010 | option_strings, |
| 1011 | dest=SUPPRESS, |
| 1012 | default=SUPPRESS, |
| 1013 | help=None): |
| 1014 | super(_HelpAction, self).__init__( |
| 1015 | option_strings=option_strings, |
| 1016 | dest=dest, |
| 1017 | default=default, |
| 1018 | nargs=0, |
| 1019 | help=help) |
| 1020 | |
| 1021 | def __call__(self, parser, namespace, values, option_string=None): |
| 1022 | parser.print_help() |
| 1023 | parser.exit() |
| 1024 | |
| 1025 | |
| 1026 | class _VersionAction(Action): |
| 1027 | |
| 1028 | def __init__(self, |
| 1029 | option_strings, |
| 1030 | version=None, |
| 1031 | dest=SUPPRESS, |
| 1032 | default=SUPPRESS, |
Steven Bethard | 50fe593 | 2010-05-24 03:47:38 +0000 | [diff] [blame] | 1033 | help="show program's version number and exit"): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1034 | super(_VersionAction, self).__init__( |
| 1035 | option_strings=option_strings, |
| 1036 | dest=dest, |
| 1037 | default=default, |
| 1038 | nargs=0, |
| 1039 | help=help) |
| 1040 | self.version = version |
| 1041 | |
| 1042 | def __call__(self, parser, namespace, values, option_string=None): |
| 1043 | version = self.version |
| 1044 | if version is None: |
| 1045 | version = parser.version |
| 1046 | formatter = parser._get_formatter() |
| 1047 | formatter.add_text(version) |
Eli Bendersky | cdac551 | 2013-09-06 06:49:15 -0700 | [diff] [blame] | 1048 | parser._print_message(formatter.format_help(), _sys.stdout) |
| 1049 | parser.exit() |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1050 | |
| 1051 | |
| 1052 | class _SubParsersAction(Action): |
| 1053 | |
| 1054 | class _ChoicesPseudoAction(Action): |
| 1055 | |
Steven Bethard | fd311a7 | 2010-12-18 11:19:23 +0000 | [diff] [blame] | 1056 | def __init__(self, name, aliases, help): |
| 1057 | metavar = dest = name |
| 1058 | if aliases: |
| 1059 | metavar += ' (%s)' % ', '.join(aliases) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1060 | sup = super(_SubParsersAction._ChoicesPseudoAction, self) |
Steven Bethard | fd311a7 | 2010-12-18 11:19:23 +0000 | [diff] [blame] | 1061 | sup.__init__(option_strings=[], dest=dest, help=help, |
| 1062 | metavar=metavar) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1063 | |
| 1064 | def __init__(self, |
| 1065 | option_strings, |
| 1066 | prog, |
| 1067 | parser_class, |
| 1068 | dest=SUPPRESS, |
Anthony Sottile | aaf6fc0 | 2017-09-20 14:35:27 -0700 | [diff] [blame] | 1069 | required=True, |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1070 | help=None, |
| 1071 | metavar=None): |
| 1072 | |
| 1073 | self._prog_prefix = prog |
| 1074 | self._parser_class = parser_class |
Steven Bethard | 8a6a198 | 2011-03-27 13:53:53 +0200 | [diff] [blame] | 1075 | self._name_parser_map = _collections.OrderedDict() |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1076 | self._choices_actions = [] |
| 1077 | |
| 1078 | super(_SubParsersAction, self).__init__( |
| 1079 | option_strings=option_strings, |
| 1080 | dest=dest, |
| 1081 | nargs=PARSER, |
| 1082 | choices=self._name_parser_map, |
Anthony Sottile | aaf6fc0 | 2017-09-20 14:35:27 -0700 | [diff] [blame] | 1083 | required=required, |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1084 | help=help, |
| 1085 | metavar=metavar) |
| 1086 | |
| 1087 | def add_parser(self, name, **kwargs): |
| 1088 | # set prog from the existing prefix |
| 1089 | if kwargs.get('prog') is None: |
| 1090 | kwargs['prog'] = '%s %s' % (self._prog_prefix, name) |
| 1091 | |
Steven Bethard | fd311a7 | 2010-12-18 11:19:23 +0000 | [diff] [blame] | 1092 | aliases = kwargs.pop('aliases', ()) |
| 1093 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1094 | # create a pseudo-action to hold the choice help |
| 1095 | if 'help' in kwargs: |
| 1096 | help = kwargs.pop('help') |
Steven Bethard | fd311a7 | 2010-12-18 11:19:23 +0000 | [diff] [blame] | 1097 | choice_action = self._ChoicesPseudoAction(name, aliases, help) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1098 | self._choices_actions.append(choice_action) |
| 1099 | |
| 1100 | # create the parser and add it to the map |
| 1101 | parser = self._parser_class(**kwargs) |
| 1102 | self._name_parser_map[name] = parser |
Steven Bethard | fd311a7 | 2010-12-18 11:19:23 +0000 | [diff] [blame] | 1103 | |
| 1104 | # make parser available under aliases also |
| 1105 | for alias in aliases: |
| 1106 | self._name_parser_map[alias] = parser |
| 1107 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1108 | return parser |
| 1109 | |
| 1110 | def _get_subactions(self): |
| 1111 | return self._choices_actions |
| 1112 | |
| 1113 | def __call__(self, parser, namespace, values, option_string=None): |
| 1114 | parser_name = values[0] |
| 1115 | arg_strings = values[1:] |
| 1116 | |
| 1117 | # set the parser name if requested |
| 1118 | if self.dest is not SUPPRESS: |
| 1119 | setattr(namespace, self.dest, parser_name) |
| 1120 | |
| 1121 | # select the parser |
| 1122 | try: |
| 1123 | parser = self._name_parser_map[parser_name] |
| 1124 | except KeyError: |
Éric Araujo | bb48a8b | 2010-12-03 19:41:00 +0000 | [diff] [blame] | 1125 | args = {'parser_name': parser_name, |
| 1126 | 'choices': ', '.join(self._name_parser_map)} |
| 1127 | msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1128 | raise ArgumentError(self, msg) |
| 1129 | |
| 1130 | # parse all the remaining options into the namespace |
Steven Bethard | fca2e8a | 2010-11-02 12:47:22 +0000 | [diff] [blame] | 1131 | # store any unrecognized options on the object, so that the top |
| 1132 | # level parser can decide what to do with them |
R David Murray | 7570cbd | 2014-10-17 19:55:11 -0400 | [diff] [blame] | 1133 | |
| 1134 | # In case this subparser defines new defaults, we parse them |
| 1135 | # in a new namespace object and then update the original |
| 1136 | # namespace for the relevant parts. |
| 1137 | subnamespace, arg_strings = parser.parse_known_args(arg_strings, None) |
| 1138 | for key, value in vars(subnamespace).items(): |
| 1139 | setattr(namespace, key, value) |
| 1140 | |
Steven Bethard | fca2e8a | 2010-11-02 12:47:22 +0000 | [diff] [blame] | 1141 | if arg_strings: |
| 1142 | vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, []) |
| 1143 | getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1144 | |
| 1145 | |
| 1146 | # ============== |
| 1147 | # Type classes |
| 1148 | # ============== |
| 1149 | |
| 1150 | class FileType(object): |
| 1151 | """Factory for creating file object types |
| 1152 | |
| 1153 | Instances of FileType are typically passed as type= arguments to the |
| 1154 | ArgumentParser add_argument() method. |
| 1155 | |
| 1156 | Keyword Arguments: |
| 1157 | - mode -- A string indicating how the file is to be opened. Accepts the |
| 1158 | same values as the builtin open() function. |
| 1159 | - bufsize -- The file's desired buffer size. Accepts the same values as |
| 1160 | the builtin open() function. |
Petri Lehtinen | 74d6c25 | 2012-12-15 22:39:32 +0200 | [diff] [blame] | 1161 | - encoding -- The file's encoding. Accepts the same values as the |
Terry Jan Reedy | 8e7586b | 2013-03-11 18:38:13 -0400 | [diff] [blame] | 1162 | builtin open() function. |
Petri Lehtinen | 74d6c25 | 2012-12-15 22:39:32 +0200 | [diff] [blame] | 1163 | - errors -- A string indicating how encoding and decoding errors are to |
| 1164 | be handled. Accepts the same value as the builtin open() function. |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1165 | """ |
| 1166 | |
Petri Lehtinen | 74d6c25 | 2012-12-15 22:39:32 +0200 | [diff] [blame] | 1167 | def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1168 | self._mode = mode |
| 1169 | self._bufsize = bufsize |
Petri Lehtinen | 74d6c25 | 2012-12-15 22:39:32 +0200 | [diff] [blame] | 1170 | self._encoding = encoding |
| 1171 | self._errors = errors |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1172 | |
| 1173 | def __call__(self, string): |
| 1174 | # the special argument "-" means sys.std{in,out} |
| 1175 | if string == '-': |
| 1176 | if 'r' in self._mode: |
| 1177 | return _sys.stdin |
| 1178 | elif 'w' in self._mode: |
| 1179 | return _sys.stdout |
| 1180 | else: |
Éric Araujo | a9c7a8f | 2010-12-03 19:19:17 +0000 | [diff] [blame] | 1181 | msg = _('argument "-" with mode %r') % self._mode |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1182 | raise ValueError(msg) |
| 1183 | |
| 1184 | # all other arguments are used as file names |
Steven Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 1185 | try: |
Petri Lehtinen | 74d6c25 | 2012-12-15 22:39:32 +0200 | [diff] [blame] | 1186 | return open(string, self._mode, self._bufsize, self._encoding, |
| 1187 | self._errors) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 1188 | except OSError as e: |
Steven Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 1189 | message = _("can't open '%s': %s") |
| 1190 | raise ArgumentTypeError(message % (string, e)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1191 | |
| 1192 | def __repr__(self): |
Steven Bethard | b027011 | 2011-01-24 21:02:50 +0000 | [diff] [blame] | 1193 | args = self._mode, self._bufsize |
Petri Lehtinen | 74d6c25 | 2012-12-15 22:39:32 +0200 | [diff] [blame] | 1194 | kwargs = [('encoding', self._encoding), ('errors', self._errors)] |
| 1195 | args_str = ', '.join([repr(arg) for arg in args if arg != -1] + |
| 1196 | ['%s=%r' % (kw, arg) for kw, arg in kwargs |
| 1197 | if arg is not None]) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1198 | return '%s(%s)' % (type(self).__name__, args_str) |
| 1199 | |
| 1200 | # =========================== |
| 1201 | # Optional and Positional Parsing |
| 1202 | # =========================== |
| 1203 | |
| 1204 | class Namespace(_AttributeHolder): |
| 1205 | """Simple object for storing attributes. |
| 1206 | |
| 1207 | Implements equality by attribute names and values, and provides a simple |
| 1208 | string representation. |
| 1209 | """ |
| 1210 | |
| 1211 | def __init__(self, **kwargs): |
| 1212 | for name in kwargs: |
| 1213 | setattr(self, name, kwargs[name]) |
| 1214 | |
| 1215 | def __eq__(self, other): |
Raymond Hettinger | dea46ec | 2014-05-26 00:43:27 -0700 | [diff] [blame] | 1216 | if not isinstance(other, Namespace): |
| 1217 | return NotImplemented |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1218 | return vars(self) == vars(other) |
| 1219 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1220 | def __contains__(self, key): |
| 1221 | return key in self.__dict__ |
| 1222 | |
| 1223 | |
| 1224 | class _ActionsContainer(object): |
| 1225 | |
| 1226 | def __init__(self, |
| 1227 | description, |
| 1228 | prefix_chars, |
| 1229 | argument_default, |
| 1230 | conflict_handler): |
| 1231 | super(_ActionsContainer, self).__init__() |
| 1232 | |
| 1233 | self.description = description |
| 1234 | self.argument_default = argument_default |
| 1235 | self.prefix_chars = prefix_chars |
| 1236 | self.conflict_handler = conflict_handler |
| 1237 | |
| 1238 | # set up registries |
| 1239 | self._registries = {} |
| 1240 | |
| 1241 | # register actions |
| 1242 | self.register('action', None, _StoreAction) |
| 1243 | self.register('action', 'store', _StoreAction) |
| 1244 | self.register('action', 'store_const', _StoreConstAction) |
| 1245 | self.register('action', 'store_true', _StoreTrueAction) |
| 1246 | self.register('action', 'store_false', _StoreFalseAction) |
| 1247 | self.register('action', 'append', _AppendAction) |
| 1248 | self.register('action', 'append_const', _AppendConstAction) |
| 1249 | self.register('action', 'count', _CountAction) |
| 1250 | self.register('action', 'help', _HelpAction) |
| 1251 | self.register('action', 'version', _VersionAction) |
| 1252 | self.register('action', 'parsers', _SubParsersAction) |
| 1253 | |
| 1254 | # raise an exception if the conflict handler is invalid |
| 1255 | self._get_handler() |
| 1256 | |
| 1257 | # action storage |
| 1258 | self._actions = [] |
| 1259 | self._option_string_actions = {} |
| 1260 | |
| 1261 | # groups |
| 1262 | self._action_groups = [] |
| 1263 | self._mutually_exclusive_groups = [] |
| 1264 | |
| 1265 | # defaults storage |
| 1266 | self._defaults = {} |
| 1267 | |
| 1268 | # determines whether an "option" looks like a negative number |
| 1269 | self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$') |
| 1270 | |
| 1271 | # whether or not there are any optionals that look like negative |
| 1272 | # numbers -- uses a list so it can be shared and edited |
| 1273 | self._has_negative_number_optionals = [] |
| 1274 | |
| 1275 | # ==================== |
| 1276 | # Registration methods |
| 1277 | # ==================== |
| 1278 | def register(self, registry_name, value, object): |
| 1279 | registry = self._registries.setdefault(registry_name, {}) |
| 1280 | registry[value] = object |
| 1281 | |
| 1282 | def _registry_get(self, registry_name, value, default=None): |
| 1283 | return self._registries[registry_name].get(value, default) |
| 1284 | |
| 1285 | # ================================== |
| 1286 | # Namespace default accessor methods |
| 1287 | # ================================== |
| 1288 | def set_defaults(self, **kwargs): |
| 1289 | self._defaults.update(kwargs) |
| 1290 | |
| 1291 | # if these defaults match any existing arguments, replace |
| 1292 | # the previous default on the object with the new one |
| 1293 | for action in self._actions: |
| 1294 | if action.dest in kwargs: |
| 1295 | action.default = kwargs[action.dest] |
| 1296 | |
| 1297 | def get_default(self, dest): |
| 1298 | for action in self._actions: |
| 1299 | if action.dest == dest and action.default is not None: |
| 1300 | return action.default |
| 1301 | return self._defaults.get(dest, None) |
| 1302 | |
| 1303 | |
| 1304 | # ======================= |
| 1305 | # Adding argument actions |
| 1306 | # ======================= |
| 1307 | def add_argument(self, *args, **kwargs): |
| 1308 | """ |
| 1309 | add_argument(dest, ..., name=value, ...) |
| 1310 | add_argument(option_string, option_string, ..., name=value, ...) |
| 1311 | """ |
| 1312 | |
| 1313 | # if no positional args are supplied or only one is supplied and |
| 1314 | # it doesn't look like an option string, parse a positional |
| 1315 | # argument |
| 1316 | chars = self.prefix_chars |
| 1317 | if not args or len(args) == 1 and args[0][0] not in chars: |
| 1318 | if args and 'dest' in kwargs: |
| 1319 | raise ValueError('dest supplied twice for positional argument') |
| 1320 | kwargs = self._get_positional_kwargs(*args, **kwargs) |
| 1321 | |
| 1322 | # otherwise, we're adding an optional argument |
| 1323 | else: |
| 1324 | kwargs = self._get_optional_kwargs(*args, **kwargs) |
| 1325 | |
| 1326 | # if no default was supplied, use the parser-level default |
| 1327 | if 'default' not in kwargs: |
| 1328 | dest = kwargs['dest'] |
| 1329 | if dest in self._defaults: |
| 1330 | kwargs['default'] = self._defaults[dest] |
| 1331 | elif self.argument_default is not None: |
| 1332 | kwargs['default'] = self.argument_default |
| 1333 | |
| 1334 | # create the action object, and add it to the parser |
| 1335 | action_class = self._pop_action_class(kwargs) |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 1336 | if not callable(action_class): |
Steven Bethard | 7cb20a8 | 2011-04-04 01:53:02 +0200 | [diff] [blame] | 1337 | raise ValueError('unknown action "%s"' % (action_class,)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1338 | action = action_class(**kwargs) |
| 1339 | |
| 1340 | # raise an error if the action type is not callable |
| 1341 | type_func = self._registry_get('type', action.type, action.type) |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 1342 | if not callable(type_func): |
Steven Bethard | 7cb20a8 | 2011-04-04 01:53:02 +0200 | [diff] [blame] | 1343 | raise ValueError('%r is not callable' % (type_func,)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1344 | |
Steven Bethard | 8d9a462 | 2011-03-26 17:33:56 +0100 | [diff] [blame] | 1345 | # raise an error if the metavar does not match the type |
| 1346 | if hasattr(self, "_get_formatter"): |
| 1347 | try: |
| 1348 | self._get_formatter()._format_args(action, None) |
| 1349 | except TypeError: |
| 1350 | raise ValueError("length of metavar tuple does not match nargs") |
| 1351 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1352 | return self._add_action(action) |
| 1353 | |
| 1354 | def add_argument_group(self, *args, **kwargs): |
| 1355 | group = _ArgumentGroup(self, *args, **kwargs) |
| 1356 | self._action_groups.append(group) |
| 1357 | return group |
| 1358 | |
| 1359 | def add_mutually_exclusive_group(self, **kwargs): |
| 1360 | group = _MutuallyExclusiveGroup(self, **kwargs) |
| 1361 | self._mutually_exclusive_groups.append(group) |
| 1362 | return group |
| 1363 | |
| 1364 | def _add_action(self, action): |
| 1365 | # resolve any conflicts |
| 1366 | self._check_conflict(action) |
| 1367 | |
| 1368 | # add to actions list |
| 1369 | self._actions.append(action) |
| 1370 | action.container = self |
| 1371 | |
| 1372 | # index the action by any option strings it has |
| 1373 | for option_string in action.option_strings: |
| 1374 | self._option_string_actions[option_string] = action |
| 1375 | |
| 1376 | # set the flag if any option strings look like negative numbers |
| 1377 | for option_string in action.option_strings: |
| 1378 | if self._negative_number_matcher.match(option_string): |
| 1379 | if not self._has_negative_number_optionals: |
| 1380 | self._has_negative_number_optionals.append(True) |
| 1381 | |
| 1382 | # return the created action |
| 1383 | return action |
| 1384 | |
| 1385 | def _remove_action(self, action): |
| 1386 | self._actions.remove(action) |
| 1387 | |
| 1388 | def _add_container_actions(self, container): |
| 1389 | # collect groups by titles |
| 1390 | title_group_map = {} |
| 1391 | for group in self._action_groups: |
| 1392 | if group.title in title_group_map: |
| 1393 | msg = _('cannot merge actions - two groups are named %r') |
| 1394 | raise ValueError(msg % (group.title)) |
| 1395 | title_group_map[group.title] = group |
| 1396 | |
| 1397 | # map each action to its group |
| 1398 | group_map = {} |
| 1399 | for group in container._action_groups: |
| 1400 | |
| 1401 | # if a group with the title exists, use that, otherwise |
| 1402 | # create a new group matching the container's group |
| 1403 | if group.title not in title_group_map: |
| 1404 | title_group_map[group.title] = self.add_argument_group( |
| 1405 | title=group.title, |
| 1406 | description=group.description, |
| 1407 | conflict_handler=group.conflict_handler) |
| 1408 | |
| 1409 | # map the actions to their new group |
| 1410 | for action in group._group_actions: |
| 1411 | group_map[action] = title_group_map[group.title] |
| 1412 | |
| 1413 | # add container's mutually exclusive groups |
| 1414 | # NOTE: if add_mutually_exclusive_group ever gains title= and |
| 1415 | # description= then this code will need to be expanded as above |
| 1416 | for group in container._mutually_exclusive_groups: |
| 1417 | mutex_group = self.add_mutually_exclusive_group( |
| 1418 | required=group.required) |
| 1419 | |
| 1420 | # map the actions to their new mutex group |
| 1421 | for action in group._group_actions: |
| 1422 | group_map[action] = mutex_group |
| 1423 | |
| 1424 | # add all actions to this container or their group |
| 1425 | for action in container._actions: |
| 1426 | group_map.get(action, self)._add_action(action) |
| 1427 | |
| 1428 | def _get_positional_kwargs(self, dest, **kwargs): |
| 1429 | # make sure required is not specified |
| 1430 | if 'required' in kwargs: |
| 1431 | msg = _("'required' is an invalid argument for positionals") |
| 1432 | raise TypeError(msg) |
| 1433 | |
| 1434 | # mark positional arguments as required if at least one is |
| 1435 | # always required |
| 1436 | if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]: |
| 1437 | kwargs['required'] = True |
| 1438 | if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs: |
| 1439 | kwargs['required'] = True |
| 1440 | |
| 1441 | # return the keyword arguments with no option strings |
| 1442 | return dict(kwargs, dest=dest, option_strings=[]) |
| 1443 | |
| 1444 | def _get_optional_kwargs(self, *args, **kwargs): |
| 1445 | # determine short and long option strings |
| 1446 | option_strings = [] |
| 1447 | long_option_strings = [] |
| 1448 | for option_string in args: |
| 1449 | # error on strings that don't start with an appropriate prefix |
| 1450 | if not option_string[0] in self.prefix_chars: |
Éric Araujo | bb48a8b | 2010-12-03 19:41:00 +0000 | [diff] [blame] | 1451 | args = {'option': option_string, |
| 1452 | 'prefix_chars': self.prefix_chars} |
| 1453 | msg = _('invalid option string %(option)r: ' |
| 1454 | 'must start with a character %(prefix_chars)r') |
| 1455 | raise ValueError(msg % args) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1456 | |
| 1457 | # strings starting with two prefix characters are long options |
| 1458 | option_strings.append(option_string) |
| 1459 | if option_string[0] in self.prefix_chars: |
| 1460 | if len(option_string) > 1: |
| 1461 | if option_string[1] in self.prefix_chars: |
| 1462 | long_option_strings.append(option_string) |
| 1463 | |
| 1464 | # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' |
| 1465 | dest = kwargs.pop('dest', None) |
| 1466 | if dest is None: |
| 1467 | if long_option_strings: |
| 1468 | dest_option_string = long_option_strings[0] |
| 1469 | else: |
| 1470 | dest_option_string = option_strings[0] |
| 1471 | dest = dest_option_string.lstrip(self.prefix_chars) |
| 1472 | if not dest: |
| 1473 | msg = _('dest= is required for options like %r') |
| 1474 | raise ValueError(msg % option_string) |
| 1475 | dest = dest.replace('-', '_') |
| 1476 | |
| 1477 | # return the updated keyword arguments |
| 1478 | return dict(kwargs, dest=dest, option_strings=option_strings) |
| 1479 | |
| 1480 | def _pop_action_class(self, kwargs, default=None): |
| 1481 | action = kwargs.pop('action', default) |
| 1482 | return self._registry_get('action', action, action) |
| 1483 | |
| 1484 | def _get_handler(self): |
| 1485 | # determine function from conflict handler string |
| 1486 | handler_func_name = '_handle_conflict_%s' % self.conflict_handler |
| 1487 | try: |
| 1488 | return getattr(self, handler_func_name) |
| 1489 | except AttributeError: |
| 1490 | msg = _('invalid conflict_resolution value: %r') |
| 1491 | raise ValueError(msg % self.conflict_handler) |
| 1492 | |
| 1493 | def _check_conflict(self, action): |
| 1494 | |
| 1495 | # find all options that conflict with this option |
| 1496 | confl_optionals = [] |
| 1497 | for option_string in action.option_strings: |
| 1498 | if option_string in self._option_string_actions: |
| 1499 | confl_optional = self._option_string_actions[option_string] |
| 1500 | confl_optionals.append((option_string, confl_optional)) |
| 1501 | |
| 1502 | # resolve any conflicts |
| 1503 | if confl_optionals: |
| 1504 | conflict_handler = self._get_handler() |
| 1505 | conflict_handler(action, confl_optionals) |
| 1506 | |
| 1507 | def _handle_conflict_error(self, action, conflicting_actions): |
Éric Araujo | 1215915 | 2010-12-04 17:31:49 +0000 | [diff] [blame] | 1508 | message = ngettext('conflicting option string: %s', |
| 1509 | 'conflicting option strings: %s', |
| 1510 | len(conflicting_actions)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1511 | conflict_string = ', '.join([option_string |
| 1512 | for option_string, action |
| 1513 | in conflicting_actions]) |
| 1514 | raise ArgumentError(action, message % conflict_string) |
| 1515 | |
| 1516 | def _handle_conflict_resolve(self, action, conflicting_actions): |
| 1517 | |
| 1518 | # remove all conflicting options |
| 1519 | for option_string, action in conflicting_actions: |
| 1520 | |
| 1521 | # remove the conflicting option |
| 1522 | action.option_strings.remove(option_string) |
| 1523 | self._option_string_actions.pop(option_string, None) |
| 1524 | |
| 1525 | # if the option now has no option string, remove it from the |
| 1526 | # container holding it |
| 1527 | if not action.option_strings: |
| 1528 | action.container._remove_action(action) |
| 1529 | |
| 1530 | |
| 1531 | class _ArgumentGroup(_ActionsContainer): |
| 1532 | |
| 1533 | def __init__(self, container, title=None, description=None, **kwargs): |
| 1534 | # add any missing keyword arguments by checking the container |
| 1535 | update = kwargs.setdefault |
| 1536 | update('conflict_handler', container.conflict_handler) |
| 1537 | update('prefix_chars', container.prefix_chars) |
| 1538 | update('argument_default', container.argument_default) |
| 1539 | super_init = super(_ArgumentGroup, self).__init__ |
| 1540 | super_init(description=description, **kwargs) |
| 1541 | |
| 1542 | # group attributes |
| 1543 | self.title = title |
| 1544 | self._group_actions = [] |
| 1545 | |
| 1546 | # share most attributes with the container |
| 1547 | self._registries = container._registries |
| 1548 | self._actions = container._actions |
| 1549 | self._option_string_actions = container._option_string_actions |
| 1550 | self._defaults = container._defaults |
| 1551 | self._has_negative_number_optionals = \ |
| 1552 | container._has_negative_number_optionals |
Georg Brandl | 0f6b47a | 2011-01-30 12:19:35 +0000 | [diff] [blame] | 1553 | self._mutually_exclusive_groups = container._mutually_exclusive_groups |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1554 | |
| 1555 | def _add_action(self, action): |
| 1556 | action = super(_ArgumentGroup, self)._add_action(action) |
| 1557 | self._group_actions.append(action) |
| 1558 | return action |
| 1559 | |
| 1560 | def _remove_action(self, action): |
| 1561 | super(_ArgumentGroup, self)._remove_action(action) |
| 1562 | self._group_actions.remove(action) |
| 1563 | |
| 1564 | |
| 1565 | class _MutuallyExclusiveGroup(_ArgumentGroup): |
| 1566 | |
| 1567 | def __init__(self, container, required=False): |
| 1568 | super(_MutuallyExclusiveGroup, self).__init__(container) |
| 1569 | self.required = required |
| 1570 | self._container = container |
| 1571 | |
| 1572 | def _add_action(self, action): |
| 1573 | if action.required: |
| 1574 | msg = _('mutually exclusive arguments must be optional') |
| 1575 | raise ValueError(msg) |
| 1576 | action = self._container._add_action(action) |
| 1577 | self._group_actions.append(action) |
| 1578 | return action |
| 1579 | |
| 1580 | def _remove_action(self, action): |
| 1581 | self._container._remove_action(action) |
| 1582 | self._group_actions.remove(action) |
| 1583 | |
| 1584 | |
| 1585 | class ArgumentParser(_AttributeHolder, _ActionsContainer): |
| 1586 | """Object for parsing command line strings into Python objects. |
| 1587 | |
| 1588 | Keyword Arguments: |
| 1589 | - prog -- The name of the program (default: sys.argv[0]) |
| 1590 | - usage -- A usage message (default: auto-generated from arguments) |
| 1591 | - description -- A description of what the program does |
| 1592 | - epilog -- Text following the argument descriptions |
| 1593 | - parents -- Parsers whose arguments should be copied into this one |
| 1594 | - formatter_class -- HelpFormatter class for printing help messages |
| 1595 | - prefix_chars -- Characters that prefix optional arguments |
| 1596 | - fromfile_prefix_chars -- Characters that prefix files containing |
| 1597 | additional arguments |
| 1598 | - argument_default -- The default value for all arguments |
| 1599 | - conflict_handler -- String indicating how to handle conflicts |
| 1600 | - add_help -- Add a -h/-help option |
Berker Peksag | 8089cd6 | 2015-02-14 01:39:17 +0200 | [diff] [blame] | 1601 | - allow_abbrev -- Allow long options to be abbreviated unambiguously |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1602 | """ |
| 1603 | |
| 1604 | def __init__(self, |
| 1605 | prog=None, |
| 1606 | usage=None, |
| 1607 | description=None, |
| 1608 | epilog=None, |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1609 | parents=[], |
| 1610 | formatter_class=HelpFormatter, |
| 1611 | prefix_chars='-', |
| 1612 | fromfile_prefix_chars=None, |
| 1613 | argument_default=None, |
| 1614 | conflict_handler='error', |
Berker Peksag | 8089cd6 | 2015-02-14 01:39:17 +0200 | [diff] [blame] | 1615 | add_help=True, |
| 1616 | allow_abbrev=True): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1617 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1618 | superinit = super(ArgumentParser, self).__init__ |
| 1619 | superinit(description=description, |
| 1620 | prefix_chars=prefix_chars, |
| 1621 | argument_default=argument_default, |
| 1622 | conflict_handler=conflict_handler) |
| 1623 | |
| 1624 | # default setting for prog |
| 1625 | if prog is None: |
| 1626 | prog = _os.path.basename(_sys.argv[0]) |
| 1627 | |
| 1628 | self.prog = prog |
| 1629 | self.usage = usage |
| 1630 | self.epilog = epilog |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1631 | self.formatter_class = formatter_class |
| 1632 | self.fromfile_prefix_chars = fromfile_prefix_chars |
| 1633 | self.add_help = add_help |
Berker Peksag | 8089cd6 | 2015-02-14 01:39:17 +0200 | [diff] [blame] | 1634 | self.allow_abbrev = allow_abbrev |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1635 | |
| 1636 | add_group = self.add_argument_group |
| 1637 | self._positionals = add_group(_('positional arguments')) |
| 1638 | self._optionals = add_group(_('optional arguments')) |
| 1639 | self._subparsers = None |
| 1640 | |
| 1641 | # register types |
| 1642 | def identity(string): |
| 1643 | return string |
| 1644 | self.register('type', None, identity) |
| 1645 | |
Florent Xicluna | af1adbe | 2012-07-07 17:02:22 +0200 | [diff] [blame] | 1646 | # add help argument if necessary |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1647 | # (using explicit default to override global argument_default) |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 1648 | default_prefix = '-' if '-' in prefix_chars else prefix_chars[0] |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1649 | if self.add_help: |
| 1650 | self.add_argument( |
R. David Murray | 88c49fe | 2010-08-03 17:56:09 +0000 | [diff] [blame] | 1651 | default_prefix+'h', default_prefix*2+'help', |
| 1652 | action='help', default=SUPPRESS, |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1653 | help=_('show this help message and exit')) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1654 | |
| 1655 | # add parent arguments and defaults |
| 1656 | for parent in parents: |
| 1657 | self._add_container_actions(parent) |
| 1658 | try: |
| 1659 | defaults = parent._defaults |
| 1660 | except AttributeError: |
| 1661 | pass |
| 1662 | else: |
| 1663 | self._defaults.update(defaults) |
| 1664 | |
| 1665 | # ======================= |
| 1666 | # Pretty __repr__ methods |
| 1667 | # ======================= |
| 1668 | def _get_kwargs(self): |
| 1669 | names = [ |
| 1670 | 'prog', |
| 1671 | 'usage', |
| 1672 | 'description', |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1673 | 'formatter_class', |
| 1674 | 'conflict_handler', |
| 1675 | 'add_help', |
| 1676 | ] |
| 1677 | return [(name, getattr(self, name)) for name in names] |
| 1678 | |
| 1679 | # ================================== |
| 1680 | # Optional/Positional adding methods |
| 1681 | # ================================== |
| 1682 | def add_subparsers(self, **kwargs): |
| 1683 | if self._subparsers is not None: |
| 1684 | self.error(_('cannot have multiple subparser arguments')) |
| 1685 | |
| 1686 | # add the parser class to the arguments if it's not present |
| 1687 | kwargs.setdefault('parser_class', type(self)) |
| 1688 | |
| 1689 | if 'title' in kwargs or 'description' in kwargs: |
| 1690 | title = _(kwargs.pop('title', 'subcommands')) |
| 1691 | description = _(kwargs.pop('description', None)) |
| 1692 | self._subparsers = self.add_argument_group(title, description) |
| 1693 | else: |
| 1694 | self._subparsers = self._positionals |
| 1695 | |
| 1696 | # prog defaults to the usage message of this parser, skipping |
| 1697 | # optional arguments and with no "usage:" prefix |
| 1698 | if kwargs.get('prog') is None: |
| 1699 | formatter = self._get_formatter() |
| 1700 | positionals = self._get_positional_actions() |
| 1701 | groups = self._mutually_exclusive_groups |
| 1702 | formatter.add_usage(self.usage, positionals, groups, '') |
| 1703 | kwargs['prog'] = formatter.format_help().strip() |
| 1704 | |
| 1705 | # create the parsers action and add it to the positionals list |
| 1706 | parsers_class = self._pop_action_class(kwargs, 'parsers') |
| 1707 | action = parsers_class(option_strings=[], **kwargs) |
| 1708 | self._subparsers._add_action(action) |
| 1709 | |
| 1710 | # return the created parsers action |
| 1711 | return action |
| 1712 | |
| 1713 | def _add_action(self, action): |
| 1714 | if action.option_strings: |
| 1715 | self._optionals._add_action(action) |
| 1716 | else: |
| 1717 | self._positionals._add_action(action) |
| 1718 | return action |
| 1719 | |
| 1720 | def _get_optional_actions(self): |
| 1721 | return [action |
| 1722 | for action in self._actions |
| 1723 | if action.option_strings] |
| 1724 | |
| 1725 | def _get_positional_actions(self): |
| 1726 | return [action |
| 1727 | for action in self._actions |
| 1728 | if not action.option_strings] |
| 1729 | |
| 1730 | # ===================================== |
| 1731 | # Command line argument parsing methods |
| 1732 | # ===================================== |
| 1733 | def parse_args(self, args=None, namespace=None): |
| 1734 | args, argv = self.parse_known_args(args, namespace) |
| 1735 | if argv: |
| 1736 | msg = _('unrecognized arguments: %s') |
| 1737 | self.error(msg % ' '.join(argv)) |
| 1738 | return args |
| 1739 | |
| 1740 | def parse_known_args(self, args=None, namespace=None): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1741 | if args is None: |
R David Murray | b522828 | 2012-09-08 12:08:01 -0400 | [diff] [blame] | 1742 | # args default to the system args |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1743 | args = _sys.argv[1:] |
R David Murray | b522828 | 2012-09-08 12:08:01 -0400 | [diff] [blame] | 1744 | else: |
| 1745 | # make sure that args are mutable |
| 1746 | args = list(args) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1747 | |
| 1748 | # default Namespace built from parser defaults |
| 1749 | if namespace is None: |
| 1750 | namespace = Namespace() |
| 1751 | |
| 1752 | # add any action defaults that aren't present |
| 1753 | for action in self._actions: |
| 1754 | if action.dest is not SUPPRESS: |
| 1755 | if not hasattr(namespace, action.dest): |
| 1756 | if action.default is not SUPPRESS: |
R David Murray | 6fb8fb1 | 2012-08-31 22:45:20 -0400 | [diff] [blame] | 1757 | setattr(namespace, action.dest, action.default) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1758 | |
| 1759 | # add any parser defaults that aren't present |
| 1760 | for dest in self._defaults: |
| 1761 | if not hasattr(namespace, dest): |
| 1762 | setattr(namespace, dest, self._defaults[dest]) |
| 1763 | |
| 1764 | # parse the arguments and exit if there are any errors |
| 1765 | try: |
Steven Bethard | fca2e8a | 2010-11-02 12:47:22 +0000 | [diff] [blame] | 1766 | namespace, args = self._parse_known_args(args, namespace) |
| 1767 | if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR): |
| 1768 | args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) |
| 1769 | delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) |
| 1770 | return namespace, args |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1771 | except ArgumentError: |
| 1772 | err = _sys.exc_info()[1] |
| 1773 | self.error(str(err)) |
| 1774 | |
| 1775 | def _parse_known_args(self, arg_strings, namespace): |
| 1776 | # replace arg strings that are file references |
| 1777 | if self.fromfile_prefix_chars is not None: |
| 1778 | arg_strings = self._read_args_from_files(arg_strings) |
| 1779 | |
| 1780 | # map all mutually exclusive arguments to the other arguments |
| 1781 | # they can't occur with |
| 1782 | action_conflicts = {} |
| 1783 | for mutex_group in self._mutually_exclusive_groups: |
| 1784 | group_actions = mutex_group._group_actions |
| 1785 | for i, mutex_action in enumerate(mutex_group._group_actions): |
| 1786 | conflicts = action_conflicts.setdefault(mutex_action, []) |
| 1787 | conflicts.extend(group_actions[:i]) |
| 1788 | conflicts.extend(group_actions[i + 1:]) |
| 1789 | |
| 1790 | # find all option indices, and determine the arg_string_pattern |
| 1791 | # which has an 'O' if there is an option at an index, |
| 1792 | # an 'A' if there is an argument, or a '-' if there is a '--' |
| 1793 | option_string_indices = {} |
| 1794 | arg_string_pattern_parts = [] |
| 1795 | arg_strings_iter = iter(arg_strings) |
| 1796 | for i, arg_string in enumerate(arg_strings_iter): |
| 1797 | |
| 1798 | # all args after -- are non-options |
| 1799 | if arg_string == '--': |
| 1800 | arg_string_pattern_parts.append('-') |
| 1801 | for arg_string in arg_strings_iter: |
| 1802 | arg_string_pattern_parts.append('A') |
| 1803 | |
| 1804 | # otherwise, add the arg to the arg strings |
| 1805 | # and note the index if it was an option |
| 1806 | else: |
| 1807 | option_tuple = self._parse_optional(arg_string) |
| 1808 | if option_tuple is None: |
| 1809 | pattern = 'A' |
| 1810 | else: |
| 1811 | option_string_indices[i] = option_tuple |
| 1812 | pattern = 'O' |
| 1813 | arg_string_pattern_parts.append(pattern) |
| 1814 | |
| 1815 | # join the pieces together to form the pattern |
| 1816 | arg_strings_pattern = ''.join(arg_string_pattern_parts) |
| 1817 | |
| 1818 | # converts arg strings to the appropriate and then takes the action |
Benjamin Peterson | 16f2fd0 | 2010-03-02 23:09:38 +0000 | [diff] [blame] | 1819 | seen_actions = set() |
| 1820 | seen_non_default_actions = set() |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1821 | |
| 1822 | def take_action(action, argument_strings, option_string=None): |
| 1823 | seen_actions.add(action) |
| 1824 | argument_values = self._get_values(action, argument_strings) |
| 1825 | |
| 1826 | # error if this argument is not allowed with other previously |
| 1827 | # seen arguments, assuming that actions that use the default |
| 1828 | # value don't really count as "present" |
| 1829 | if argument_values is not action.default: |
| 1830 | seen_non_default_actions.add(action) |
| 1831 | for conflict_action in action_conflicts.get(action, []): |
| 1832 | if conflict_action in seen_non_default_actions: |
| 1833 | msg = _('not allowed with argument %s') |
| 1834 | action_name = _get_action_name(conflict_action) |
| 1835 | raise ArgumentError(action, msg % action_name) |
| 1836 | |
| 1837 | # take the action if we didn't receive a SUPPRESS value |
| 1838 | # (e.g. from a default) |
| 1839 | if argument_values is not SUPPRESS: |
| 1840 | action(self, namespace, argument_values, option_string) |
| 1841 | |
| 1842 | # function to convert arg_strings into an optional action |
| 1843 | def consume_optional(start_index): |
| 1844 | |
| 1845 | # get the optional identified at this index |
| 1846 | option_tuple = option_string_indices[start_index] |
| 1847 | action, option_string, explicit_arg = option_tuple |
| 1848 | |
| 1849 | # identify additional optionals in the same arg string |
| 1850 | # (e.g. -xyz is the same as -x -y -z if no args are required) |
| 1851 | match_argument = self._match_argument |
| 1852 | action_tuples = [] |
| 1853 | while True: |
| 1854 | |
| 1855 | # if we found no optional action, skip it |
| 1856 | if action is None: |
| 1857 | extras.append(arg_strings[start_index]) |
| 1858 | return start_index + 1 |
| 1859 | |
| 1860 | # if there is an explicit argument, try to match the |
| 1861 | # optional's string arguments to only this |
| 1862 | if explicit_arg is not None: |
| 1863 | arg_count = match_argument(action, 'A') |
| 1864 | |
| 1865 | # if the action is a single-dash option and takes no |
| 1866 | # arguments, try to parse more single-dash options out |
| 1867 | # of the tail of the option string |
| 1868 | chars = self.prefix_chars |
| 1869 | if arg_count == 0 and option_string[1] not in chars: |
| 1870 | action_tuples.append((action, [], option_string)) |
Steven Bethard | 1ca45a5 | 2010-11-01 15:57:36 +0000 | [diff] [blame] | 1871 | char = option_string[0] |
| 1872 | option_string = char + explicit_arg[0] |
| 1873 | new_explicit_arg = explicit_arg[1:] or None |
| 1874 | optionals_map = self._option_string_actions |
| 1875 | if option_string in optionals_map: |
| 1876 | action = optionals_map[option_string] |
| 1877 | explicit_arg = new_explicit_arg |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1878 | else: |
| 1879 | msg = _('ignored explicit argument %r') |
| 1880 | raise ArgumentError(action, msg % explicit_arg) |
| 1881 | |
| 1882 | # if the action expect exactly one argument, we've |
| 1883 | # successfully matched the option; exit the loop |
| 1884 | elif arg_count == 1: |
| 1885 | stop = start_index + 1 |
| 1886 | args = [explicit_arg] |
| 1887 | action_tuples.append((action, args, option_string)) |
| 1888 | break |
| 1889 | |
| 1890 | # error if a double-dash option did not use the |
| 1891 | # explicit argument |
| 1892 | else: |
| 1893 | msg = _('ignored explicit argument %r') |
| 1894 | raise ArgumentError(action, msg % explicit_arg) |
| 1895 | |
| 1896 | # if there is no explicit argument, try to match the |
| 1897 | # optional's string arguments with the following strings |
| 1898 | # if successful, exit the loop |
| 1899 | else: |
| 1900 | start = start_index + 1 |
| 1901 | selected_patterns = arg_strings_pattern[start:] |
| 1902 | arg_count = match_argument(action, selected_patterns) |
| 1903 | stop = start + arg_count |
| 1904 | args = arg_strings[start:stop] |
| 1905 | action_tuples.append((action, args, option_string)) |
| 1906 | break |
| 1907 | |
| 1908 | # add the Optional to the list and return the index at which |
| 1909 | # the Optional's string args stopped |
| 1910 | assert action_tuples |
| 1911 | for action, args, option_string in action_tuples: |
| 1912 | take_action(action, args, option_string) |
| 1913 | return stop |
| 1914 | |
| 1915 | # the list of Positionals left to be parsed; this is modified |
| 1916 | # by consume_positionals() |
| 1917 | positionals = self._get_positional_actions() |
| 1918 | |
| 1919 | # function to convert arg_strings into positional actions |
| 1920 | def consume_positionals(start_index): |
| 1921 | # match as many Positionals as possible |
| 1922 | match_partial = self._match_arguments_partial |
| 1923 | selected_pattern = arg_strings_pattern[start_index:] |
| 1924 | arg_counts = match_partial(positionals, selected_pattern) |
| 1925 | |
| 1926 | # slice off the appropriate arg strings for each Positional |
| 1927 | # and add the Positional and its args to the list |
| 1928 | for action, arg_count in zip(positionals, arg_counts): |
| 1929 | args = arg_strings[start_index: start_index + arg_count] |
| 1930 | start_index += arg_count |
| 1931 | take_action(action, args) |
| 1932 | |
| 1933 | # slice off the Positionals that we just parsed and return the |
| 1934 | # index at which the Positionals' string args stopped |
| 1935 | positionals[:] = positionals[len(arg_counts):] |
| 1936 | return start_index |
| 1937 | |
| 1938 | # consume Positionals and Optionals alternately, until we have |
| 1939 | # passed the last option string |
| 1940 | extras = [] |
| 1941 | start_index = 0 |
| 1942 | if option_string_indices: |
| 1943 | max_option_string_index = max(option_string_indices) |
| 1944 | else: |
| 1945 | max_option_string_index = -1 |
| 1946 | while start_index <= max_option_string_index: |
| 1947 | |
| 1948 | # consume any Positionals preceding the next option |
| 1949 | next_option_string_index = min([ |
| 1950 | index |
| 1951 | for index in option_string_indices |
| 1952 | if index >= start_index]) |
| 1953 | if start_index != next_option_string_index: |
| 1954 | positionals_end_index = consume_positionals(start_index) |
| 1955 | |
| 1956 | # only try to parse the next optional if we didn't consume |
| 1957 | # the option string during the positionals parsing |
| 1958 | if positionals_end_index > start_index: |
| 1959 | start_index = positionals_end_index |
| 1960 | continue |
| 1961 | else: |
| 1962 | start_index = positionals_end_index |
| 1963 | |
| 1964 | # if we consumed all the positionals we could and we're not |
| 1965 | # at the index of an option string, there were extra arguments |
| 1966 | if start_index not in option_string_indices: |
| 1967 | strings = arg_strings[start_index:next_option_string_index] |
| 1968 | extras.extend(strings) |
| 1969 | start_index = next_option_string_index |
| 1970 | |
| 1971 | # consume the next optional and any arguments for it |
| 1972 | start_index = consume_optional(start_index) |
| 1973 | |
| 1974 | # consume any positionals following the last Optional |
| 1975 | stop_index = consume_positionals(start_index) |
| 1976 | |
| 1977 | # if we didn't consume all the argument strings, there were extras |
| 1978 | extras.extend(arg_strings[stop_index:]) |
| 1979 | |
R David Murray | 64b0ef1 | 2012-08-31 23:09:34 -0400 | [diff] [blame] | 1980 | # make sure all required actions were present and also convert |
| 1981 | # action defaults which were not given as arguments |
| 1982 | required_actions = [] |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1983 | for action in self._actions: |
R David Murray | 6fb8fb1 | 2012-08-31 22:45:20 -0400 | [diff] [blame] | 1984 | if action not in seen_actions: |
| 1985 | if action.required: |
R David Murray | 64b0ef1 | 2012-08-31 23:09:34 -0400 | [diff] [blame] | 1986 | required_actions.append(_get_action_name(action)) |
R David Murray | 6fb8fb1 | 2012-08-31 22:45:20 -0400 | [diff] [blame] | 1987 | else: |
| 1988 | # Convert action default now instead of doing it before |
| 1989 | # parsing arguments to avoid calling convert functions |
| 1990 | # twice (which may fail) if the argument was given, but |
| 1991 | # only if it was defined already in the namespace |
| 1992 | if (action.default is not None and |
Barry Warsaw | d89774e | 2012-09-12 15:31:38 -0400 | [diff] [blame] | 1993 | isinstance(action.default, str) and |
R David Murray | 64b0ef1 | 2012-08-31 23:09:34 -0400 | [diff] [blame] | 1994 | hasattr(namespace, action.dest) and |
| 1995 | action.default is getattr(namespace, action.dest)): |
R David Murray | 6fb8fb1 | 2012-08-31 22:45:20 -0400 | [diff] [blame] | 1996 | setattr(namespace, action.dest, |
| 1997 | self._get_value(action, action.default)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 1998 | |
R David Murray | f97c59a | 2011-06-09 12:34:07 -0400 | [diff] [blame] | 1999 | if required_actions: |
| 2000 | self.error(_('the following arguments are required: %s') % |
| 2001 | ', '.join(required_actions)) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2002 | |
| 2003 | # make sure all required groups had one option present |
| 2004 | for group in self._mutually_exclusive_groups: |
| 2005 | if group.required: |
| 2006 | for action in group._group_actions: |
| 2007 | if action in seen_non_default_actions: |
| 2008 | break |
| 2009 | |
| 2010 | # if no actions were used, report the error |
| 2011 | else: |
| 2012 | names = [_get_action_name(action) |
| 2013 | for action in group._group_actions |
| 2014 | if action.help is not SUPPRESS] |
| 2015 | msg = _('one of the arguments %s is required') |
| 2016 | self.error(msg % ' '.join(names)) |
| 2017 | |
| 2018 | # return the updated namespace and the extra arguments |
| 2019 | return namespace, extras |
| 2020 | |
| 2021 | def _read_args_from_files(self, arg_strings): |
| 2022 | # expand arguments referencing files |
| 2023 | new_arg_strings = [] |
| 2024 | for arg_string in arg_strings: |
| 2025 | |
| 2026 | # for regular arguments, just add them back into the list |
R David Murray | b94082a | 2012-07-21 22:20:11 -0400 | [diff] [blame] | 2027 | if not arg_string or arg_string[0] not in self.fromfile_prefix_chars: |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2028 | new_arg_strings.append(arg_string) |
| 2029 | |
| 2030 | # replace arguments referencing files with the file content |
| 2031 | else: |
| 2032 | try: |
Giampaolo Rodola' | 2f50aaf | 2013-02-12 02:04:27 +0100 | [diff] [blame] | 2033 | with open(arg_string[1:]) as args_file: |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2034 | arg_strings = [] |
| 2035 | for arg_line in args_file.read().splitlines(): |
| 2036 | for arg in self.convert_arg_line_to_args(arg_line): |
| 2037 | arg_strings.append(arg) |
| 2038 | arg_strings = self._read_args_from_files(arg_strings) |
| 2039 | new_arg_strings.extend(arg_strings) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 2040 | except OSError: |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2041 | err = _sys.exc_info()[1] |
| 2042 | self.error(str(err)) |
| 2043 | |
| 2044 | # return the modified argument list |
| 2045 | return new_arg_strings |
| 2046 | |
| 2047 | def convert_arg_line_to_args(self, arg_line): |
| 2048 | return [arg_line] |
| 2049 | |
| 2050 | def _match_argument(self, action, arg_strings_pattern): |
| 2051 | # match the pattern for this action to the arg strings |
| 2052 | nargs_pattern = self._get_nargs_pattern(action) |
| 2053 | match = _re.match(nargs_pattern, arg_strings_pattern) |
| 2054 | |
| 2055 | # raise an exception if we weren't able to find a match |
| 2056 | if match is None: |
| 2057 | nargs_errors = { |
| 2058 | None: _('expected one argument'), |
| 2059 | OPTIONAL: _('expected at most one argument'), |
| 2060 | ONE_OR_MORE: _('expected at least one argument'), |
| 2061 | } |
Éric Araujo | 1215915 | 2010-12-04 17:31:49 +0000 | [diff] [blame] | 2062 | default = ngettext('expected %s argument', |
| 2063 | 'expected %s arguments', |
| 2064 | action.nargs) % action.nargs |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2065 | msg = nargs_errors.get(action.nargs, default) |
| 2066 | raise ArgumentError(action, msg) |
| 2067 | |
| 2068 | # return the number of arguments matched |
| 2069 | return len(match.group(1)) |
| 2070 | |
| 2071 | def _match_arguments_partial(self, actions, arg_strings_pattern): |
| 2072 | # progressively shorten the actions list by slicing off the |
| 2073 | # final actions until we find a match |
| 2074 | result = [] |
| 2075 | for i in range(len(actions), 0, -1): |
| 2076 | actions_slice = actions[:i] |
| 2077 | pattern = ''.join([self._get_nargs_pattern(action) |
| 2078 | for action in actions_slice]) |
| 2079 | match = _re.match(pattern, arg_strings_pattern) |
| 2080 | if match is not None: |
| 2081 | result.extend([len(string) for string in match.groups()]) |
| 2082 | break |
| 2083 | |
| 2084 | # return the list of arg string counts |
| 2085 | return result |
| 2086 | |
| 2087 | def _parse_optional(self, arg_string): |
| 2088 | # if it's an empty string, it was meant to be a positional |
| 2089 | if not arg_string: |
| 2090 | return None |
| 2091 | |
| 2092 | # if it doesn't start with a prefix, it was meant to be positional |
| 2093 | if not arg_string[0] in self.prefix_chars: |
| 2094 | return None |
| 2095 | |
| 2096 | # if the option string is present in the parser, return the action |
| 2097 | if arg_string in self._option_string_actions: |
| 2098 | action = self._option_string_actions[arg_string] |
| 2099 | return action, arg_string, None |
| 2100 | |
| 2101 | # if it's just a single character, it was meant to be positional |
| 2102 | if len(arg_string) == 1: |
| 2103 | return None |
| 2104 | |
| 2105 | # if the option string before the "=" is present, return the action |
| 2106 | if '=' in arg_string: |
| 2107 | option_string, explicit_arg = arg_string.split('=', 1) |
| 2108 | if option_string in self._option_string_actions: |
| 2109 | action = self._option_string_actions[option_string] |
| 2110 | return action, option_string, explicit_arg |
| 2111 | |
Berker Peksag | 8089cd6 | 2015-02-14 01:39:17 +0200 | [diff] [blame] | 2112 | if self.allow_abbrev: |
| 2113 | # search through all possible prefixes of the option string |
| 2114 | # and all actions in the parser for possible interpretations |
| 2115 | option_tuples = self._get_option_tuples(arg_string) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2116 | |
Berker Peksag | 8089cd6 | 2015-02-14 01:39:17 +0200 | [diff] [blame] | 2117 | # if multiple actions match, the option string was ambiguous |
| 2118 | if len(option_tuples) > 1: |
| 2119 | options = ', '.join([option_string |
| 2120 | for action, option_string, explicit_arg in option_tuples]) |
| 2121 | args = {'option': arg_string, 'matches': options} |
| 2122 | msg = _('ambiguous option: %(option)s could match %(matches)s') |
| 2123 | self.error(msg % args) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2124 | |
Berker Peksag | 8089cd6 | 2015-02-14 01:39:17 +0200 | [diff] [blame] | 2125 | # if exactly one action matched, this segmentation is good, |
| 2126 | # so return the parsed action |
| 2127 | elif len(option_tuples) == 1: |
| 2128 | option_tuple, = option_tuples |
| 2129 | return option_tuple |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2130 | |
| 2131 | # if it was not found as an option, but it looks like a negative |
| 2132 | # number, it was meant to be positional |
| 2133 | # unless there are negative-number-like options |
| 2134 | if self._negative_number_matcher.match(arg_string): |
| 2135 | if not self._has_negative_number_optionals: |
| 2136 | return None |
| 2137 | |
| 2138 | # if it contains a space, it was meant to be a positional |
| 2139 | if ' ' in arg_string: |
| 2140 | return None |
| 2141 | |
| 2142 | # it was meant to be an optional but there is no such option |
| 2143 | # in this parser (though it might be a valid option in a subparser) |
| 2144 | return None, arg_string, None |
| 2145 | |
| 2146 | def _get_option_tuples(self, option_string): |
| 2147 | result = [] |
| 2148 | |
| 2149 | # option strings starting with two prefix characters are only |
| 2150 | # split at the '=' |
| 2151 | chars = self.prefix_chars |
| 2152 | if option_string[0] in chars and option_string[1] in chars: |
| 2153 | if '=' in option_string: |
| 2154 | option_prefix, explicit_arg = option_string.split('=', 1) |
| 2155 | else: |
| 2156 | option_prefix = option_string |
| 2157 | explicit_arg = None |
| 2158 | for option_string in self._option_string_actions: |
| 2159 | if option_string.startswith(option_prefix): |
| 2160 | action = self._option_string_actions[option_string] |
| 2161 | tup = action, option_string, explicit_arg |
| 2162 | result.append(tup) |
| 2163 | |
| 2164 | # single character options can be concatenated with their arguments |
| 2165 | # but multiple character options always have to have their argument |
| 2166 | # separate |
| 2167 | elif option_string[0] in chars and option_string[1] not in chars: |
| 2168 | option_prefix = option_string |
| 2169 | explicit_arg = None |
| 2170 | short_option_prefix = option_string[:2] |
| 2171 | short_explicit_arg = option_string[2:] |
| 2172 | |
| 2173 | for option_string in self._option_string_actions: |
| 2174 | if option_string == short_option_prefix: |
| 2175 | action = self._option_string_actions[option_string] |
| 2176 | tup = action, option_string, short_explicit_arg |
| 2177 | result.append(tup) |
| 2178 | elif option_string.startswith(option_prefix): |
| 2179 | action = self._option_string_actions[option_string] |
| 2180 | tup = action, option_string, explicit_arg |
| 2181 | result.append(tup) |
| 2182 | |
| 2183 | # shouldn't ever get here |
| 2184 | else: |
| 2185 | self.error(_('unexpected option string: %s') % option_string) |
| 2186 | |
| 2187 | # return the collected option tuples |
| 2188 | return result |
| 2189 | |
| 2190 | def _get_nargs_pattern(self, action): |
| 2191 | # in all examples below, we have to allow for '--' args |
| 2192 | # which are represented as '-' in the pattern |
| 2193 | nargs = action.nargs |
| 2194 | |
| 2195 | # the default (None) is assumed to be a single argument |
| 2196 | if nargs is None: |
| 2197 | nargs_pattern = '(-*A-*)' |
| 2198 | |
| 2199 | # allow zero or one arguments |
| 2200 | elif nargs == OPTIONAL: |
| 2201 | nargs_pattern = '(-*A?-*)' |
| 2202 | |
| 2203 | # allow zero or more arguments |
| 2204 | elif nargs == ZERO_OR_MORE: |
| 2205 | nargs_pattern = '(-*[A-]*)' |
| 2206 | |
| 2207 | # allow one or more arguments |
| 2208 | elif nargs == ONE_OR_MORE: |
| 2209 | nargs_pattern = '(-*A[A-]*)' |
| 2210 | |
| 2211 | # allow any number of options or arguments |
| 2212 | elif nargs == REMAINDER: |
| 2213 | nargs_pattern = '([-AO]*)' |
| 2214 | |
| 2215 | # allow one argument followed by any number of options or arguments |
| 2216 | elif nargs == PARSER: |
| 2217 | nargs_pattern = '(-*A[-AO]*)' |
| 2218 | |
R. David Murray | 0f6b9d2 | 2017-09-06 20:25:40 -0400 | [diff] [blame] | 2219 | # suppress action, like nargs=0 |
| 2220 | elif nargs == SUPPRESS: |
| 2221 | nargs_pattern = '(-*-*)' |
| 2222 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2223 | # all others should be integers |
| 2224 | else: |
| 2225 | nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs) |
| 2226 | |
| 2227 | # if this is an optional action, -- is not allowed |
| 2228 | if action.option_strings: |
| 2229 | nargs_pattern = nargs_pattern.replace('-*', '') |
| 2230 | nargs_pattern = nargs_pattern.replace('-', '') |
| 2231 | |
| 2232 | # return the pattern |
| 2233 | return nargs_pattern |
| 2234 | |
| 2235 | # ======================== |
R. David Murray | 0f6b9d2 | 2017-09-06 20:25:40 -0400 | [diff] [blame] | 2236 | # Alt command line argument parsing, allowing free intermix |
| 2237 | # ======================== |
| 2238 | |
| 2239 | def parse_intermixed_args(self, args=None, namespace=None): |
| 2240 | args, argv = self.parse_known_intermixed_args(args, namespace) |
| 2241 | if argv: |
| 2242 | msg = _('unrecognized arguments: %s') |
| 2243 | self.error(msg % ' '.join(argv)) |
| 2244 | return args |
| 2245 | |
| 2246 | def parse_known_intermixed_args(self, args=None, namespace=None): |
| 2247 | # returns a namespace and list of extras |
| 2248 | # |
| 2249 | # positional can be freely intermixed with optionals. optionals are |
| 2250 | # first parsed with all positional arguments deactivated. The 'extras' |
| 2251 | # are then parsed. If the parser definition is incompatible with the |
| 2252 | # intermixed assumptions (e.g. use of REMAINDER, subparsers) a |
| 2253 | # TypeError is raised. |
| 2254 | # |
| 2255 | # positionals are 'deactivated' by setting nargs and default to |
| 2256 | # SUPPRESS. This blocks the addition of that positional to the |
| 2257 | # namespace |
| 2258 | |
| 2259 | positionals = self._get_positional_actions() |
| 2260 | a = [action for action in positionals |
| 2261 | if action.nargs in [PARSER, REMAINDER]] |
| 2262 | if a: |
| 2263 | raise TypeError('parse_intermixed_args: positional arg' |
| 2264 | ' with nargs=%s'%a[0].nargs) |
| 2265 | |
| 2266 | if [action.dest for group in self._mutually_exclusive_groups |
| 2267 | for action in group._group_actions if action in positionals]: |
| 2268 | raise TypeError('parse_intermixed_args: positional in' |
| 2269 | ' mutuallyExclusiveGroup') |
| 2270 | |
| 2271 | try: |
| 2272 | save_usage = self.usage |
| 2273 | try: |
| 2274 | if self.usage is None: |
| 2275 | # capture the full usage for use in error messages |
| 2276 | self.usage = self.format_usage()[7:] |
| 2277 | for action in positionals: |
| 2278 | # deactivate positionals |
| 2279 | action.save_nargs = action.nargs |
| 2280 | # action.nargs = 0 |
| 2281 | action.nargs = SUPPRESS |
| 2282 | action.save_default = action.default |
| 2283 | action.default = SUPPRESS |
| 2284 | namespace, remaining_args = self.parse_known_args(args, |
| 2285 | namespace) |
| 2286 | for action in positionals: |
| 2287 | # remove the empty positional values from namespace |
| 2288 | if (hasattr(namespace, action.dest) |
| 2289 | and getattr(namespace, action.dest)==[]): |
| 2290 | from warnings import warn |
| 2291 | warn('Do not expect %s in %s' % (action.dest, namespace)) |
| 2292 | delattr(namespace, action.dest) |
| 2293 | finally: |
| 2294 | # restore nargs and usage before exiting |
| 2295 | for action in positionals: |
| 2296 | action.nargs = action.save_nargs |
| 2297 | action.default = action.save_default |
| 2298 | optionals = self._get_optional_actions() |
| 2299 | try: |
| 2300 | # parse positionals. optionals aren't normally required, but |
| 2301 | # they could be, so make sure they aren't. |
| 2302 | for action in optionals: |
| 2303 | action.save_required = action.required |
| 2304 | action.required = False |
| 2305 | for group in self._mutually_exclusive_groups: |
| 2306 | group.save_required = group.required |
| 2307 | group.required = False |
| 2308 | namespace, extras = self.parse_known_args(remaining_args, |
| 2309 | namespace) |
| 2310 | finally: |
| 2311 | # restore parser values before exiting |
| 2312 | for action in optionals: |
| 2313 | action.required = action.save_required |
| 2314 | for group in self._mutually_exclusive_groups: |
| 2315 | group.required = group.save_required |
| 2316 | finally: |
| 2317 | self.usage = save_usage |
| 2318 | return namespace, extras |
| 2319 | |
| 2320 | # ======================== |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2321 | # Value conversion methods |
| 2322 | # ======================== |
| 2323 | def _get_values(self, action, arg_strings): |
R David Murray | 00528e8 | 2012-07-21 22:48:35 -0400 | [diff] [blame] | 2324 | # for everything but PARSER, REMAINDER args, strip out first '--' |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2325 | if action.nargs not in [PARSER, REMAINDER]: |
R David Murray | 00528e8 | 2012-07-21 22:48:35 -0400 | [diff] [blame] | 2326 | try: |
| 2327 | arg_strings.remove('--') |
| 2328 | except ValueError: |
| 2329 | pass |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2330 | |
| 2331 | # optional argument produces a default when not present |
| 2332 | if not arg_strings and action.nargs == OPTIONAL: |
| 2333 | if action.option_strings: |
| 2334 | value = action.const |
| 2335 | else: |
| 2336 | value = action.default |
Benjamin Peterson | 16f2fd0 | 2010-03-02 23:09:38 +0000 | [diff] [blame] | 2337 | if isinstance(value, str): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2338 | value = self._get_value(action, value) |
| 2339 | self._check_value(action, value) |
| 2340 | |
| 2341 | # when nargs='*' on a positional, if there were no command-line |
| 2342 | # args, use the default if it is anything other than None |
| 2343 | elif (not arg_strings and action.nargs == ZERO_OR_MORE and |
| 2344 | not action.option_strings): |
| 2345 | if action.default is not None: |
| 2346 | value = action.default |
| 2347 | else: |
| 2348 | value = arg_strings |
| 2349 | self._check_value(action, value) |
| 2350 | |
| 2351 | # single argument or optional argument produces a single value |
| 2352 | elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]: |
| 2353 | arg_string, = arg_strings |
| 2354 | value = self._get_value(action, arg_string) |
| 2355 | self._check_value(action, value) |
| 2356 | |
| 2357 | # REMAINDER arguments convert all values, checking none |
| 2358 | elif action.nargs == REMAINDER: |
| 2359 | value = [self._get_value(action, v) for v in arg_strings] |
| 2360 | |
| 2361 | # PARSER arguments convert all values, but check only the first |
| 2362 | elif action.nargs == PARSER: |
| 2363 | value = [self._get_value(action, v) for v in arg_strings] |
| 2364 | self._check_value(action, value[0]) |
| 2365 | |
R. David Murray | 0f6b9d2 | 2017-09-06 20:25:40 -0400 | [diff] [blame] | 2366 | # SUPPRESS argument does not put anything in the namespace |
| 2367 | elif action.nargs == SUPPRESS: |
| 2368 | value = SUPPRESS |
| 2369 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2370 | # all other types of nargs produce a list |
| 2371 | else: |
| 2372 | value = [self._get_value(action, v) for v in arg_strings] |
| 2373 | for v in value: |
| 2374 | self._check_value(action, v) |
| 2375 | |
| 2376 | # return the converted value |
| 2377 | return value |
| 2378 | |
| 2379 | def _get_value(self, action, arg_string): |
| 2380 | type_func = self._registry_get('type', action.type, action.type) |
Florent Xicluna | 5d1155c | 2011-10-28 14:45:05 +0200 | [diff] [blame] | 2381 | if not callable(type_func): |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2382 | msg = _('%r is not callable') |
| 2383 | raise ArgumentError(action, msg % type_func) |
| 2384 | |
| 2385 | # convert the value to the appropriate type |
| 2386 | try: |
| 2387 | result = type_func(arg_string) |
| 2388 | |
| 2389 | # ArgumentTypeErrors indicate errors |
| 2390 | except ArgumentTypeError: |
| 2391 | name = getattr(action.type, '__name__', repr(action.type)) |
| 2392 | msg = str(_sys.exc_info()[1]) |
| 2393 | raise ArgumentError(action, msg) |
| 2394 | |
| 2395 | # TypeErrors or ValueErrors also indicate errors |
| 2396 | except (TypeError, ValueError): |
| 2397 | name = getattr(action.type, '__name__', repr(action.type)) |
Éric Araujo | bb48a8b | 2010-12-03 19:41:00 +0000 | [diff] [blame] | 2398 | args = {'type': name, 'value': arg_string} |
| 2399 | msg = _('invalid %(type)s value: %(value)r') |
| 2400 | raise ArgumentError(action, msg % args) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2401 | |
| 2402 | # return the converted value |
| 2403 | return result |
| 2404 | |
| 2405 | def _check_value(self, action, value): |
| 2406 | # converted value must be one of the choices (if specified) |
Vinay Sajip | 9ae5050 | 2016-08-23 08:43:16 +0100 | [diff] [blame] | 2407 | if action.choices is not None and value not in action.choices: |
| 2408 | args = {'value': value, |
| 2409 | 'choices': ', '.join(map(repr, action.choices))} |
| 2410 | msg = _('invalid choice: %(value)r (choose from %(choices)s)') |
| 2411 | raise ArgumentError(action, msg % args) |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2412 | |
| 2413 | # ======================= |
| 2414 | # Help-formatting methods |
| 2415 | # ======================= |
| 2416 | def format_usage(self): |
| 2417 | formatter = self._get_formatter() |
| 2418 | formatter.add_usage(self.usage, self._actions, |
| 2419 | self._mutually_exclusive_groups) |
| 2420 | return formatter.format_help() |
| 2421 | |
| 2422 | def format_help(self): |
| 2423 | formatter = self._get_formatter() |
| 2424 | |
| 2425 | # usage |
| 2426 | formatter.add_usage(self.usage, self._actions, |
| 2427 | self._mutually_exclusive_groups) |
| 2428 | |
| 2429 | # description |
| 2430 | formatter.add_text(self.description) |
| 2431 | |
| 2432 | # positionals, optionals and user-defined groups |
| 2433 | for action_group in self._action_groups: |
| 2434 | formatter.start_section(action_group.title) |
| 2435 | formatter.add_text(action_group.description) |
| 2436 | formatter.add_arguments(action_group._group_actions) |
| 2437 | formatter.end_section() |
| 2438 | |
| 2439 | # epilog |
| 2440 | formatter.add_text(self.epilog) |
| 2441 | |
| 2442 | # determine help from format above |
| 2443 | return formatter.format_help() |
| 2444 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2445 | def _get_formatter(self): |
| 2446 | return self.formatter_class(prog=self.prog) |
| 2447 | |
| 2448 | # ===================== |
| 2449 | # Help-printing methods |
| 2450 | # ===================== |
| 2451 | def print_usage(self, file=None): |
| 2452 | if file is None: |
| 2453 | file = _sys.stdout |
| 2454 | self._print_message(self.format_usage(), file) |
| 2455 | |
| 2456 | def print_help(self, file=None): |
| 2457 | if file is None: |
| 2458 | file = _sys.stdout |
| 2459 | self._print_message(self.format_help(), file) |
| 2460 | |
Benjamin Peterson | 698a18a | 2010-03-02 22:34:37 +0000 | [diff] [blame] | 2461 | def _print_message(self, message, file=None): |
| 2462 | if message: |
| 2463 | if file is None: |
| 2464 | file = _sys.stderr |
| 2465 | file.write(message) |
| 2466 | |
| 2467 | # =============== |
| 2468 | # Exiting methods |
| 2469 | # =============== |
| 2470 | def exit(self, status=0, message=None): |
| 2471 | if message: |
| 2472 | self._print_message(message, _sys.stderr) |
| 2473 | _sys.exit(status) |
| 2474 | |
| 2475 | def error(self, message): |
| 2476 | """error(message: string) |
| 2477 | |
| 2478 | Prints a usage message incorporating the message to stderr and |
| 2479 | exits. |
| 2480 | |
| 2481 | If you override this in a subclass, it should not return -- it |
| 2482 | should either exit or raise an exception. |
| 2483 | """ |
| 2484 | self.print_usage(_sys.stderr) |
Éric Araujo | bb48a8b | 2010-12-03 19:41:00 +0000 | [diff] [blame] | 2485 | args = {'prog': self.prog, 'message': message} |
| 2486 | self.exit(2, _('%(prog)s: error: %(message)s\n') % args) |