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