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