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