blob: 370692bd1bf4e70149857138a22c09534491d7c1 [file] [log] [blame]
Benjamin Peterson2b37fc42010-03-24 22:10:42 +00001# Author: Steven J. Bethard <steven.bethard@gmail.com>.
Raymond Hettinger496058f2019-08-29 21:04:37 -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] = '['
Flavian Hautboisda27d9b2019-08-25 21:06:45 +0200408 if end in inserts:
409 inserts[end] += ']'
410 else:
411 inserts[end] = ']'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000412 else:
Steven Bethard49998ee2010-11-01 16:29:26 +0000413 if start in inserts:
414 inserts[start] += ' ('
415 else:
416 inserts[start] = '('
Flavian Hautboisda27d9b2019-08-25 21:06:45 +0200417 if end in inserts:
418 inserts[end] += ')'
419 else:
420 inserts[end] = ')'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000421 for i in range(start + 1, end):
422 inserts[i] = '|'
423
424 # collect all actions format strings
425 parts = []
426 for i, action in enumerate(actions):
427
428 # suppressed arguments are marked with None
429 # remove | separators for suppressed arguments
430 if action.help is SUPPRESS:
431 parts.append(None)
432 if inserts.get(i) == '|':
433 inserts.pop(i)
434 elif inserts.get(i + 1) == '|':
435 inserts.pop(i + 1)
436
437 # produce all arg strings
438 elif not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100439 default = self._get_default_metavar_for_positional(action)
440 part = self._format_args(action, default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000441
442 # if it's in a group, strip the outer []
443 if action in group_actions:
444 if part[0] == '[' and part[-1] == ']':
445 part = part[1:-1]
446
447 # add the action string to the list
448 parts.append(part)
449
450 # produce the first way to invoke the option in brackets
451 else:
452 option_string = action.option_strings[0]
453
454 # if the Optional doesn't take a value, format is:
455 # -s or --long
456 if action.nargs == 0:
457 part = '%s' % option_string
458
459 # if the Optional takes a value, format is:
460 # -s ARGS or --long ARGS
461 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100462 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000463 args_string = self._format_args(action, default)
464 part = '%s %s' % (option_string, args_string)
465
466 # make it look optional if it's not required or in a group
467 if not action.required and action not in group_actions:
468 part = '[%s]' % part
469
470 # add the action string to the list
471 parts.append(part)
472
473 # insert things at the necessary indices
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000474 for i in sorted(inserts, reverse=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000475 parts[i:i] = [inserts[i]]
476
477 # join all the action items with spaces
478 text = ' '.join([item for item in parts if item is not None])
479
480 # clean up separators for mutually exclusive groups
481 open = r'[\[(]'
482 close = r'[\])]'
483 text = _re.sub(r'(%s) ' % open, r'\1', text)
484 text = _re.sub(r' (%s)' % close, r'\1', text)
485 text = _re.sub(r'%s *%s' % (open, close), r'', text)
486 text = _re.sub(r'\(([^|]*)\)', r'\1', text)
487 text = text.strip()
488
489 # return the text
490 return text
491
492 def _format_text(self, text):
493 if '%(prog)' in text:
494 text = text % dict(prog=self._prog)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200495 text_width = max(self._width - self._current_indent, 11)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000496 indent = ' ' * self._current_indent
497 return self._fill_text(text, text_width, indent) + '\n\n'
498
499 def _format_action(self, action):
500 # determine the required width and the entry label
501 help_position = min(self._action_max_length + 2,
502 self._max_help_position)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200503 help_width = max(self._width - help_position, 11)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000504 action_width = help_position - self._current_indent - 2
505 action_header = self._format_action_invocation(action)
506
Georg Brandl2514f522014-10-20 08:36:02 +0200507 # no help; start on same line and add a final newline
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000508 if not action.help:
509 tup = self._current_indent, '', action_header
510 action_header = '%*s%s\n' % tup
511
512 # short action name; start on the same line and pad two spaces
513 elif len(action_header) <= action_width:
514 tup = self._current_indent, '', action_width, action_header
515 action_header = '%*s%-*s ' % tup
516 indent_first = 0
517
518 # long action name; start on the next line
519 else:
520 tup = self._current_indent, '', action_header
521 action_header = '%*s%s\n' % tup
522 indent_first = help_position
523
524 # collect the pieces of the action help
525 parts = [action_header]
526
527 # if there was help for the action, add lines of help text
528 if action.help:
529 help_text = self._expand_help(action)
530 help_lines = self._split_lines(help_text, help_width)
531 parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
532 for line in help_lines[1:]:
533 parts.append('%*s%s\n' % (help_position, '', line))
534
535 # or add a newline if the description doesn't end with one
536 elif not action_header.endswith('\n'):
537 parts.append('\n')
538
539 # if there are any sub-actions, add their help as well
540 for subaction in self._iter_indented_subactions(action):
541 parts.append(self._format_action(subaction))
542
543 # return a single string
544 return self._join_parts(parts)
545
546 def _format_action_invocation(self, action):
547 if not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100548 default = self._get_default_metavar_for_positional(action)
549 metavar, = self._metavar_formatter(action, default)(1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000550 return metavar
551
552 else:
553 parts = []
554
555 # if the Optional doesn't take a value, format is:
556 # -s, --long
557 if action.nargs == 0:
558 parts.extend(action.option_strings)
559
560 # if the Optional takes a value, format is:
561 # -s ARGS, --long ARGS
562 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100563 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000564 args_string = self._format_args(action, default)
565 for option_string in action.option_strings:
566 parts.append('%s %s' % (option_string, args_string))
567
568 return ', '.join(parts)
569
570 def _metavar_formatter(self, action, default_metavar):
571 if action.metavar is not None:
572 result = action.metavar
573 elif action.choices is not None:
574 choice_strs = [str(choice) for choice in action.choices]
575 result = '{%s}' % ','.join(choice_strs)
576 else:
577 result = default_metavar
578
579 def format(tuple_size):
580 if isinstance(result, tuple):
581 return result
582 else:
583 return (result, ) * tuple_size
584 return format
585
586 def _format_args(self, action, default_metavar):
587 get_metavar = self._metavar_formatter(action, default_metavar)
588 if action.nargs is None:
589 result = '%s' % get_metavar(1)
590 elif action.nargs == OPTIONAL:
591 result = '[%s]' % get_metavar(1)
592 elif action.nargs == ZERO_OR_MORE:
593 result = '[%s [%s ...]]' % get_metavar(2)
594 elif action.nargs == ONE_OR_MORE:
595 result = '%s [%s ...]' % get_metavar(2)
596 elif action.nargs == REMAINDER:
597 result = '...'
598 elif action.nargs == PARSER:
599 result = '%s ...' % get_metavar(1)
R. David Murray0f6b9d22017-09-06 20:25:40 -0400600 elif action.nargs == SUPPRESS:
601 result = ''
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000602 else:
tmblweed4b3e9752019-08-01 21:57:13 -0700603 try:
604 formats = ['%s' for _ in range(action.nargs)]
605 except TypeError:
606 raise ValueError("invalid nargs value") from None
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000607 result = ' '.join(formats) % get_metavar(action.nargs)
608 return result
609
610 def _expand_help(self, action):
611 params = dict(vars(action), prog=self._prog)
612 for name in list(params):
613 if params[name] is SUPPRESS:
614 del params[name]
615 for name in list(params):
616 if hasattr(params[name], '__name__'):
617 params[name] = params[name].__name__
618 if params.get('choices') is not None:
619 choices_str = ', '.join([str(c) for c in params['choices']])
620 params['choices'] = choices_str
621 return self._get_help_string(action) % params
622
623 def _iter_indented_subactions(self, action):
624 try:
625 get_subactions = action._get_subactions
626 except AttributeError:
627 pass
628 else:
629 self._indent()
Philip Jenvey4993cc02012-10-01 12:53:43 -0700630 yield from get_subactions()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000631 self._dedent()
632
633 def _split_lines(self, text, width):
634 text = self._whitespace_matcher.sub(' ', text).strip()
Serhiy Storchaka81108372017-09-26 00:55:55 +0300635 # The textwrap module is used only for formatting help.
636 # Delay its import for speeding up the common usage of argparse.
637 import textwrap
638 return textwrap.wrap(text, width)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000639
640 def _fill_text(self, text, width, indent):
641 text = self._whitespace_matcher.sub(' ', text).strip()
Serhiy Storchaka81108372017-09-26 00:55:55 +0300642 import textwrap
643 return textwrap.fill(text, width,
644 initial_indent=indent,
645 subsequent_indent=indent)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000646
647 def _get_help_string(self, action):
648 return action.help
649
Steven Bethard0331e902011-03-26 14:48:04 +0100650 def _get_default_metavar_for_optional(self, action):
651 return action.dest.upper()
652
653 def _get_default_metavar_for_positional(self, action):
654 return action.dest
655
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000656
657class RawDescriptionHelpFormatter(HelpFormatter):
658 """Help message formatter which retains any formatting in descriptions.
659
660 Only the name of this class is considered a public API. All the methods
661 provided by the class are considered an implementation detail.
662 """
663
664 def _fill_text(self, text, width, indent):
Ezio Melottid8b509b2011-09-28 17:37:55 +0300665 return ''.join(indent + line for line in text.splitlines(keepends=True))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000666
667
668class RawTextHelpFormatter(RawDescriptionHelpFormatter):
669 """Help message formatter which retains formatting of all help text.
670
671 Only the name of this class is considered a public API. All the methods
672 provided by the class are considered an implementation detail.
673 """
674
675 def _split_lines(self, text, width):
676 return text.splitlines()
677
678
679class ArgumentDefaultsHelpFormatter(HelpFormatter):
680 """Help message formatter which adds default values to argument help.
681
682 Only the name of this class is considered a public API. All the methods
683 provided by the class are considered an implementation detail.
684 """
685
686 def _get_help_string(self, action):
687 help = action.help
688 if '%(default)' not in action.help:
689 if action.default is not SUPPRESS:
690 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
691 if action.option_strings or action.nargs in defaulting_nargs:
692 help += ' (default: %(default)s)'
693 return help
694
695
Steven Bethard0331e902011-03-26 14:48:04 +0100696class MetavarTypeHelpFormatter(HelpFormatter):
697 """Help message formatter which uses the argument 'type' as the default
698 metavar value (instead of the argument 'dest')
699
700 Only the name of this class is considered a public API. All the methods
701 provided by the class are considered an implementation detail.
702 """
703
704 def _get_default_metavar_for_optional(self, action):
705 return action.type.__name__
706
707 def _get_default_metavar_for_positional(self, action):
708 return action.type.__name__
709
710
711
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000712# =====================
713# Options and Arguments
714# =====================
715
716def _get_action_name(argument):
717 if argument is None:
718 return None
719 elif argument.option_strings:
720 return '/'.join(argument.option_strings)
721 elif argument.metavar not in (None, SUPPRESS):
722 return argument.metavar
723 elif argument.dest not in (None, SUPPRESS):
724 return argument.dest
725 else:
726 return None
727
728
729class ArgumentError(Exception):
730 """An error from creating or using an argument (optional or positional).
731
732 The string value of this exception is the message, augmented with
733 information about the argument that caused it.
734 """
735
736 def __init__(self, argument, message):
737 self.argument_name = _get_action_name(argument)
738 self.message = message
739
740 def __str__(self):
741 if self.argument_name is None:
742 format = '%(message)s'
743 else:
744 format = 'argument %(argument_name)s: %(message)s'
745 return format % dict(message=self.message,
746 argument_name=self.argument_name)
747
748
749class ArgumentTypeError(Exception):
750 """An error from trying to convert a command line string to a type."""
751 pass
752
753
754# ==============
755# Action classes
756# ==============
757
758class Action(_AttributeHolder):
759 """Information about how to convert command line strings to Python objects.
760
761 Action objects are used by an ArgumentParser to represent the information
762 needed to parse a single argument from one or more strings from the
763 command line. The keyword arguments to the Action constructor are also
764 all attributes of Action instances.
765
766 Keyword Arguments:
767
768 - option_strings -- A list of command-line option strings which
769 should be associated with this action.
770
771 - dest -- The name of the attribute to hold the created object(s)
772
773 - nargs -- The number of command-line arguments that should be
774 consumed. By default, one argument will be consumed and a single
775 value will be produced. Other values include:
776 - N (an integer) consumes N arguments (and produces a list)
777 - '?' consumes zero or one arguments
778 - '*' consumes zero or more arguments (and produces a list)
779 - '+' consumes one or more arguments (and produces a list)
780 Note that the difference between the default and nargs=1 is that
781 with the default, a single value will be produced, while with
782 nargs=1, a list containing a single value will be produced.
783
784 - const -- The value to be produced if the option is specified and the
785 option uses an action that takes no values.
786
787 - default -- The value to be produced if the option is not specified.
788
R David Murray15cd9a02012-07-21 17:04:25 -0400789 - type -- A callable that accepts a single string argument, and
790 returns the converted value. The standard Python types str, int,
791 float, and complex are useful examples of such callables. If None,
792 str is used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000793
794 - choices -- A container of values that should be allowed. If not None,
795 after a command-line argument has been converted to the appropriate
796 type, an exception will be raised if it is not a member of this
797 collection.
798
799 - required -- True if the action must always be specified at the
800 command line. This is only meaningful for optional command-line
801 arguments.
802
803 - help -- The help string describing the argument.
804
805 - metavar -- The name to be used for the option's argument with the
806 help string. If None, the 'dest' value will be used as the name.
807 """
808
809 def __init__(self,
810 option_strings,
811 dest,
812 nargs=None,
813 const=None,
814 default=None,
815 type=None,
816 choices=None,
817 required=False,
818 help=None,
819 metavar=None):
820 self.option_strings = option_strings
821 self.dest = dest
822 self.nargs = nargs
823 self.const = const
824 self.default = default
825 self.type = type
826 self.choices = choices
827 self.required = required
828 self.help = help
829 self.metavar = metavar
830
831 def _get_kwargs(self):
832 names = [
833 'option_strings',
834 'dest',
835 'nargs',
836 'const',
837 'default',
838 'type',
839 'choices',
840 'help',
841 'metavar',
842 ]
843 return [(name, getattr(self, name)) for name in names]
844
845 def __call__(self, parser, namespace, values, option_string=None):
846 raise NotImplementedError(_('.__call__() not defined'))
847
848
849class _StoreAction(Action):
850
851 def __init__(self,
852 option_strings,
853 dest,
854 nargs=None,
855 const=None,
856 default=None,
857 type=None,
858 choices=None,
859 required=False,
860 help=None,
861 metavar=None):
862 if nargs == 0:
tmblweed4b3e9752019-08-01 21:57:13 -0700863 raise ValueError('nargs for store actions must be != 0; if you '
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000864 'have nothing to store, actions such as store '
865 'true or store const may be more appropriate')
866 if const is not None and nargs != OPTIONAL:
867 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
868 super(_StoreAction, self).__init__(
869 option_strings=option_strings,
870 dest=dest,
871 nargs=nargs,
872 const=const,
873 default=default,
874 type=type,
875 choices=choices,
876 required=required,
877 help=help,
878 metavar=metavar)
879
880 def __call__(self, parser, namespace, values, option_string=None):
881 setattr(namespace, self.dest, values)
882
883
884class _StoreConstAction(Action):
885
886 def __init__(self,
887 option_strings,
888 dest,
889 const,
890 default=None,
891 required=False,
892 help=None,
893 metavar=None):
894 super(_StoreConstAction, self).__init__(
895 option_strings=option_strings,
896 dest=dest,
897 nargs=0,
898 const=const,
899 default=default,
900 required=required,
901 help=help)
902
903 def __call__(self, parser, namespace, values, option_string=None):
904 setattr(namespace, self.dest, self.const)
905
906
907class _StoreTrueAction(_StoreConstAction):
908
909 def __init__(self,
910 option_strings,
911 dest,
912 default=False,
913 required=False,
914 help=None):
915 super(_StoreTrueAction, self).__init__(
916 option_strings=option_strings,
917 dest=dest,
918 const=True,
919 default=default,
920 required=required,
921 help=help)
922
923
924class _StoreFalseAction(_StoreConstAction):
925
926 def __init__(self,
927 option_strings,
928 dest,
929 default=True,
930 required=False,
931 help=None):
932 super(_StoreFalseAction, self).__init__(
933 option_strings=option_strings,
934 dest=dest,
935 const=False,
936 default=default,
937 required=required,
938 help=help)
939
940
941class _AppendAction(Action):
942
943 def __init__(self,
944 option_strings,
945 dest,
946 nargs=None,
947 const=None,
948 default=None,
949 type=None,
950 choices=None,
951 required=False,
952 help=None,
953 metavar=None):
954 if nargs == 0:
tmblweed4b3e9752019-08-01 21:57:13 -0700955 raise ValueError('nargs for append actions must be != 0; if arg '
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000956 'strings are not supplying the value to append, '
957 'the append const action may be more appropriate')
958 if const is not None and nargs != OPTIONAL:
959 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
960 super(_AppendAction, self).__init__(
961 option_strings=option_strings,
962 dest=dest,
963 nargs=nargs,
964 const=const,
965 default=default,
966 type=type,
967 choices=choices,
968 required=required,
969 help=help,
970 metavar=metavar)
971
972 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +0300973 items = getattr(namespace, self.dest, None)
974 items = _copy_items(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000975 items.append(values)
976 setattr(namespace, self.dest, items)
977
978
979class _AppendConstAction(Action):
980
981 def __init__(self,
982 option_strings,
983 dest,
984 const,
985 default=None,
986 required=False,
987 help=None,
988 metavar=None):
989 super(_AppendConstAction, self).__init__(
990 option_strings=option_strings,
991 dest=dest,
992 nargs=0,
993 const=const,
994 default=default,
995 required=required,
996 help=help,
997 metavar=metavar)
998
999 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001000 items = getattr(namespace, self.dest, None)
1001 items = _copy_items(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001002 items.append(self.const)
1003 setattr(namespace, self.dest, items)
1004
1005
1006class _CountAction(Action):
1007
1008 def __init__(self,
1009 option_strings,
1010 dest,
1011 default=None,
1012 required=False,
1013 help=None):
1014 super(_CountAction, self).__init__(
1015 option_strings=option_strings,
1016 dest=dest,
1017 nargs=0,
1018 default=default,
1019 required=required,
1020 help=help)
1021
1022 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001023 count = getattr(namespace, self.dest, None)
1024 if count is None:
1025 count = 0
1026 setattr(namespace, self.dest, count + 1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001027
1028
1029class _HelpAction(Action):
1030
1031 def __init__(self,
1032 option_strings,
1033 dest=SUPPRESS,
1034 default=SUPPRESS,
1035 help=None):
1036 super(_HelpAction, self).__init__(
1037 option_strings=option_strings,
1038 dest=dest,
1039 default=default,
1040 nargs=0,
1041 help=help)
1042
1043 def __call__(self, parser, namespace, values, option_string=None):
1044 parser.print_help()
1045 parser.exit()
1046
1047
1048class _VersionAction(Action):
1049
1050 def __init__(self,
1051 option_strings,
1052 version=None,
1053 dest=SUPPRESS,
1054 default=SUPPRESS,
Steven Bethard50fe5932010-05-24 03:47:38 +00001055 help="show program's version number and exit"):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001056 super(_VersionAction, self).__init__(
1057 option_strings=option_strings,
1058 dest=dest,
1059 default=default,
1060 nargs=0,
1061 help=help)
1062 self.version = version
1063
1064 def __call__(self, parser, namespace, values, option_string=None):
1065 version = self.version
1066 if version is None:
1067 version = parser.version
1068 formatter = parser._get_formatter()
1069 formatter.add_text(version)
Eli Benderskycdac5512013-09-06 06:49:15 -07001070 parser._print_message(formatter.format_help(), _sys.stdout)
1071 parser.exit()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001072
1073
1074class _SubParsersAction(Action):
1075
1076 class _ChoicesPseudoAction(Action):
1077
Steven Bethardfd311a72010-12-18 11:19:23 +00001078 def __init__(self, name, aliases, help):
1079 metavar = dest = name
1080 if aliases:
1081 metavar += ' (%s)' % ', '.join(aliases)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001082 sup = super(_SubParsersAction._ChoicesPseudoAction, self)
Steven Bethardfd311a72010-12-18 11:19:23 +00001083 sup.__init__(option_strings=[], dest=dest, help=help,
1084 metavar=metavar)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001085
1086 def __init__(self,
1087 option_strings,
1088 prog,
1089 parser_class,
1090 dest=SUPPRESS,
Ned Deily8ebf5ce2018-05-23 21:55:15 -04001091 required=False,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001092 help=None,
1093 metavar=None):
1094
1095 self._prog_prefix = prog
1096 self._parser_class = parser_class
Raymond Hettinger05565ed2018-01-11 22:20:33 -08001097 self._name_parser_map = {}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001098 self._choices_actions = []
1099
1100 super(_SubParsersAction, self).__init__(
1101 option_strings=option_strings,
1102 dest=dest,
1103 nargs=PARSER,
1104 choices=self._name_parser_map,
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001105 required=required,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001106 help=help,
1107 metavar=metavar)
1108
1109 def add_parser(self, name, **kwargs):
1110 # set prog from the existing prefix
1111 if kwargs.get('prog') is None:
1112 kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1113
Steven Bethardfd311a72010-12-18 11:19:23 +00001114 aliases = kwargs.pop('aliases', ())
1115
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001116 # create a pseudo-action to hold the choice help
1117 if 'help' in kwargs:
1118 help = kwargs.pop('help')
Steven Bethardfd311a72010-12-18 11:19:23 +00001119 choice_action = self._ChoicesPseudoAction(name, aliases, help)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001120 self._choices_actions.append(choice_action)
1121
1122 # create the parser and add it to the map
1123 parser = self._parser_class(**kwargs)
1124 self._name_parser_map[name] = parser
Steven Bethardfd311a72010-12-18 11:19:23 +00001125
1126 # make parser available under aliases also
1127 for alias in aliases:
1128 self._name_parser_map[alias] = parser
1129
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001130 return parser
1131
1132 def _get_subactions(self):
1133 return self._choices_actions
1134
1135 def __call__(self, parser, namespace, values, option_string=None):
1136 parser_name = values[0]
1137 arg_strings = values[1:]
1138
1139 # set the parser name if requested
1140 if self.dest is not SUPPRESS:
1141 setattr(namespace, self.dest, parser_name)
1142
1143 # select the parser
1144 try:
1145 parser = self._name_parser_map[parser_name]
1146 except KeyError:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001147 args = {'parser_name': parser_name,
1148 'choices': ', '.join(self._name_parser_map)}
1149 msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001150 raise ArgumentError(self, msg)
1151
1152 # parse all the remaining options into the namespace
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001153 # store any unrecognized options on the object, so that the top
1154 # level parser can decide what to do with them
R David Murray7570cbd2014-10-17 19:55:11 -04001155
1156 # In case this subparser defines new defaults, we parse them
1157 # in a new namespace object and then update the original
1158 # namespace for the relevant parts.
1159 subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
1160 for key, value in vars(subnamespace).items():
1161 setattr(namespace, key, value)
1162
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001163 if arg_strings:
1164 vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1165 getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001166
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001167class _ExtendAction(_AppendAction):
1168 def __call__(self, parser, namespace, values, option_string=None):
1169 items = getattr(namespace, self.dest, None)
1170 items = _copy_items(items)
1171 items.extend(values)
1172 setattr(namespace, self.dest, items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001173
1174# ==============
1175# Type classes
1176# ==============
1177
1178class FileType(object):
1179 """Factory for creating file object types
1180
1181 Instances of FileType are typically passed as type= arguments to the
1182 ArgumentParser add_argument() method.
1183
1184 Keyword Arguments:
1185 - mode -- A string indicating how the file is to be opened. Accepts the
1186 same values as the builtin open() function.
1187 - bufsize -- The file's desired buffer size. Accepts the same values as
1188 the builtin open() function.
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001189 - encoding -- The file's encoding. Accepts the same values as the
Terry Jan Reedy8e7586b2013-03-11 18:38:13 -04001190 builtin open() function.
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001191 - errors -- A string indicating how encoding and decoding errors are to
1192 be handled. Accepts the same value as the builtin open() function.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001193 """
1194
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001195 def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001196 self._mode = mode
1197 self._bufsize = bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001198 self._encoding = encoding
1199 self._errors = errors
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001200
1201 def __call__(self, string):
1202 # the special argument "-" means sys.std{in,out}
1203 if string == '-':
1204 if 'r' in self._mode:
1205 return _sys.stdin
1206 elif 'w' in self._mode:
1207 return _sys.stdout
1208 else:
Éric Araujoa9c7a8f2010-12-03 19:19:17 +00001209 msg = _('argument "-" with mode %r') % self._mode
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001210 raise ValueError(msg)
1211
1212 # all other arguments are used as file names
Steven Bethardb0270112011-01-24 21:02:50 +00001213 try:
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001214 return open(string, self._mode, self._bufsize, self._encoding,
1215 self._errors)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001216 except OSError as e:
Jakub Kulík42671ae2019-09-13 11:25:32 +02001217 args = {'filename': string, 'error': e}
1218 message = _("can't open '%(filename)s': %(error)s")
1219 raise ArgumentTypeError(message % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001220
1221 def __repr__(self):
Steven Bethardb0270112011-01-24 21:02:50 +00001222 args = self._mode, self._bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001223 kwargs = [('encoding', self._encoding), ('errors', self._errors)]
1224 args_str = ', '.join([repr(arg) for arg in args if arg != -1] +
1225 ['%s=%r' % (kw, arg) for kw, arg in kwargs
1226 if arg is not None])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001227 return '%s(%s)' % (type(self).__name__, args_str)
1228
1229# ===========================
1230# Optional and Positional Parsing
1231# ===========================
1232
1233class Namespace(_AttributeHolder):
1234 """Simple object for storing attributes.
1235
1236 Implements equality by attribute names and values, and provides a simple
1237 string representation.
1238 """
1239
1240 def __init__(self, **kwargs):
1241 for name in kwargs:
1242 setattr(self, name, kwargs[name])
1243
1244 def __eq__(self, other):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07001245 if not isinstance(other, Namespace):
1246 return NotImplemented
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001247 return vars(self) == vars(other)
1248
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001249 def __contains__(self, key):
1250 return key in self.__dict__
1251
1252
1253class _ActionsContainer(object):
1254
1255 def __init__(self,
1256 description,
1257 prefix_chars,
1258 argument_default,
1259 conflict_handler):
1260 super(_ActionsContainer, self).__init__()
1261
1262 self.description = description
1263 self.argument_default = argument_default
1264 self.prefix_chars = prefix_chars
1265 self.conflict_handler = conflict_handler
1266
1267 # set up registries
1268 self._registries = {}
1269
1270 # register actions
1271 self.register('action', None, _StoreAction)
1272 self.register('action', 'store', _StoreAction)
1273 self.register('action', 'store_const', _StoreConstAction)
1274 self.register('action', 'store_true', _StoreTrueAction)
1275 self.register('action', 'store_false', _StoreFalseAction)
1276 self.register('action', 'append', _AppendAction)
1277 self.register('action', 'append_const', _AppendConstAction)
1278 self.register('action', 'count', _CountAction)
1279 self.register('action', 'help', _HelpAction)
1280 self.register('action', 'version', _VersionAction)
1281 self.register('action', 'parsers', _SubParsersAction)
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001282 self.register('action', 'extend', _ExtendAction)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001283
1284 # raise an exception if the conflict handler is invalid
1285 self._get_handler()
1286
1287 # action storage
1288 self._actions = []
1289 self._option_string_actions = {}
1290
1291 # groups
1292 self._action_groups = []
1293 self._mutually_exclusive_groups = []
1294
1295 # defaults storage
1296 self._defaults = {}
1297
1298 # determines whether an "option" looks like a negative number
1299 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1300
1301 # whether or not there are any optionals that look like negative
1302 # numbers -- uses a list so it can be shared and edited
1303 self._has_negative_number_optionals = []
1304
1305 # ====================
1306 # Registration methods
1307 # ====================
1308 def register(self, registry_name, value, object):
1309 registry = self._registries.setdefault(registry_name, {})
1310 registry[value] = object
1311
1312 def _registry_get(self, registry_name, value, default=None):
1313 return self._registries[registry_name].get(value, default)
1314
1315 # ==================================
1316 # Namespace default accessor methods
1317 # ==================================
1318 def set_defaults(self, **kwargs):
1319 self._defaults.update(kwargs)
1320
1321 # if these defaults match any existing arguments, replace
1322 # the previous default on the object with the new one
1323 for action in self._actions:
1324 if action.dest in kwargs:
1325 action.default = kwargs[action.dest]
1326
1327 def get_default(self, dest):
1328 for action in self._actions:
1329 if action.dest == dest and action.default is not None:
1330 return action.default
1331 return self._defaults.get(dest, None)
1332
1333
1334 # =======================
1335 # Adding argument actions
1336 # =======================
1337 def add_argument(self, *args, **kwargs):
1338 """
1339 add_argument(dest, ..., name=value, ...)
1340 add_argument(option_string, option_string, ..., name=value, ...)
1341 """
1342
1343 # if no positional args are supplied or only one is supplied and
1344 # it doesn't look like an option string, parse a positional
1345 # argument
1346 chars = self.prefix_chars
1347 if not args or len(args) == 1 and args[0][0] not in chars:
1348 if args and 'dest' in kwargs:
1349 raise ValueError('dest supplied twice for positional argument')
1350 kwargs = self._get_positional_kwargs(*args, **kwargs)
1351
1352 # otherwise, we're adding an optional argument
1353 else:
1354 kwargs = self._get_optional_kwargs(*args, **kwargs)
1355
1356 # if no default was supplied, use the parser-level default
1357 if 'default' not in kwargs:
1358 dest = kwargs['dest']
1359 if dest in self._defaults:
1360 kwargs['default'] = self._defaults[dest]
1361 elif self.argument_default is not None:
1362 kwargs['default'] = self.argument_default
1363
1364 # create the action object, and add it to the parser
1365 action_class = self._pop_action_class(kwargs)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001366 if not callable(action_class):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001367 raise ValueError('unknown action "%s"' % (action_class,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001368 action = action_class(**kwargs)
1369
1370 # raise an error if the action type is not callable
1371 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001372 if not callable(type_func):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001373 raise ValueError('%r is not callable' % (type_func,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001374
zygocephalus03d58312019-06-07 23:08:36 +03001375 if type_func is FileType:
1376 raise ValueError('%r is a FileType class object, instance of it'
1377 ' must be passed' % (type_func,))
1378
Steven Bethard8d9a4622011-03-26 17:33:56 +01001379 # raise an error if the metavar does not match the type
1380 if hasattr(self, "_get_formatter"):
1381 try:
1382 self._get_formatter()._format_args(action, None)
1383 except TypeError:
1384 raise ValueError("length of metavar tuple does not match nargs")
1385
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001386 return self._add_action(action)
1387
1388 def add_argument_group(self, *args, **kwargs):
1389 group = _ArgumentGroup(self, *args, **kwargs)
1390 self._action_groups.append(group)
1391 return group
1392
1393 def add_mutually_exclusive_group(self, **kwargs):
1394 group = _MutuallyExclusiveGroup(self, **kwargs)
1395 self._mutually_exclusive_groups.append(group)
1396 return group
1397
1398 def _add_action(self, action):
1399 # resolve any conflicts
1400 self._check_conflict(action)
1401
1402 # add to actions list
1403 self._actions.append(action)
1404 action.container = self
1405
1406 # index the action by any option strings it has
1407 for option_string in action.option_strings:
1408 self._option_string_actions[option_string] = action
1409
1410 # set the flag if any option strings look like negative numbers
1411 for option_string in action.option_strings:
1412 if self._negative_number_matcher.match(option_string):
1413 if not self._has_negative_number_optionals:
1414 self._has_negative_number_optionals.append(True)
1415
1416 # return the created action
1417 return action
1418
1419 def _remove_action(self, action):
1420 self._actions.remove(action)
1421
1422 def _add_container_actions(self, container):
1423 # collect groups by titles
1424 title_group_map = {}
1425 for group in self._action_groups:
1426 if group.title in title_group_map:
1427 msg = _('cannot merge actions - two groups are named %r')
1428 raise ValueError(msg % (group.title))
1429 title_group_map[group.title] = group
1430
1431 # map each action to its group
1432 group_map = {}
1433 for group in container._action_groups:
1434
1435 # if a group with the title exists, use that, otherwise
1436 # create a new group matching the container's group
1437 if group.title not in title_group_map:
1438 title_group_map[group.title] = self.add_argument_group(
1439 title=group.title,
1440 description=group.description,
1441 conflict_handler=group.conflict_handler)
1442
1443 # map the actions to their new group
1444 for action in group._group_actions:
1445 group_map[action] = title_group_map[group.title]
1446
1447 # add container's mutually exclusive groups
1448 # NOTE: if add_mutually_exclusive_group ever gains title= and
1449 # description= then this code will need to be expanded as above
1450 for group in container._mutually_exclusive_groups:
1451 mutex_group = self.add_mutually_exclusive_group(
1452 required=group.required)
1453
1454 # map the actions to their new mutex group
1455 for action in group._group_actions:
1456 group_map[action] = mutex_group
1457
1458 # add all actions to this container or their group
1459 for action in container._actions:
1460 group_map.get(action, self)._add_action(action)
1461
1462 def _get_positional_kwargs(self, dest, **kwargs):
1463 # make sure required is not specified
1464 if 'required' in kwargs:
1465 msg = _("'required' is an invalid argument for positionals")
1466 raise TypeError(msg)
1467
1468 # mark positional arguments as required if at least one is
1469 # always required
1470 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1471 kwargs['required'] = True
1472 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1473 kwargs['required'] = True
1474
1475 # return the keyword arguments with no option strings
1476 return dict(kwargs, dest=dest, option_strings=[])
1477
1478 def _get_optional_kwargs(self, *args, **kwargs):
1479 # determine short and long option strings
1480 option_strings = []
1481 long_option_strings = []
1482 for option_string in args:
1483 # error on strings that don't start with an appropriate prefix
1484 if not option_string[0] in self.prefix_chars:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001485 args = {'option': option_string,
1486 'prefix_chars': self.prefix_chars}
1487 msg = _('invalid option string %(option)r: '
1488 'must start with a character %(prefix_chars)r')
1489 raise ValueError(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001490
1491 # strings starting with two prefix characters are long options
1492 option_strings.append(option_string)
Shashank Parekhb9600b02019-06-21 08:32:22 +05301493 if len(option_string) > 1 and option_string[1] in self.prefix_chars:
1494 long_option_strings.append(option_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001495
1496 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1497 dest = kwargs.pop('dest', None)
1498 if dest is None:
1499 if long_option_strings:
1500 dest_option_string = long_option_strings[0]
1501 else:
1502 dest_option_string = option_strings[0]
1503 dest = dest_option_string.lstrip(self.prefix_chars)
1504 if not dest:
1505 msg = _('dest= is required for options like %r')
1506 raise ValueError(msg % option_string)
1507 dest = dest.replace('-', '_')
1508
1509 # return the updated keyword arguments
1510 return dict(kwargs, dest=dest, option_strings=option_strings)
1511
1512 def _pop_action_class(self, kwargs, default=None):
1513 action = kwargs.pop('action', default)
1514 return self._registry_get('action', action, action)
1515
1516 def _get_handler(self):
1517 # determine function from conflict handler string
1518 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1519 try:
1520 return getattr(self, handler_func_name)
1521 except AttributeError:
1522 msg = _('invalid conflict_resolution value: %r')
1523 raise ValueError(msg % self.conflict_handler)
1524
1525 def _check_conflict(self, action):
1526
1527 # find all options that conflict with this option
1528 confl_optionals = []
1529 for option_string in action.option_strings:
1530 if option_string in self._option_string_actions:
1531 confl_optional = self._option_string_actions[option_string]
1532 confl_optionals.append((option_string, confl_optional))
1533
1534 # resolve any conflicts
1535 if confl_optionals:
1536 conflict_handler = self._get_handler()
1537 conflict_handler(action, confl_optionals)
1538
1539 def _handle_conflict_error(self, action, conflicting_actions):
Éric Araujo12159152010-12-04 17:31:49 +00001540 message = ngettext('conflicting option string: %s',
1541 'conflicting option strings: %s',
1542 len(conflicting_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001543 conflict_string = ', '.join([option_string
1544 for option_string, action
1545 in conflicting_actions])
1546 raise ArgumentError(action, message % conflict_string)
1547
1548 def _handle_conflict_resolve(self, action, conflicting_actions):
1549
1550 # remove all conflicting options
1551 for option_string, action in conflicting_actions:
1552
1553 # remove the conflicting option
1554 action.option_strings.remove(option_string)
1555 self._option_string_actions.pop(option_string, None)
1556
1557 # if the option now has no option string, remove it from the
1558 # container holding it
1559 if not action.option_strings:
1560 action.container._remove_action(action)
1561
1562
1563class _ArgumentGroup(_ActionsContainer):
1564
1565 def __init__(self, container, title=None, description=None, **kwargs):
1566 # add any missing keyword arguments by checking the container
1567 update = kwargs.setdefault
1568 update('conflict_handler', container.conflict_handler)
1569 update('prefix_chars', container.prefix_chars)
1570 update('argument_default', container.argument_default)
1571 super_init = super(_ArgumentGroup, self).__init__
1572 super_init(description=description, **kwargs)
1573
1574 # group attributes
1575 self.title = title
1576 self._group_actions = []
1577
1578 # share most attributes with the container
1579 self._registries = container._registries
1580 self._actions = container._actions
1581 self._option_string_actions = container._option_string_actions
1582 self._defaults = container._defaults
1583 self._has_negative_number_optionals = \
1584 container._has_negative_number_optionals
Georg Brandl0f6b47a2011-01-30 12:19:35 +00001585 self._mutually_exclusive_groups = container._mutually_exclusive_groups
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001586
1587 def _add_action(self, action):
1588 action = super(_ArgumentGroup, self)._add_action(action)
1589 self._group_actions.append(action)
1590 return action
1591
1592 def _remove_action(self, action):
1593 super(_ArgumentGroup, self)._remove_action(action)
1594 self._group_actions.remove(action)
1595
1596
1597class _MutuallyExclusiveGroup(_ArgumentGroup):
1598
1599 def __init__(self, container, required=False):
1600 super(_MutuallyExclusiveGroup, self).__init__(container)
1601 self.required = required
1602 self._container = container
1603
1604 def _add_action(self, action):
1605 if action.required:
1606 msg = _('mutually exclusive arguments must be optional')
1607 raise ValueError(msg)
1608 action = self._container._add_action(action)
1609 self._group_actions.append(action)
1610 return action
1611
1612 def _remove_action(self, action):
1613 self._container._remove_action(action)
1614 self._group_actions.remove(action)
1615
1616
1617class ArgumentParser(_AttributeHolder, _ActionsContainer):
1618 """Object for parsing command line strings into Python objects.
1619
1620 Keyword Arguments:
1621 - prog -- The name of the program (default: sys.argv[0])
1622 - usage -- A usage message (default: auto-generated from arguments)
1623 - description -- A description of what the program does
1624 - epilog -- Text following the argument descriptions
1625 - parents -- Parsers whose arguments should be copied into this one
1626 - formatter_class -- HelpFormatter class for printing help messages
1627 - prefix_chars -- Characters that prefix optional arguments
1628 - fromfile_prefix_chars -- Characters that prefix files containing
1629 additional arguments
1630 - argument_default -- The default value for all arguments
1631 - conflict_handler -- String indicating how to handle conflicts
1632 - add_help -- Add a -h/-help option
Berker Peksag8089cd62015-02-14 01:39:17 +02001633 - allow_abbrev -- Allow long options to be abbreviated unambiguously
Hai Shif5456382019-09-12 05:56:05 -05001634 - exit_on_error -- Determines whether or not ArgumentParser exits with
1635 error info when an error occurs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001636 """
1637
1638 def __init__(self,
1639 prog=None,
1640 usage=None,
1641 description=None,
1642 epilog=None,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001643 parents=[],
1644 formatter_class=HelpFormatter,
1645 prefix_chars='-',
1646 fromfile_prefix_chars=None,
1647 argument_default=None,
1648 conflict_handler='error',
Berker Peksag8089cd62015-02-14 01:39:17 +02001649 add_help=True,
Hai Shif5456382019-09-12 05:56:05 -05001650 allow_abbrev=True,
1651 exit_on_error=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001652
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001653 superinit = super(ArgumentParser, self).__init__
1654 superinit(description=description,
1655 prefix_chars=prefix_chars,
1656 argument_default=argument_default,
1657 conflict_handler=conflict_handler)
1658
1659 # default setting for prog
1660 if prog is None:
1661 prog = _os.path.basename(_sys.argv[0])
1662
1663 self.prog = prog
1664 self.usage = usage
1665 self.epilog = epilog
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001666 self.formatter_class = formatter_class
1667 self.fromfile_prefix_chars = fromfile_prefix_chars
1668 self.add_help = add_help
Berker Peksag8089cd62015-02-14 01:39:17 +02001669 self.allow_abbrev = allow_abbrev
Hai Shif5456382019-09-12 05:56:05 -05001670 self.exit_on_error = exit_on_error
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001671
1672 add_group = self.add_argument_group
1673 self._positionals = add_group(_('positional arguments'))
1674 self._optionals = add_group(_('optional arguments'))
1675 self._subparsers = None
1676
1677 # register types
1678 def identity(string):
1679 return string
1680 self.register('type', None, identity)
1681
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001682 # add help argument if necessary
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001683 # (using explicit default to override global argument_default)
R. David Murray88c49fe2010-08-03 17:56:09 +00001684 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001685 if self.add_help:
1686 self.add_argument(
R. David Murray88c49fe2010-08-03 17:56:09 +00001687 default_prefix+'h', default_prefix*2+'help',
1688 action='help', default=SUPPRESS,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001689 help=_('show this help message and exit'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001690
1691 # add parent arguments and defaults
1692 for parent in parents:
1693 self._add_container_actions(parent)
1694 try:
1695 defaults = parent._defaults
1696 except AttributeError:
1697 pass
1698 else:
1699 self._defaults.update(defaults)
1700
1701 # =======================
1702 # Pretty __repr__ methods
1703 # =======================
1704 def _get_kwargs(self):
1705 names = [
1706 'prog',
1707 'usage',
1708 'description',
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001709 'formatter_class',
1710 'conflict_handler',
1711 'add_help',
1712 ]
1713 return [(name, getattr(self, name)) for name in names]
1714
1715 # ==================================
1716 # Optional/Positional adding methods
1717 # ==================================
1718 def add_subparsers(self, **kwargs):
1719 if self._subparsers is not None:
1720 self.error(_('cannot have multiple subparser arguments'))
1721
1722 # add the parser class to the arguments if it's not present
1723 kwargs.setdefault('parser_class', type(self))
1724
1725 if 'title' in kwargs or 'description' in kwargs:
1726 title = _(kwargs.pop('title', 'subcommands'))
1727 description = _(kwargs.pop('description', None))
1728 self._subparsers = self.add_argument_group(title, description)
1729 else:
1730 self._subparsers = self._positionals
1731
1732 # prog defaults to the usage message of this parser, skipping
1733 # optional arguments and with no "usage:" prefix
1734 if kwargs.get('prog') is None:
1735 formatter = self._get_formatter()
1736 positionals = self._get_positional_actions()
1737 groups = self._mutually_exclusive_groups
1738 formatter.add_usage(self.usage, positionals, groups, '')
1739 kwargs['prog'] = formatter.format_help().strip()
1740
1741 # create the parsers action and add it to the positionals list
1742 parsers_class = self._pop_action_class(kwargs, 'parsers')
1743 action = parsers_class(option_strings=[], **kwargs)
1744 self._subparsers._add_action(action)
1745
1746 # return the created parsers action
1747 return action
1748
1749 def _add_action(self, action):
1750 if action.option_strings:
1751 self._optionals._add_action(action)
1752 else:
1753 self._positionals._add_action(action)
1754 return action
1755
1756 def _get_optional_actions(self):
1757 return [action
1758 for action in self._actions
1759 if action.option_strings]
1760
1761 def _get_positional_actions(self):
1762 return [action
1763 for action in self._actions
1764 if not action.option_strings]
1765
1766 # =====================================
1767 # Command line argument parsing methods
1768 # =====================================
1769 def parse_args(self, args=None, namespace=None):
1770 args, argv = self.parse_known_args(args, namespace)
1771 if argv:
1772 msg = _('unrecognized arguments: %s')
1773 self.error(msg % ' '.join(argv))
1774 return args
1775
1776 def parse_known_args(self, args=None, namespace=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001777 if args is None:
R David Murrayb5228282012-09-08 12:08:01 -04001778 # args default to the system args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001779 args = _sys.argv[1:]
R David Murrayb5228282012-09-08 12:08:01 -04001780 else:
1781 # make sure that args are mutable
1782 args = list(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001783
1784 # default Namespace built from parser defaults
1785 if namespace is None:
1786 namespace = Namespace()
1787
1788 # add any action defaults that aren't present
1789 for action in self._actions:
1790 if action.dest is not SUPPRESS:
1791 if not hasattr(namespace, action.dest):
1792 if action.default is not SUPPRESS:
R David Murray6fb8fb12012-08-31 22:45:20 -04001793 setattr(namespace, action.dest, action.default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001794
1795 # add any parser defaults that aren't present
1796 for dest in self._defaults:
1797 if not hasattr(namespace, dest):
1798 setattr(namespace, dest, self._defaults[dest])
1799
1800 # parse the arguments and exit if there are any errors
Hai Shif5456382019-09-12 05:56:05 -05001801 if self.exit_on_error:
1802 try:
1803 namespace, args = self._parse_known_args(args, namespace)
1804 except ArgumentError:
1805 err = _sys.exc_info()[1]
1806 self.error(str(err))
1807 else:
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001808 namespace, args = self._parse_known_args(args, namespace)
Hai Shif5456382019-09-12 05:56:05 -05001809
1810 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1811 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1812 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1813 return namespace, args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001814
1815 def _parse_known_args(self, arg_strings, namespace):
1816 # replace arg strings that are file references
1817 if self.fromfile_prefix_chars is not None:
1818 arg_strings = self._read_args_from_files(arg_strings)
1819
1820 # map all mutually exclusive arguments to the other arguments
1821 # they can't occur with
1822 action_conflicts = {}
1823 for mutex_group in self._mutually_exclusive_groups:
1824 group_actions = mutex_group._group_actions
1825 for i, mutex_action in enumerate(mutex_group._group_actions):
1826 conflicts = action_conflicts.setdefault(mutex_action, [])
1827 conflicts.extend(group_actions[:i])
1828 conflicts.extend(group_actions[i + 1:])
1829
1830 # find all option indices, and determine the arg_string_pattern
1831 # which has an 'O' if there is an option at an index,
1832 # an 'A' if there is an argument, or a '-' if there is a '--'
1833 option_string_indices = {}
1834 arg_string_pattern_parts = []
1835 arg_strings_iter = iter(arg_strings)
1836 for i, arg_string in enumerate(arg_strings_iter):
1837
1838 # all args after -- are non-options
1839 if arg_string == '--':
1840 arg_string_pattern_parts.append('-')
1841 for arg_string in arg_strings_iter:
1842 arg_string_pattern_parts.append('A')
1843
1844 # otherwise, add the arg to the arg strings
1845 # and note the index if it was an option
1846 else:
1847 option_tuple = self._parse_optional(arg_string)
1848 if option_tuple is None:
1849 pattern = 'A'
1850 else:
1851 option_string_indices[i] = option_tuple
1852 pattern = 'O'
1853 arg_string_pattern_parts.append(pattern)
1854
1855 # join the pieces together to form the pattern
1856 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1857
1858 # converts arg strings to the appropriate and then takes the action
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00001859 seen_actions = set()
1860 seen_non_default_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001861
1862 def take_action(action, argument_strings, option_string=None):
1863 seen_actions.add(action)
1864 argument_values = self._get_values(action, argument_strings)
1865
1866 # error if this argument is not allowed with other previously
1867 # seen arguments, assuming that actions that use the default
1868 # value don't really count as "present"
1869 if argument_values is not action.default:
1870 seen_non_default_actions.add(action)
1871 for conflict_action in action_conflicts.get(action, []):
1872 if conflict_action in seen_non_default_actions:
1873 msg = _('not allowed with argument %s')
1874 action_name = _get_action_name(conflict_action)
1875 raise ArgumentError(action, msg % action_name)
1876
1877 # take the action if we didn't receive a SUPPRESS value
1878 # (e.g. from a default)
1879 if argument_values is not SUPPRESS:
1880 action(self, namespace, argument_values, option_string)
1881
1882 # function to convert arg_strings into an optional action
1883 def consume_optional(start_index):
1884
1885 # get the optional identified at this index
1886 option_tuple = option_string_indices[start_index]
1887 action, option_string, explicit_arg = option_tuple
1888
1889 # identify additional optionals in the same arg string
1890 # (e.g. -xyz is the same as -x -y -z if no args are required)
1891 match_argument = self._match_argument
1892 action_tuples = []
1893 while True:
1894
1895 # if we found no optional action, skip it
1896 if action is None:
1897 extras.append(arg_strings[start_index])
1898 return start_index + 1
1899
1900 # if there is an explicit argument, try to match the
1901 # optional's string arguments to only this
1902 if explicit_arg is not None:
1903 arg_count = match_argument(action, 'A')
1904
1905 # if the action is a single-dash option and takes no
1906 # arguments, try to parse more single-dash options out
1907 # of the tail of the option string
1908 chars = self.prefix_chars
1909 if arg_count == 0 and option_string[1] not in chars:
1910 action_tuples.append((action, [], option_string))
Steven Bethard1ca45a52010-11-01 15:57:36 +00001911 char = option_string[0]
1912 option_string = char + explicit_arg[0]
1913 new_explicit_arg = explicit_arg[1:] or None
1914 optionals_map = self._option_string_actions
1915 if option_string in optionals_map:
1916 action = optionals_map[option_string]
1917 explicit_arg = new_explicit_arg
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001918 else:
1919 msg = _('ignored explicit argument %r')
1920 raise ArgumentError(action, msg % explicit_arg)
1921
1922 # if the action expect exactly one argument, we've
1923 # successfully matched the option; exit the loop
1924 elif arg_count == 1:
1925 stop = start_index + 1
1926 args = [explicit_arg]
1927 action_tuples.append((action, args, option_string))
1928 break
1929
1930 # error if a double-dash option did not use the
1931 # explicit argument
1932 else:
1933 msg = _('ignored explicit argument %r')
1934 raise ArgumentError(action, msg % explicit_arg)
1935
1936 # if there is no explicit argument, try to match the
1937 # optional's string arguments with the following strings
1938 # if successful, exit the loop
1939 else:
1940 start = start_index + 1
1941 selected_patterns = arg_strings_pattern[start:]
1942 arg_count = match_argument(action, selected_patterns)
1943 stop = start + arg_count
1944 args = arg_strings[start:stop]
1945 action_tuples.append((action, args, option_string))
1946 break
1947
1948 # add the Optional to the list and return the index at which
1949 # the Optional's string args stopped
1950 assert action_tuples
1951 for action, args, option_string in action_tuples:
1952 take_action(action, args, option_string)
1953 return stop
1954
1955 # the list of Positionals left to be parsed; this is modified
1956 # by consume_positionals()
1957 positionals = self._get_positional_actions()
1958
1959 # function to convert arg_strings into positional actions
1960 def consume_positionals(start_index):
1961 # match as many Positionals as possible
1962 match_partial = self._match_arguments_partial
1963 selected_pattern = arg_strings_pattern[start_index:]
1964 arg_counts = match_partial(positionals, selected_pattern)
1965
1966 # slice off the appropriate arg strings for each Positional
1967 # and add the Positional and its args to the list
1968 for action, arg_count in zip(positionals, arg_counts):
1969 args = arg_strings[start_index: start_index + arg_count]
1970 start_index += arg_count
1971 take_action(action, args)
1972
1973 # slice off the Positionals that we just parsed and return the
1974 # index at which the Positionals' string args stopped
1975 positionals[:] = positionals[len(arg_counts):]
1976 return start_index
1977
1978 # consume Positionals and Optionals alternately, until we have
1979 # passed the last option string
1980 extras = []
1981 start_index = 0
1982 if option_string_indices:
1983 max_option_string_index = max(option_string_indices)
1984 else:
1985 max_option_string_index = -1
1986 while start_index <= max_option_string_index:
1987
1988 # consume any Positionals preceding the next option
1989 next_option_string_index = min([
1990 index
1991 for index in option_string_indices
1992 if index >= start_index])
1993 if start_index != next_option_string_index:
1994 positionals_end_index = consume_positionals(start_index)
1995
1996 # only try to parse the next optional if we didn't consume
1997 # the option string during the positionals parsing
1998 if positionals_end_index > start_index:
1999 start_index = positionals_end_index
2000 continue
2001 else:
2002 start_index = positionals_end_index
2003
2004 # if we consumed all the positionals we could and we're not
2005 # at the index of an option string, there were extra arguments
2006 if start_index not in option_string_indices:
2007 strings = arg_strings[start_index:next_option_string_index]
2008 extras.extend(strings)
2009 start_index = next_option_string_index
2010
2011 # consume the next optional and any arguments for it
2012 start_index = consume_optional(start_index)
2013
2014 # consume any positionals following the last Optional
2015 stop_index = consume_positionals(start_index)
2016
2017 # if we didn't consume all the argument strings, there were extras
2018 extras.extend(arg_strings[stop_index:])
2019
R David Murray64b0ef12012-08-31 23:09:34 -04002020 # make sure all required actions were present and also convert
2021 # action defaults which were not given as arguments
2022 required_actions = []
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002023 for action in self._actions:
R David Murray6fb8fb12012-08-31 22:45:20 -04002024 if action not in seen_actions:
2025 if action.required:
R David Murray64b0ef12012-08-31 23:09:34 -04002026 required_actions.append(_get_action_name(action))
R David Murray6fb8fb12012-08-31 22:45:20 -04002027 else:
2028 # Convert action default now instead of doing it before
2029 # parsing arguments to avoid calling convert functions
2030 # twice (which may fail) if the argument was given, but
2031 # only if it was defined already in the namespace
2032 if (action.default is not None and
Barry Warsawd89774e2012-09-12 15:31:38 -04002033 isinstance(action.default, str) and
R David Murray64b0ef12012-08-31 23:09:34 -04002034 hasattr(namespace, action.dest) and
2035 action.default is getattr(namespace, action.dest)):
R David Murray6fb8fb12012-08-31 22:45:20 -04002036 setattr(namespace, action.dest,
2037 self._get_value(action, action.default))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002038
R David Murrayf97c59a2011-06-09 12:34:07 -04002039 if required_actions:
2040 self.error(_('the following arguments are required: %s') %
2041 ', '.join(required_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002042
2043 # make sure all required groups had one option present
2044 for group in self._mutually_exclusive_groups:
2045 if group.required:
2046 for action in group._group_actions:
2047 if action in seen_non_default_actions:
2048 break
2049
2050 # if no actions were used, report the error
2051 else:
2052 names = [_get_action_name(action)
2053 for action in group._group_actions
2054 if action.help is not SUPPRESS]
2055 msg = _('one of the arguments %s is required')
2056 self.error(msg % ' '.join(names))
2057
2058 # return the updated namespace and the extra arguments
2059 return namespace, extras
2060
2061 def _read_args_from_files(self, arg_strings):
2062 # expand arguments referencing files
2063 new_arg_strings = []
2064 for arg_string in arg_strings:
2065
2066 # for regular arguments, just add them back into the list
R David Murrayb94082a2012-07-21 22:20:11 -04002067 if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002068 new_arg_strings.append(arg_string)
2069
2070 # replace arguments referencing files with the file content
2071 else:
2072 try:
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01002073 with open(arg_string[1:]) as args_file:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002074 arg_strings = []
2075 for arg_line in args_file.read().splitlines():
2076 for arg in self.convert_arg_line_to_args(arg_line):
2077 arg_strings.append(arg)
2078 arg_strings = self._read_args_from_files(arg_strings)
2079 new_arg_strings.extend(arg_strings)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002080 except OSError:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002081 err = _sys.exc_info()[1]
2082 self.error(str(err))
2083
2084 # return the modified argument list
2085 return new_arg_strings
2086
2087 def convert_arg_line_to_args(self, arg_line):
2088 return [arg_line]
2089
2090 def _match_argument(self, action, arg_strings_pattern):
2091 # match the pattern for this action to the arg strings
2092 nargs_pattern = self._get_nargs_pattern(action)
2093 match = _re.match(nargs_pattern, arg_strings_pattern)
2094
2095 # raise an exception if we weren't able to find a match
2096 if match is None:
2097 nargs_errors = {
2098 None: _('expected one argument'),
2099 OPTIONAL: _('expected at most one argument'),
2100 ONE_OR_MORE: _('expected at least one argument'),
2101 }
Éric Araujo12159152010-12-04 17:31:49 +00002102 default = ngettext('expected %s argument',
2103 'expected %s arguments',
2104 action.nargs) % action.nargs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002105 msg = nargs_errors.get(action.nargs, default)
2106 raise ArgumentError(action, msg)
2107
2108 # return the number of arguments matched
2109 return len(match.group(1))
2110
2111 def _match_arguments_partial(self, actions, arg_strings_pattern):
2112 # progressively shorten the actions list by slicing off the
2113 # final actions until we find a match
2114 result = []
2115 for i in range(len(actions), 0, -1):
2116 actions_slice = actions[:i]
2117 pattern = ''.join([self._get_nargs_pattern(action)
2118 for action in actions_slice])
2119 match = _re.match(pattern, arg_strings_pattern)
2120 if match is not None:
2121 result.extend([len(string) for string in match.groups()])
2122 break
2123
2124 # return the list of arg string counts
2125 return result
2126
2127 def _parse_optional(self, arg_string):
2128 # if it's an empty string, it was meant to be a positional
2129 if not arg_string:
2130 return None
2131
2132 # if it doesn't start with a prefix, it was meant to be positional
2133 if not arg_string[0] in self.prefix_chars:
2134 return None
2135
2136 # if the option string is present in the parser, return the action
2137 if arg_string in self._option_string_actions:
2138 action = self._option_string_actions[arg_string]
2139 return action, arg_string, None
2140
2141 # if it's just a single character, it was meant to be positional
2142 if len(arg_string) == 1:
2143 return None
2144
2145 # if the option string before the "=" is present, return the action
2146 if '=' in arg_string:
2147 option_string, explicit_arg = arg_string.split('=', 1)
2148 if option_string in self._option_string_actions:
2149 action = self._option_string_actions[option_string]
2150 return action, option_string, explicit_arg
2151
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -05002152 if self.allow_abbrev or not arg_string.startswith('--'):
Berker Peksag8089cd62015-02-14 01:39:17 +02002153 # search through all possible prefixes of the option string
2154 # and all actions in the parser for possible interpretations
2155 option_tuples = self._get_option_tuples(arg_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002156
Berker Peksag8089cd62015-02-14 01:39:17 +02002157 # if multiple actions match, the option string was ambiguous
2158 if len(option_tuples) > 1:
2159 options = ', '.join([option_string
2160 for action, option_string, explicit_arg in option_tuples])
2161 args = {'option': arg_string, 'matches': options}
2162 msg = _('ambiguous option: %(option)s could match %(matches)s')
2163 self.error(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002164
Berker Peksag8089cd62015-02-14 01:39:17 +02002165 # if exactly one action matched, this segmentation is good,
2166 # so return the parsed action
2167 elif len(option_tuples) == 1:
2168 option_tuple, = option_tuples
2169 return option_tuple
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002170
2171 # if it was not found as an option, but it looks like a negative
2172 # number, it was meant to be positional
2173 # unless there are negative-number-like options
2174 if self._negative_number_matcher.match(arg_string):
2175 if not self._has_negative_number_optionals:
2176 return None
2177
2178 # if it contains a space, it was meant to be a positional
2179 if ' ' in arg_string:
2180 return None
2181
2182 # it was meant to be an optional but there is no such option
2183 # in this parser (though it might be a valid option in a subparser)
2184 return None, arg_string, None
2185
2186 def _get_option_tuples(self, option_string):
2187 result = []
2188
2189 # option strings starting with two prefix characters are only
2190 # split at the '='
2191 chars = self.prefix_chars
2192 if option_string[0] in chars and option_string[1] in chars:
2193 if '=' in option_string:
2194 option_prefix, explicit_arg = option_string.split('=', 1)
2195 else:
2196 option_prefix = option_string
2197 explicit_arg = None
2198 for option_string in self._option_string_actions:
2199 if option_string.startswith(option_prefix):
2200 action = self._option_string_actions[option_string]
2201 tup = action, option_string, explicit_arg
2202 result.append(tup)
2203
2204 # single character options can be concatenated with their arguments
2205 # but multiple character options always have to have their argument
2206 # separate
2207 elif option_string[0] in chars and option_string[1] not in chars:
2208 option_prefix = option_string
2209 explicit_arg = None
2210 short_option_prefix = option_string[:2]
2211 short_explicit_arg = option_string[2:]
2212
2213 for option_string in self._option_string_actions:
2214 if option_string == short_option_prefix:
2215 action = self._option_string_actions[option_string]
2216 tup = action, option_string, short_explicit_arg
2217 result.append(tup)
2218 elif option_string.startswith(option_prefix):
2219 action = self._option_string_actions[option_string]
2220 tup = action, option_string, explicit_arg
2221 result.append(tup)
2222
2223 # shouldn't ever get here
2224 else:
2225 self.error(_('unexpected option string: %s') % option_string)
2226
2227 # return the collected option tuples
2228 return result
2229
2230 def _get_nargs_pattern(self, action):
2231 # in all examples below, we have to allow for '--' args
2232 # which are represented as '-' in the pattern
2233 nargs = action.nargs
2234
2235 # the default (None) is assumed to be a single argument
2236 if nargs is None:
2237 nargs_pattern = '(-*A-*)'
2238
2239 # allow zero or one arguments
2240 elif nargs == OPTIONAL:
2241 nargs_pattern = '(-*A?-*)'
2242
2243 # allow zero or more arguments
2244 elif nargs == ZERO_OR_MORE:
2245 nargs_pattern = '(-*[A-]*)'
2246
2247 # allow one or more arguments
2248 elif nargs == ONE_OR_MORE:
2249 nargs_pattern = '(-*A[A-]*)'
2250
2251 # allow any number of options or arguments
2252 elif nargs == REMAINDER:
2253 nargs_pattern = '([-AO]*)'
2254
2255 # allow one argument followed by any number of options or arguments
2256 elif nargs == PARSER:
2257 nargs_pattern = '(-*A[-AO]*)'
2258
R. David Murray0f6b9d22017-09-06 20:25:40 -04002259 # suppress action, like nargs=0
2260 elif nargs == SUPPRESS:
2261 nargs_pattern = '(-*-*)'
2262
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002263 # all others should be integers
2264 else:
2265 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2266
2267 # if this is an optional action, -- is not allowed
2268 if action.option_strings:
2269 nargs_pattern = nargs_pattern.replace('-*', '')
2270 nargs_pattern = nargs_pattern.replace('-', '')
2271
2272 # return the pattern
2273 return nargs_pattern
2274
2275 # ========================
R. David Murray0f6b9d22017-09-06 20:25:40 -04002276 # Alt command line argument parsing, allowing free intermix
2277 # ========================
2278
2279 def parse_intermixed_args(self, args=None, namespace=None):
2280 args, argv = self.parse_known_intermixed_args(args, namespace)
2281 if argv:
2282 msg = _('unrecognized arguments: %s')
2283 self.error(msg % ' '.join(argv))
2284 return args
2285
2286 def parse_known_intermixed_args(self, args=None, namespace=None):
2287 # returns a namespace and list of extras
2288 #
2289 # positional can be freely intermixed with optionals. optionals are
2290 # first parsed with all positional arguments deactivated. The 'extras'
2291 # are then parsed. If the parser definition is incompatible with the
2292 # intermixed assumptions (e.g. use of REMAINDER, subparsers) a
2293 # TypeError is raised.
2294 #
2295 # positionals are 'deactivated' by setting nargs and default to
2296 # SUPPRESS. This blocks the addition of that positional to the
2297 # namespace
2298
2299 positionals = self._get_positional_actions()
2300 a = [action for action in positionals
2301 if action.nargs in [PARSER, REMAINDER]]
2302 if a:
2303 raise TypeError('parse_intermixed_args: positional arg'
2304 ' with nargs=%s'%a[0].nargs)
2305
2306 if [action.dest for group in self._mutually_exclusive_groups
2307 for action in group._group_actions if action in positionals]:
2308 raise TypeError('parse_intermixed_args: positional in'
2309 ' mutuallyExclusiveGroup')
2310
2311 try:
2312 save_usage = self.usage
2313 try:
2314 if self.usage is None:
2315 # capture the full usage for use in error messages
2316 self.usage = self.format_usage()[7:]
2317 for action in positionals:
2318 # deactivate positionals
2319 action.save_nargs = action.nargs
2320 # action.nargs = 0
2321 action.nargs = SUPPRESS
2322 action.save_default = action.default
2323 action.default = SUPPRESS
2324 namespace, remaining_args = self.parse_known_args(args,
2325 namespace)
2326 for action in positionals:
2327 # remove the empty positional values from namespace
2328 if (hasattr(namespace, action.dest)
2329 and getattr(namespace, action.dest)==[]):
2330 from warnings import warn
2331 warn('Do not expect %s in %s' % (action.dest, namespace))
2332 delattr(namespace, action.dest)
2333 finally:
2334 # restore nargs and usage before exiting
2335 for action in positionals:
2336 action.nargs = action.save_nargs
2337 action.default = action.save_default
2338 optionals = self._get_optional_actions()
2339 try:
2340 # parse positionals. optionals aren't normally required, but
2341 # they could be, so make sure they aren't.
2342 for action in optionals:
2343 action.save_required = action.required
2344 action.required = False
2345 for group in self._mutually_exclusive_groups:
2346 group.save_required = group.required
2347 group.required = False
2348 namespace, extras = self.parse_known_args(remaining_args,
2349 namespace)
2350 finally:
2351 # restore parser values before exiting
2352 for action in optionals:
2353 action.required = action.save_required
2354 for group in self._mutually_exclusive_groups:
2355 group.required = group.save_required
2356 finally:
2357 self.usage = save_usage
2358 return namespace, extras
2359
2360 # ========================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002361 # Value conversion methods
2362 # ========================
2363 def _get_values(self, action, arg_strings):
R David Murray00528e82012-07-21 22:48:35 -04002364 # for everything but PARSER, REMAINDER args, strip out first '--'
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002365 if action.nargs not in [PARSER, REMAINDER]:
R David Murray00528e82012-07-21 22:48:35 -04002366 try:
2367 arg_strings.remove('--')
2368 except ValueError:
2369 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002370
2371 # optional argument produces a default when not present
2372 if not arg_strings and action.nargs == OPTIONAL:
2373 if action.option_strings:
2374 value = action.const
2375 else:
2376 value = action.default
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00002377 if isinstance(value, str):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002378 value = self._get_value(action, value)
2379 self._check_value(action, value)
2380
2381 # when nargs='*' on a positional, if there were no command-line
2382 # args, use the default if it is anything other than None
2383 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2384 not action.option_strings):
2385 if action.default is not None:
2386 value = action.default
2387 else:
2388 value = arg_strings
2389 self._check_value(action, value)
2390
2391 # single argument or optional argument produces a single value
2392 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2393 arg_string, = arg_strings
2394 value = self._get_value(action, arg_string)
2395 self._check_value(action, value)
2396
2397 # REMAINDER arguments convert all values, checking none
2398 elif action.nargs == REMAINDER:
2399 value = [self._get_value(action, v) for v in arg_strings]
2400
2401 # PARSER arguments convert all values, but check only the first
2402 elif action.nargs == PARSER:
2403 value = [self._get_value(action, v) for v in arg_strings]
2404 self._check_value(action, value[0])
2405
R. David Murray0f6b9d22017-09-06 20:25:40 -04002406 # SUPPRESS argument does not put anything in the namespace
2407 elif action.nargs == SUPPRESS:
2408 value = SUPPRESS
2409
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002410 # all other types of nargs produce a list
2411 else:
2412 value = [self._get_value(action, v) for v in arg_strings]
2413 for v in value:
2414 self._check_value(action, v)
2415
2416 # return the converted value
2417 return value
2418
2419 def _get_value(self, action, arg_string):
2420 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02002421 if not callable(type_func):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002422 msg = _('%r is not callable')
2423 raise ArgumentError(action, msg % type_func)
2424
2425 # convert the value to the appropriate type
2426 try:
2427 result = type_func(arg_string)
2428
2429 # ArgumentTypeErrors indicate errors
2430 except ArgumentTypeError:
2431 name = getattr(action.type, '__name__', repr(action.type))
2432 msg = str(_sys.exc_info()[1])
2433 raise ArgumentError(action, msg)
2434
2435 # TypeErrors or ValueErrors also indicate errors
2436 except (TypeError, ValueError):
2437 name = getattr(action.type, '__name__', repr(action.type))
Éric Araujobb48a8b2010-12-03 19:41:00 +00002438 args = {'type': name, 'value': arg_string}
2439 msg = _('invalid %(type)s value: %(value)r')
2440 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002441
2442 # return the converted value
2443 return result
2444
2445 def _check_value(self, action, value):
2446 # converted value must be one of the choices (if specified)
Vinay Sajip9ae50502016-08-23 08:43:16 +01002447 if action.choices is not None and value not in action.choices:
2448 args = {'value': value,
2449 'choices': ', '.join(map(repr, action.choices))}
2450 msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2451 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002452
2453 # =======================
2454 # Help-formatting methods
2455 # =======================
2456 def format_usage(self):
2457 formatter = self._get_formatter()
2458 formatter.add_usage(self.usage, self._actions,
2459 self._mutually_exclusive_groups)
2460 return formatter.format_help()
2461
2462 def format_help(self):
2463 formatter = self._get_formatter()
2464
2465 # usage
2466 formatter.add_usage(self.usage, self._actions,
2467 self._mutually_exclusive_groups)
2468
2469 # description
2470 formatter.add_text(self.description)
2471
2472 # positionals, optionals and user-defined groups
2473 for action_group in self._action_groups:
2474 formatter.start_section(action_group.title)
2475 formatter.add_text(action_group.description)
2476 formatter.add_arguments(action_group._group_actions)
2477 formatter.end_section()
2478
2479 # epilog
2480 formatter.add_text(self.epilog)
2481
2482 # determine help from format above
2483 return formatter.format_help()
2484
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002485 def _get_formatter(self):
2486 return self.formatter_class(prog=self.prog)
2487
2488 # =====================
2489 # Help-printing methods
2490 # =====================
2491 def print_usage(self, file=None):
2492 if file is None:
2493 file = _sys.stdout
2494 self._print_message(self.format_usage(), file)
2495
2496 def print_help(self, file=None):
2497 if file is None:
2498 file = _sys.stdout
2499 self._print_message(self.format_help(), file)
2500
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002501 def _print_message(self, message, file=None):
2502 if message:
2503 if file is None:
2504 file = _sys.stderr
2505 file.write(message)
2506
2507 # ===============
2508 # Exiting methods
2509 # ===============
2510 def exit(self, status=0, message=None):
2511 if message:
2512 self._print_message(message, _sys.stderr)
2513 _sys.exit(status)
2514
2515 def error(self, message):
2516 """error(message: string)
2517
2518 Prints a usage message incorporating the message to stderr and
2519 exits.
2520
2521 If you override this in a subclass, it should not return -- it
2522 should either exit or raise an exception.
2523 """
2524 self.print_usage(_sys.stderr)
Éric Araujobb48a8b2010-12-03 19:41:00 +00002525 args = {'prog': self.prog, 'message': message}
2526 self.exit(2, _('%(prog)s: error: %(message)s\n') % args)