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