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