blob: 456ec8bb7fc86a0c859f9e14407a81ab590a1236 [file] [log] [blame]
Benjamin Peterson2b37fc42010-03-24 22:10:42 +00001# Author: Steven J. Bethard <steven.bethard@gmail.com>.
Miss Islington (bot)c19d6bc2019-08-29 21:27:33 -07002# New maintainer as of 29 August 2019: Raymond Hettinger <raymond.hettinger@gmail.com>
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003
4"""Command-line parsing library
5
6This module is an optparse-inspired command-line parsing library that:
7
8 - handles both optional and positional arguments
9 - produces highly informative usage messages
10 - supports parsers that dispatch to sub-parsers
11
12The following is a simple usage example that sums integers from the
13command-line and writes the result to a file::
14
15 parser = argparse.ArgumentParser(
16 description='sum the integers at the command line')
17 parser.add_argument(
18 'integers', metavar='int', nargs='+', type=int,
19 help='an integer to be summed')
20 parser.add_argument(
21 '--log', default=sys.stdout, type=argparse.FileType('w'),
22 help='the file where the sum should be written')
23 args = parser.parse_args()
24 args.log.write('%s' % sum(args.integers))
25 args.log.close()
26
27The module contains the following public classes:
28
29 - ArgumentParser -- The main entry point for command-line parsing. As the
30 example above shows, the add_argument() method is used to populate
31 the parser with actions for optional and positional arguments. Then
32 the parse_args() method is invoked to convert the args at the
33 command-line into an object with attributes.
34
35 - ArgumentError -- The exception raised by ArgumentParser objects when
36 there are errors with the parser's actions. Errors raised while
37 parsing the command-line are caught by ArgumentParser and emitted
38 as command-line messages.
39
40 - FileType -- A factory for defining types of files to be created. As the
41 example above shows, instances of FileType are typically passed as
42 the type= argument of add_argument() calls.
43
44 - Action -- The base class for parser actions. Typically actions are
45 selected by passing strings like 'store_true' or 'append_const' to
46 the action= argument of add_argument(). However, for greater
47 customization of ArgumentParser actions, subclasses of Action may
48 be defined and passed as the action= argument.
49
50 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
51 ArgumentDefaultsHelpFormatter -- Formatter classes which
52 may be passed as the formatter_class= argument to the
53 ArgumentParser constructor. HelpFormatter is the default,
54 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
55 not to change the formatting for help text, and
56 ArgumentDefaultsHelpFormatter adds information about argument defaults
57 to the help.
58
59All other classes in this module are considered implementation details.
60(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
61considered public as object names -- the API of the formatter objects is
62still considered an implementation detail.)
63"""
64
65__version__ = '1.1'
66__all__ = [
67 'ArgumentParser',
68 'ArgumentError',
Steven Bethard72c55382010-11-01 15:23:12 +000069 'ArgumentTypeError',
Benjamin Peterson698a18a2010-03-02 22:34:37 +000070 'FileType',
71 'HelpFormatter',
Steven Bethard72c55382010-11-01 15:23:12 +000072 'ArgumentDefaultsHelpFormatter',
Benjamin Peterson698a18a2010-03-02 22:34:37 +000073 'RawDescriptionHelpFormatter',
74 'RawTextHelpFormatter',
Steven Bethard0331e902011-03-26 14:48:04 +010075 'MetavarTypeHelpFormatter',
Steven Bethard72c55382010-11-01 15:23:12 +000076 'Namespace',
77 'Action',
78 'ONE_OR_MORE',
79 'OPTIONAL',
80 'PARSER',
81 'REMAINDER',
82 'SUPPRESS',
83 'ZERO_OR_MORE',
Benjamin Peterson698a18a2010-03-02 22:34:37 +000084]
85
86
Benjamin Peterson698a18a2010-03-02 22:34:37 +000087import os as _os
88import re as _re
Berker Peksag74102c92018-07-25 18:23:44 +030089import shutil as _shutil
Benjamin Peterson698a18a2010-03-02 22:34:37 +000090import sys as _sys
Benjamin Peterson698a18a2010-03-02 22:34:37 +000091
Éric Araujo12159152010-12-04 17:31:49 +000092from gettext import gettext as _, ngettext
Benjamin Peterson698a18a2010-03-02 22:34:37 +000093
Benjamin Peterson698a18a2010-03-02 22:34:37 +000094SUPPRESS = '==SUPPRESS=='
95
96OPTIONAL = '?'
97ZERO_OR_MORE = '*'
98ONE_OR_MORE = '+'
99PARSER = 'A...'
100REMAINDER = '...'
Steven Bethardfca2e8a2010-11-02 12:47:22 +0000101_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000102
103# =============================
104# Utility functions and classes
105# =============================
106
107class _AttributeHolder(object):
108 """Abstract base class that provides __repr__.
109
110 The __repr__ method returns a string in the format::
111 ClassName(attr=name, attr=name, ...)
112 The attributes are determined either by a class-level attribute,
113 '_kwarg_names', or by inspecting the instance __dict__.
114 """
115
116 def __repr__(self):
117 type_name = type(self).__name__
118 arg_strings = []
Berker Peksag76b17142015-07-29 23:51:47 +0300119 star_args = {}
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000120 for arg in self._get_args():
121 arg_strings.append(repr(arg))
122 for name, value in self._get_kwargs():
Berker Peksag76b17142015-07-29 23:51:47 +0300123 if name.isidentifier():
124 arg_strings.append('%s=%r' % (name, value))
125 else:
126 star_args[name] = value
127 if star_args:
128 arg_strings.append('**%s' % repr(star_args))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000129 return '%s(%s)' % (type_name, ', '.join(arg_strings))
130
131 def _get_kwargs(self):
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000132 return sorted(self.__dict__.items())
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000133
134 def _get_args(self):
135 return []
136
137
Serhiy Storchaka81108372017-09-26 00:55:55 +0300138def _copy_items(items):
139 if items is None:
140 return []
141 # The copy module is used only in the 'append' and 'append_const'
142 # actions, and it is needed only when the default value isn't a list.
143 # Delay its import for speeding up the common case.
144 if type(items) is list:
145 return items[:]
146 import copy
147 return copy.copy(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000148
149
150# ===============
151# Formatting Help
152# ===============
153
154class HelpFormatter(object):
155 """Formatter for generating usage messages and argument help strings.
156
157 Only the name of this class is considered a public API. All the methods
158 provided by the class are considered an implementation detail.
159 """
160
161 def __init__(self,
162 prog,
163 indent_increment=2,
164 max_help_position=24,
165 width=None):
166
167 # default setting for width
168 if width is None:
Berker Peksag74102c92018-07-25 18:23:44 +0300169 width = _shutil.get_terminal_size().columns
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000170 width -= 2
171
172 self._prog = prog
173 self._indent_increment = indent_increment
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200174 self._max_help_position = min(max_help_position,
175 max(width - 20, indent_increment * 2))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000176 self._width = width
177
178 self._current_indent = 0
179 self._level = 0
180 self._action_max_length = 0
181
182 self._root_section = self._Section(self, None)
183 self._current_section = self._root_section
184
Xiang Zhang7fe28ad2017-01-22 14:37:22 +0800185 self._whitespace_matcher = _re.compile(r'\s+', _re.ASCII)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000186 self._long_break_matcher = _re.compile(r'\n\n\n+')
187
188 # ===============================
189 # Section and indentation methods
190 # ===============================
191 def _indent(self):
192 self._current_indent += self._indent_increment
193 self._level += 1
194
195 def _dedent(self):
196 self._current_indent -= self._indent_increment
197 assert self._current_indent >= 0, 'Indent decreased below 0.'
198 self._level -= 1
199
200 class _Section(object):
201
202 def __init__(self, formatter, parent, heading=None):
203 self.formatter = formatter
204 self.parent = parent
205 self.heading = heading
206 self.items = []
207
208 def format_help(self):
209 # format the indented section
210 if self.parent is not None:
211 self.formatter._indent()
212 join = self.formatter._join_parts
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000213 item_help = join([func(*args) for func, args in self.items])
214 if self.parent is not None:
215 self.formatter._dedent()
216
217 # return nothing if the section was empty
218 if not item_help:
219 return ''
220
221 # add the heading if the section was non-empty
222 if self.heading is not SUPPRESS and self.heading is not None:
223 current_indent = self.formatter._current_indent
224 heading = '%*s%s:\n' % (current_indent, '', self.heading)
225 else:
226 heading = ''
227
228 # join the section-initial newline, the heading and the help
229 return join(['\n', heading, item_help, '\n'])
230
231 def _add_item(self, func, args):
232 self._current_section.items.append((func, args))
233
234 # ========================
235 # Message building methods
236 # ========================
237 def start_section(self, heading):
238 self._indent()
239 section = self._Section(self, self._current_section, heading)
240 self._add_item(section.format_help, [])
241 self._current_section = section
242
243 def end_section(self):
244 self._current_section = self._current_section.parent
245 self._dedent()
246
247 def add_text(self, text):
248 if text is not SUPPRESS and text is not None:
249 self._add_item(self._format_text, [text])
250
251 def add_usage(self, usage, actions, groups, prefix=None):
252 if usage is not SUPPRESS:
253 args = usage, actions, groups, prefix
254 self._add_item(self._format_usage, args)
255
256 def add_argument(self, action):
257 if action.help is not SUPPRESS:
258
259 # find all invocations
260 get_invocation = self._format_action_invocation
261 invocations = [get_invocation(action)]
262 for subaction in self._iter_indented_subactions(action):
263 invocations.append(get_invocation(subaction))
264
265 # update the maximum item length
266 invocation_length = max([len(s) for s in invocations])
267 action_length = invocation_length + self._current_indent
268 self._action_max_length = max(self._action_max_length,
269 action_length)
270
271 # add the item to the list
272 self._add_item(self._format_action, [action])
273
274 def add_arguments(self, actions):
275 for action in actions:
276 self.add_argument(action)
277
278 # =======================
279 # Help-formatting methods
280 # =======================
281 def format_help(self):
282 help = self._root_section.format_help()
283 if help:
284 help = self._long_break_matcher.sub('\n\n', help)
285 help = help.strip('\n') + '\n'
286 return help
287
288 def _join_parts(self, part_strings):
289 return ''.join([part
290 for part in part_strings
291 if part and part is not SUPPRESS])
292
293 def _format_usage(self, usage, actions, groups, prefix):
294 if prefix is None:
295 prefix = _('usage: ')
296
297 # if usage is specified, use that
298 if usage is not None:
299 usage = usage % dict(prog=self._prog)
300
301 # if no optionals or positionals are available, usage is just prog
302 elif usage is None and not actions:
303 usage = '%(prog)s' % dict(prog=self._prog)
304
305 # if optionals and positionals are available, calculate usage
306 elif usage is None:
307 prog = '%(prog)s' % dict(prog=self._prog)
308
309 # split optionals from positionals
310 optionals = []
311 positionals = []
312 for action in actions:
313 if action.option_strings:
314 optionals.append(action)
315 else:
316 positionals.append(action)
317
318 # build full usage string
319 format = self._format_actions_usage
320 action_usage = format(optionals + positionals, groups)
321 usage = ' '.join([s for s in [prog, action_usage] if s])
322
323 # wrap the usage parts if it's too long
324 text_width = self._width - self._current_indent
325 if len(prefix) + len(usage) > text_width:
326
327 # break usage into wrappable parts
wim glenn66f02aa2018-06-08 05:12:49 -0500328 part_regexp = (
329 r'\(.*?\)+(?=\s|$)|'
330 r'\[.*?\]+(?=\s|$)|'
331 r'\S+'
332 )
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000333 opt_usage = format(optionals, groups)
334 pos_usage = format(positionals, groups)
335 opt_parts = _re.findall(part_regexp, opt_usage)
336 pos_parts = _re.findall(part_regexp, pos_usage)
337 assert ' '.join(opt_parts) == opt_usage
338 assert ' '.join(pos_parts) == pos_usage
339
340 # helper for wrapping lines
341 def get_lines(parts, indent, prefix=None):
342 lines = []
343 line = []
344 if prefix is not None:
345 line_len = len(prefix) - 1
346 else:
347 line_len = len(indent) - 1
348 for part in parts:
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200349 if line_len + 1 + len(part) > text_width and line:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000350 lines.append(indent + ' '.join(line))
351 line = []
352 line_len = len(indent) - 1
353 line.append(part)
354 line_len += len(part) + 1
355 if line:
356 lines.append(indent + ' '.join(line))
357 if prefix is not None:
358 lines[0] = lines[0][len(indent):]
359 return lines
360
361 # if prog is short, follow it with optionals or positionals
362 if len(prefix) + len(prog) <= 0.75 * text_width:
363 indent = ' ' * (len(prefix) + len(prog) + 1)
364 if opt_parts:
365 lines = get_lines([prog] + opt_parts, indent, prefix)
366 lines.extend(get_lines(pos_parts, indent))
367 elif pos_parts:
368 lines = get_lines([prog] + pos_parts, indent, prefix)
369 else:
370 lines = [prog]
371
372 # if prog is long, put it on its own line
373 else:
374 indent = ' ' * len(prefix)
375 parts = opt_parts + pos_parts
376 lines = get_lines(parts, indent)
377 if len(lines) > 1:
378 lines = []
379 lines.extend(get_lines(opt_parts, indent))
380 lines.extend(get_lines(pos_parts, indent))
381 lines = [prog] + lines
382
383 # join lines into usage
384 usage = '\n'.join(lines)
385
386 # prefix with 'usage:'
387 return '%s%s\n\n' % (prefix, usage)
388
389 def _format_actions_usage(self, actions, groups):
390 # find group indices and identify actions in groups
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000391 group_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000392 inserts = {}
393 for group in groups:
394 try:
395 start = actions.index(group._group_actions[0])
396 except ValueError:
397 continue
398 else:
399 end = start + len(group._group_actions)
400 if actions[start:end] == group._group_actions:
401 for action in group._group_actions:
402 group_actions.add(action)
403 if not group.required:
Steven Bethard49998ee2010-11-01 16:29:26 +0000404 if start in inserts:
405 inserts[start] += ' ['
406 else:
407 inserts[start] = '['
Raymond Hettingerbd8ca9a2019-08-30 15:25:38 -0700408 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] = '('
Raymond Hettingerbd8ca9a2019-08-30 15:25:38 -0700417 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:
Miss Islington (bot)1cc70322019-08-01 22:16:44 -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:
Miss Islington (bot)1cc70322019-08-01 22:16:44 -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:
Miss Islington (bot)1cc70322019-08-01 22:16:44 -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:
Steven Bethardb0270112011-01-24 21:02:50 +00001217 message = _("can't open '%s': %s")
1218 raise ArgumentTypeError(message % (string, e))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001219
1220 def __repr__(self):
Steven Bethardb0270112011-01-24 21:02:50 +00001221 args = self._mode, self._bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001222 kwargs = [('encoding', self._encoding), ('errors', self._errors)]
1223 args_str = ', '.join([repr(arg) for arg in args if arg != -1] +
1224 ['%s=%r' % (kw, arg) for kw, arg in kwargs
1225 if arg is not None])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001226 return '%s(%s)' % (type(self).__name__, args_str)
1227
1228# ===========================
1229# Optional and Positional Parsing
1230# ===========================
1231
1232class Namespace(_AttributeHolder):
1233 """Simple object for storing attributes.
1234
1235 Implements equality by attribute names and values, and provides a simple
1236 string representation.
1237 """
1238
1239 def __init__(self, **kwargs):
1240 for name in kwargs:
1241 setattr(self, name, kwargs[name])
1242
1243 def __eq__(self, other):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07001244 if not isinstance(other, Namespace):
1245 return NotImplemented
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001246 return vars(self) == vars(other)
1247
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001248 def __contains__(self, key):
1249 return key in self.__dict__
1250
1251
1252class _ActionsContainer(object):
1253
1254 def __init__(self,
1255 description,
1256 prefix_chars,
1257 argument_default,
1258 conflict_handler):
1259 super(_ActionsContainer, self).__init__()
1260
1261 self.description = description
1262 self.argument_default = argument_default
1263 self.prefix_chars = prefix_chars
1264 self.conflict_handler = conflict_handler
1265
1266 # set up registries
1267 self._registries = {}
1268
1269 # register actions
1270 self.register('action', None, _StoreAction)
1271 self.register('action', 'store', _StoreAction)
1272 self.register('action', 'store_const', _StoreConstAction)
1273 self.register('action', 'store_true', _StoreTrueAction)
1274 self.register('action', 'store_false', _StoreFalseAction)
1275 self.register('action', 'append', _AppendAction)
1276 self.register('action', 'append_const', _AppendConstAction)
1277 self.register('action', 'count', _CountAction)
1278 self.register('action', 'help', _HelpAction)
1279 self.register('action', 'version', _VersionAction)
1280 self.register('action', 'parsers', _SubParsersAction)
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001281 self.register('action', 'extend', _ExtendAction)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001282
1283 # raise an exception if the conflict handler is invalid
1284 self._get_handler()
1285
1286 # action storage
1287 self._actions = []
1288 self._option_string_actions = {}
1289
1290 # groups
1291 self._action_groups = []
1292 self._mutually_exclusive_groups = []
1293
1294 # defaults storage
1295 self._defaults = {}
1296
1297 # determines whether an "option" looks like a negative number
1298 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1299
1300 # whether or not there are any optionals that look like negative
1301 # numbers -- uses a list so it can be shared and edited
1302 self._has_negative_number_optionals = []
1303
1304 # ====================
1305 # Registration methods
1306 # ====================
1307 def register(self, registry_name, value, object):
1308 registry = self._registries.setdefault(registry_name, {})
1309 registry[value] = object
1310
1311 def _registry_get(self, registry_name, value, default=None):
1312 return self._registries[registry_name].get(value, default)
1313
1314 # ==================================
1315 # Namespace default accessor methods
1316 # ==================================
1317 def set_defaults(self, **kwargs):
1318 self._defaults.update(kwargs)
1319
1320 # if these defaults match any existing arguments, replace
1321 # the previous default on the object with the new one
1322 for action in self._actions:
1323 if action.dest in kwargs:
1324 action.default = kwargs[action.dest]
1325
1326 def get_default(self, dest):
1327 for action in self._actions:
1328 if action.dest == dest and action.default is not None:
1329 return action.default
1330 return self._defaults.get(dest, None)
1331
1332
1333 # =======================
1334 # Adding argument actions
1335 # =======================
1336 def add_argument(self, *args, **kwargs):
1337 """
1338 add_argument(dest, ..., name=value, ...)
1339 add_argument(option_string, option_string, ..., name=value, ...)
1340 """
1341
1342 # if no positional args are supplied or only one is supplied and
1343 # it doesn't look like an option string, parse a positional
1344 # argument
1345 chars = self.prefix_chars
1346 if not args or len(args) == 1 and args[0][0] not in chars:
1347 if args and 'dest' in kwargs:
1348 raise ValueError('dest supplied twice for positional argument')
1349 kwargs = self._get_positional_kwargs(*args, **kwargs)
1350
1351 # otherwise, we're adding an optional argument
1352 else:
1353 kwargs = self._get_optional_kwargs(*args, **kwargs)
1354
1355 # if no default was supplied, use the parser-level default
1356 if 'default' not in kwargs:
1357 dest = kwargs['dest']
1358 if dest in self._defaults:
1359 kwargs['default'] = self._defaults[dest]
1360 elif self.argument_default is not None:
1361 kwargs['default'] = self.argument_default
1362
1363 # create the action object, and add it to the parser
1364 action_class = self._pop_action_class(kwargs)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001365 if not callable(action_class):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001366 raise ValueError('unknown action "%s"' % (action_class,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001367 action = action_class(**kwargs)
1368
1369 # raise an error if the action type is not callable
1370 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001371 if not callable(type_func):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001372 raise ValueError('%r is not callable' % (type_func,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001373
Miss Islington (bot)606ac582019-06-07 14:11:59 -07001374 if type_func is FileType:
1375 raise ValueError('%r is a FileType class object, instance of it'
1376 ' must be passed' % (type_func,))
1377
Steven Bethard8d9a4622011-03-26 17:33:56 +01001378 # raise an error if the metavar does not match the type
1379 if hasattr(self, "_get_formatter"):
1380 try:
1381 self._get_formatter()._format_args(action, None)
1382 except TypeError:
1383 raise ValueError("length of metavar tuple does not match nargs")
1384
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001385 return self._add_action(action)
1386
1387 def add_argument_group(self, *args, **kwargs):
1388 group = _ArgumentGroup(self, *args, **kwargs)
1389 self._action_groups.append(group)
1390 return group
1391
1392 def add_mutually_exclusive_group(self, **kwargs):
1393 group = _MutuallyExclusiveGroup(self, **kwargs)
1394 self._mutually_exclusive_groups.append(group)
1395 return group
1396
1397 def _add_action(self, action):
1398 # resolve any conflicts
1399 self._check_conflict(action)
1400
1401 # add to actions list
1402 self._actions.append(action)
1403 action.container = self
1404
1405 # index the action by any option strings it has
1406 for option_string in action.option_strings:
1407 self._option_string_actions[option_string] = action
1408
1409 # set the flag if any option strings look like negative numbers
1410 for option_string in action.option_strings:
1411 if self._negative_number_matcher.match(option_string):
1412 if not self._has_negative_number_optionals:
1413 self._has_negative_number_optionals.append(True)
1414
1415 # return the created action
1416 return action
1417
1418 def _remove_action(self, action):
1419 self._actions.remove(action)
1420
1421 def _add_container_actions(self, container):
1422 # collect groups by titles
1423 title_group_map = {}
1424 for group in self._action_groups:
1425 if group.title in title_group_map:
1426 msg = _('cannot merge actions - two groups are named %r')
1427 raise ValueError(msg % (group.title))
1428 title_group_map[group.title] = group
1429
1430 # map each action to its group
1431 group_map = {}
1432 for group in container._action_groups:
1433
1434 # if a group with the title exists, use that, otherwise
1435 # create a new group matching the container's group
1436 if group.title not in title_group_map:
1437 title_group_map[group.title] = self.add_argument_group(
1438 title=group.title,
1439 description=group.description,
1440 conflict_handler=group.conflict_handler)
1441
1442 # map the actions to their new group
1443 for action in group._group_actions:
1444 group_map[action] = title_group_map[group.title]
1445
1446 # add container's mutually exclusive groups
1447 # NOTE: if add_mutually_exclusive_group ever gains title= and
1448 # description= then this code will need to be expanded as above
1449 for group in container._mutually_exclusive_groups:
1450 mutex_group = self.add_mutually_exclusive_group(
1451 required=group.required)
1452
1453 # map the actions to their new mutex group
1454 for action in group._group_actions:
1455 group_map[action] = mutex_group
1456
1457 # add all actions to this container or their group
1458 for action in container._actions:
1459 group_map.get(action, self)._add_action(action)
1460
1461 def _get_positional_kwargs(self, dest, **kwargs):
1462 # make sure required is not specified
1463 if 'required' in kwargs:
1464 msg = _("'required' is an invalid argument for positionals")
1465 raise TypeError(msg)
1466
1467 # mark positional arguments as required if at least one is
1468 # always required
1469 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1470 kwargs['required'] = True
1471 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1472 kwargs['required'] = True
1473
1474 # return the keyword arguments with no option strings
1475 return dict(kwargs, dest=dest, option_strings=[])
1476
1477 def _get_optional_kwargs(self, *args, **kwargs):
1478 # determine short and long option strings
1479 option_strings = []
1480 long_option_strings = []
1481 for option_string in args:
1482 # error on strings that don't start with an appropriate prefix
1483 if not option_string[0] in self.prefix_chars:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001484 args = {'option': option_string,
1485 'prefix_chars': self.prefix_chars}
1486 msg = _('invalid option string %(option)r: '
1487 'must start with a character %(prefix_chars)r')
1488 raise ValueError(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001489
1490 # strings starting with two prefix characters are long options
1491 option_strings.append(option_string)
1492 if option_string[0] in self.prefix_chars:
1493 if len(option_string) > 1:
1494 if option_string[1] in self.prefix_chars:
1495 long_option_strings.append(option_string)
1496
1497 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1498 dest = kwargs.pop('dest', None)
1499 if dest is None:
1500 if long_option_strings:
1501 dest_option_string = long_option_strings[0]
1502 else:
1503 dest_option_string = option_strings[0]
1504 dest = dest_option_string.lstrip(self.prefix_chars)
1505 if not dest:
1506 msg = _('dest= is required for options like %r')
1507 raise ValueError(msg % option_string)
1508 dest = dest.replace('-', '_')
1509
1510 # return the updated keyword arguments
1511 return dict(kwargs, dest=dest, option_strings=option_strings)
1512
1513 def _pop_action_class(self, kwargs, default=None):
1514 action = kwargs.pop('action', default)
1515 return self._registry_get('action', action, action)
1516
1517 def _get_handler(self):
1518 # determine function from conflict handler string
1519 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1520 try:
1521 return getattr(self, handler_func_name)
1522 except AttributeError:
1523 msg = _('invalid conflict_resolution value: %r')
1524 raise ValueError(msg % self.conflict_handler)
1525
1526 def _check_conflict(self, action):
1527
1528 # find all options that conflict with this option
1529 confl_optionals = []
1530 for option_string in action.option_strings:
1531 if option_string in self._option_string_actions:
1532 confl_optional = self._option_string_actions[option_string]
1533 confl_optionals.append((option_string, confl_optional))
1534
1535 # resolve any conflicts
1536 if confl_optionals:
1537 conflict_handler = self._get_handler()
1538 conflict_handler(action, confl_optionals)
1539
1540 def _handle_conflict_error(self, action, conflicting_actions):
Éric Araujo12159152010-12-04 17:31:49 +00001541 message = ngettext('conflicting option string: %s',
1542 'conflicting option strings: %s',
1543 len(conflicting_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001544 conflict_string = ', '.join([option_string
1545 for option_string, action
1546 in conflicting_actions])
1547 raise ArgumentError(action, message % conflict_string)
1548
1549 def _handle_conflict_resolve(self, action, conflicting_actions):
1550
1551 # remove all conflicting options
1552 for option_string, action in conflicting_actions:
1553
1554 # remove the conflicting option
1555 action.option_strings.remove(option_string)
1556 self._option_string_actions.pop(option_string, None)
1557
1558 # if the option now has no option string, remove it from the
1559 # container holding it
1560 if not action.option_strings:
1561 action.container._remove_action(action)
1562
1563
1564class _ArgumentGroup(_ActionsContainer):
1565
1566 def __init__(self, container, title=None, description=None, **kwargs):
1567 # add any missing keyword arguments by checking the container
1568 update = kwargs.setdefault
1569 update('conflict_handler', container.conflict_handler)
1570 update('prefix_chars', container.prefix_chars)
1571 update('argument_default', container.argument_default)
1572 super_init = super(_ArgumentGroup, self).__init__
1573 super_init(description=description, **kwargs)
1574
1575 # group attributes
1576 self.title = title
1577 self._group_actions = []
1578
1579 # share most attributes with the container
1580 self._registries = container._registries
1581 self._actions = container._actions
1582 self._option_string_actions = container._option_string_actions
1583 self._defaults = container._defaults
1584 self._has_negative_number_optionals = \
1585 container._has_negative_number_optionals
Georg Brandl0f6b47a2011-01-30 12:19:35 +00001586 self._mutually_exclusive_groups = container._mutually_exclusive_groups
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001587
1588 def _add_action(self, action):
1589 action = super(_ArgumentGroup, self)._add_action(action)
1590 self._group_actions.append(action)
1591 return action
1592
1593 def _remove_action(self, action):
1594 super(_ArgumentGroup, self)._remove_action(action)
1595 self._group_actions.remove(action)
1596
1597
1598class _MutuallyExclusiveGroup(_ArgumentGroup):
1599
1600 def __init__(self, container, required=False):
1601 super(_MutuallyExclusiveGroup, self).__init__(container)
1602 self.required = required
1603 self._container = container
1604
1605 def _add_action(self, action):
1606 if action.required:
1607 msg = _('mutually exclusive arguments must be optional')
1608 raise ValueError(msg)
1609 action = self._container._add_action(action)
1610 self._group_actions.append(action)
1611 return action
1612
1613 def _remove_action(self, action):
1614 self._container._remove_action(action)
1615 self._group_actions.remove(action)
1616
1617
1618class ArgumentParser(_AttributeHolder, _ActionsContainer):
1619 """Object for parsing command line strings into Python objects.
1620
1621 Keyword Arguments:
1622 - prog -- The name of the program (default: sys.argv[0])
1623 - usage -- A usage message (default: auto-generated from arguments)
1624 - description -- A description of what the program does
1625 - epilog -- Text following the argument descriptions
1626 - parents -- Parsers whose arguments should be copied into this one
1627 - formatter_class -- HelpFormatter class for printing help messages
1628 - prefix_chars -- Characters that prefix optional arguments
1629 - fromfile_prefix_chars -- Characters that prefix files containing
1630 additional arguments
1631 - argument_default -- The default value for all arguments
1632 - conflict_handler -- String indicating how to handle conflicts
1633 - add_help -- Add a -h/-help option
Berker Peksag8089cd62015-02-14 01:39:17 +02001634 - allow_abbrev -- Allow long options to be abbreviated unambiguously
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001635 """
1636
1637 def __init__(self,
1638 prog=None,
1639 usage=None,
1640 description=None,
1641 epilog=None,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001642 parents=[],
1643 formatter_class=HelpFormatter,
1644 prefix_chars='-',
1645 fromfile_prefix_chars=None,
1646 argument_default=None,
1647 conflict_handler='error',
Berker Peksag8089cd62015-02-14 01:39:17 +02001648 add_help=True,
1649 allow_abbrev=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001650
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001651 superinit = super(ArgumentParser, self).__init__
1652 superinit(description=description,
1653 prefix_chars=prefix_chars,
1654 argument_default=argument_default,
1655 conflict_handler=conflict_handler)
1656
1657 # default setting for prog
1658 if prog is None:
1659 prog = _os.path.basename(_sys.argv[0])
1660
1661 self.prog = prog
1662 self.usage = usage
1663 self.epilog = epilog
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001664 self.formatter_class = formatter_class
1665 self.fromfile_prefix_chars = fromfile_prefix_chars
1666 self.add_help = add_help
Berker Peksag8089cd62015-02-14 01:39:17 +02001667 self.allow_abbrev = allow_abbrev
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001668
1669 add_group = self.add_argument_group
1670 self._positionals = add_group(_('positional arguments'))
1671 self._optionals = add_group(_('optional arguments'))
1672 self._subparsers = None
1673
1674 # register types
1675 def identity(string):
1676 return string
1677 self.register('type', None, identity)
1678
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001679 # add help argument if necessary
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001680 # (using explicit default to override global argument_default)
R. David Murray88c49fe2010-08-03 17:56:09 +00001681 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001682 if self.add_help:
1683 self.add_argument(
R. David Murray88c49fe2010-08-03 17:56:09 +00001684 default_prefix+'h', default_prefix*2+'help',
1685 action='help', default=SUPPRESS,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001686 help=_('show this help message and exit'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001687
1688 # add parent arguments and defaults
1689 for parent in parents:
1690 self._add_container_actions(parent)
1691 try:
1692 defaults = parent._defaults
1693 except AttributeError:
1694 pass
1695 else:
1696 self._defaults.update(defaults)
1697
1698 # =======================
1699 # Pretty __repr__ methods
1700 # =======================
1701 def _get_kwargs(self):
1702 names = [
1703 'prog',
1704 'usage',
1705 'description',
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001706 'formatter_class',
1707 'conflict_handler',
1708 'add_help',
1709 ]
1710 return [(name, getattr(self, name)) for name in names]
1711
1712 # ==================================
1713 # Optional/Positional adding methods
1714 # ==================================
1715 def add_subparsers(self, **kwargs):
1716 if self._subparsers is not None:
1717 self.error(_('cannot have multiple subparser arguments'))
1718
1719 # add the parser class to the arguments if it's not present
1720 kwargs.setdefault('parser_class', type(self))
1721
1722 if 'title' in kwargs or 'description' in kwargs:
1723 title = _(kwargs.pop('title', 'subcommands'))
1724 description = _(kwargs.pop('description', None))
1725 self._subparsers = self.add_argument_group(title, description)
1726 else:
1727 self._subparsers = self._positionals
1728
1729 # prog defaults to the usage message of this parser, skipping
1730 # optional arguments and with no "usage:" prefix
1731 if kwargs.get('prog') is None:
1732 formatter = self._get_formatter()
1733 positionals = self._get_positional_actions()
1734 groups = self._mutually_exclusive_groups
1735 formatter.add_usage(self.usage, positionals, groups, '')
1736 kwargs['prog'] = formatter.format_help().strip()
1737
1738 # create the parsers action and add it to the positionals list
1739 parsers_class = self._pop_action_class(kwargs, 'parsers')
1740 action = parsers_class(option_strings=[], **kwargs)
1741 self._subparsers._add_action(action)
1742
1743 # return the created parsers action
1744 return action
1745
1746 def _add_action(self, action):
1747 if action.option_strings:
1748 self._optionals._add_action(action)
1749 else:
1750 self._positionals._add_action(action)
1751 return action
1752
1753 def _get_optional_actions(self):
1754 return [action
1755 for action in self._actions
1756 if action.option_strings]
1757
1758 def _get_positional_actions(self):
1759 return [action
1760 for action in self._actions
1761 if not action.option_strings]
1762
1763 # =====================================
1764 # Command line argument parsing methods
1765 # =====================================
1766 def parse_args(self, args=None, namespace=None):
1767 args, argv = self.parse_known_args(args, namespace)
1768 if argv:
1769 msg = _('unrecognized arguments: %s')
1770 self.error(msg % ' '.join(argv))
1771 return args
1772
1773 def parse_known_args(self, args=None, namespace=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001774 if args is None:
R David Murrayb5228282012-09-08 12:08:01 -04001775 # args default to the system args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001776 args = _sys.argv[1:]
R David Murrayb5228282012-09-08 12:08:01 -04001777 else:
1778 # make sure that args are mutable
1779 args = list(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001780
1781 # default Namespace built from parser defaults
1782 if namespace is None:
1783 namespace = Namespace()
1784
1785 # add any action defaults that aren't present
1786 for action in self._actions:
1787 if action.dest is not SUPPRESS:
1788 if not hasattr(namespace, action.dest):
1789 if action.default is not SUPPRESS:
R David Murray6fb8fb12012-08-31 22:45:20 -04001790 setattr(namespace, action.dest, action.default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001791
1792 # add any parser defaults that aren't present
1793 for dest in self._defaults:
1794 if not hasattr(namespace, dest):
1795 setattr(namespace, dest, self._defaults[dest])
1796
1797 # parse the arguments and exit if there are any errors
1798 try:
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001799 namespace, args = self._parse_known_args(args, namespace)
1800 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1801 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1802 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1803 return namespace, args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001804 except ArgumentError:
1805 err = _sys.exc_info()[1]
1806 self.error(str(err))
1807
1808 def _parse_known_args(self, arg_strings, namespace):
1809 # replace arg strings that are file references
1810 if self.fromfile_prefix_chars is not None:
1811 arg_strings = self._read_args_from_files(arg_strings)
1812
1813 # map all mutually exclusive arguments to the other arguments
1814 # they can't occur with
1815 action_conflicts = {}
1816 for mutex_group in self._mutually_exclusive_groups:
1817 group_actions = mutex_group._group_actions
1818 for i, mutex_action in enumerate(mutex_group._group_actions):
1819 conflicts = action_conflicts.setdefault(mutex_action, [])
1820 conflicts.extend(group_actions[:i])
1821 conflicts.extend(group_actions[i + 1:])
1822
1823 # find all option indices, and determine the arg_string_pattern
1824 # which has an 'O' if there is an option at an index,
1825 # an 'A' if there is an argument, or a '-' if there is a '--'
1826 option_string_indices = {}
1827 arg_string_pattern_parts = []
1828 arg_strings_iter = iter(arg_strings)
1829 for i, arg_string in enumerate(arg_strings_iter):
1830
1831 # all args after -- are non-options
1832 if arg_string == '--':
1833 arg_string_pattern_parts.append('-')
1834 for arg_string in arg_strings_iter:
1835 arg_string_pattern_parts.append('A')
1836
1837 # otherwise, add the arg to the arg strings
1838 # and note the index if it was an option
1839 else:
1840 option_tuple = self._parse_optional(arg_string)
1841 if option_tuple is None:
1842 pattern = 'A'
1843 else:
1844 option_string_indices[i] = option_tuple
1845 pattern = 'O'
1846 arg_string_pattern_parts.append(pattern)
1847
1848 # join the pieces together to form the pattern
1849 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1850
1851 # converts arg strings to the appropriate and then takes the action
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00001852 seen_actions = set()
1853 seen_non_default_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001854
1855 def take_action(action, argument_strings, option_string=None):
1856 seen_actions.add(action)
1857 argument_values = self._get_values(action, argument_strings)
1858
1859 # error if this argument is not allowed with other previously
1860 # seen arguments, assuming that actions that use the default
1861 # value don't really count as "present"
1862 if argument_values is not action.default:
1863 seen_non_default_actions.add(action)
1864 for conflict_action in action_conflicts.get(action, []):
1865 if conflict_action in seen_non_default_actions:
1866 msg = _('not allowed with argument %s')
1867 action_name = _get_action_name(conflict_action)
1868 raise ArgumentError(action, msg % action_name)
1869
1870 # take the action if we didn't receive a SUPPRESS value
1871 # (e.g. from a default)
1872 if argument_values is not SUPPRESS:
1873 action(self, namespace, argument_values, option_string)
1874
1875 # function to convert arg_strings into an optional action
1876 def consume_optional(start_index):
1877
1878 # get the optional identified at this index
1879 option_tuple = option_string_indices[start_index]
1880 action, option_string, explicit_arg = option_tuple
1881
1882 # identify additional optionals in the same arg string
1883 # (e.g. -xyz is the same as -x -y -z if no args are required)
1884 match_argument = self._match_argument
1885 action_tuples = []
1886 while True:
1887
1888 # if we found no optional action, skip it
1889 if action is None:
1890 extras.append(arg_strings[start_index])
1891 return start_index + 1
1892
1893 # if there is an explicit argument, try to match the
1894 # optional's string arguments to only this
1895 if explicit_arg is not None:
1896 arg_count = match_argument(action, 'A')
1897
1898 # if the action is a single-dash option and takes no
1899 # arguments, try to parse more single-dash options out
1900 # of the tail of the option string
1901 chars = self.prefix_chars
1902 if arg_count == 0 and option_string[1] not in chars:
1903 action_tuples.append((action, [], option_string))
Steven Bethard1ca45a52010-11-01 15:57:36 +00001904 char = option_string[0]
1905 option_string = char + explicit_arg[0]
1906 new_explicit_arg = explicit_arg[1:] or None
1907 optionals_map = self._option_string_actions
1908 if option_string in optionals_map:
1909 action = optionals_map[option_string]
1910 explicit_arg = new_explicit_arg
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001911 else:
1912 msg = _('ignored explicit argument %r')
1913 raise ArgumentError(action, msg % explicit_arg)
1914
1915 # if the action expect exactly one argument, we've
1916 # successfully matched the option; exit the loop
1917 elif arg_count == 1:
1918 stop = start_index + 1
1919 args = [explicit_arg]
1920 action_tuples.append((action, args, option_string))
1921 break
1922
1923 # error if a double-dash option did not use the
1924 # explicit argument
1925 else:
1926 msg = _('ignored explicit argument %r')
1927 raise ArgumentError(action, msg % explicit_arg)
1928
1929 # if there is no explicit argument, try to match the
1930 # optional's string arguments with the following strings
1931 # if successful, exit the loop
1932 else:
1933 start = start_index + 1
1934 selected_patterns = arg_strings_pattern[start:]
1935 arg_count = match_argument(action, selected_patterns)
1936 stop = start + arg_count
1937 args = arg_strings[start:stop]
1938 action_tuples.append((action, args, option_string))
1939 break
1940
1941 # add the Optional to the list and return the index at which
1942 # the Optional's string args stopped
1943 assert action_tuples
1944 for action, args, option_string in action_tuples:
1945 take_action(action, args, option_string)
1946 return stop
1947
1948 # the list of Positionals left to be parsed; this is modified
1949 # by consume_positionals()
1950 positionals = self._get_positional_actions()
1951
1952 # function to convert arg_strings into positional actions
1953 def consume_positionals(start_index):
1954 # match as many Positionals as possible
1955 match_partial = self._match_arguments_partial
1956 selected_pattern = arg_strings_pattern[start_index:]
1957 arg_counts = match_partial(positionals, selected_pattern)
1958
1959 # slice off the appropriate arg strings for each Positional
1960 # and add the Positional and its args to the list
1961 for action, arg_count in zip(positionals, arg_counts):
1962 args = arg_strings[start_index: start_index + arg_count]
1963 start_index += arg_count
1964 take_action(action, args)
1965
1966 # slice off the Positionals that we just parsed and return the
1967 # index at which the Positionals' string args stopped
1968 positionals[:] = positionals[len(arg_counts):]
1969 return start_index
1970
1971 # consume Positionals and Optionals alternately, until we have
1972 # passed the last option string
1973 extras = []
1974 start_index = 0
1975 if option_string_indices:
1976 max_option_string_index = max(option_string_indices)
1977 else:
1978 max_option_string_index = -1
1979 while start_index <= max_option_string_index:
1980
1981 # consume any Positionals preceding the next option
1982 next_option_string_index = min([
1983 index
1984 for index in option_string_indices
1985 if index >= start_index])
1986 if start_index != next_option_string_index:
1987 positionals_end_index = consume_positionals(start_index)
1988
1989 # only try to parse the next optional if we didn't consume
1990 # the option string during the positionals parsing
1991 if positionals_end_index > start_index:
1992 start_index = positionals_end_index
1993 continue
1994 else:
1995 start_index = positionals_end_index
1996
1997 # if we consumed all the positionals we could and we're not
1998 # at the index of an option string, there were extra arguments
1999 if start_index not in option_string_indices:
2000 strings = arg_strings[start_index:next_option_string_index]
2001 extras.extend(strings)
2002 start_index = next_option_string_index
2003
2004 # consume the next optional and any arguments for it
2005 start_index = consume_optional(start_index)
2006
2007 # consume any positionals following the last Optional
2008 stop_index = consume_positionals(start_index)
2009
2010 # if we didn't consume all the argument strings, there were extras
2011 extras.extend(arg_strings[stop_index:])
2012
R David Murray64b0ef12012-08-31 23:09:34 -04002013 # make sure all required actions were present and also convert
2014 # action defaults which were not given as arguments
2015 required_actions = []
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002016 for action in self._actions:
R David Murray6fb8fb12012-08-31 22:45:20 -04002017 if action not in seen_actions:
2018 if action.required:
R David Murray64b0ef12012-08-31 23:09:34 -04002019 required_actions.append(_get_action_name(action))
R David Murray6fb8fb12012-08-31 22:45:20 -04002020 else:
2021 # Convert action default now instead of doing it before
2022 # parsing arguments to avoid calling convert functions
2023 # twice (which may fail) if the argument was given, but
2024 # only if it was defined already in the namespace
2025 if (action.default is not None and
Barry Warsawd89774e2012-09-12 15:31:38 -04002026 isinstance(action.default, str) and
R David Murray64b0ef12012-08-31 23:09:34 -04002027 hasattr(namespace, action.dest) and
2028 action.default is getattr(namespace, action.dest)):
R David Murray6fb8fb12012-08-31 22:45:20 -04002029 setattr(namespace, action.dest,
2030 self._get_value(action, action.default))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002031
R David Murrayf97c59a2011-06-09 12:34:07 -04002032 if required_actions:
2033 self.error(_('the following arguments are required: %s') %
2034 ', '.join(required_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002035
2036 # make sure all required groups had one option present
2037 for group in self._mutually_exclusive_groups:
2038 if group.required:
2039 for action in group._group_actions:
2040 if action in seen_non_default_actions:
2041 break
2042
2043 # if no actions were used, report the error
2044 else:
2045 names = [_get_action_name(action)
2046 for action in group._group_actions
2047 if action.help is not SUPPRESS]
2048 msg = _('one of the arguments %s is required')
2049 self.error(msg % ' '.join(names))
2050
2051 # return the updated namespace and the extra arguments
2052 return namespace, extras
2053
2054 def _read_args_from_files(self, arg_strings):
2055 # expand arguments referencing files
2056 new_arg_strings = []
2057 for arg_string in arg_strings:
2058
2059 # for regular arguments, just add them back into the list
R David Murrayb94082a2012-07-21 22:20:11 -04002060 if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002061 new_arg_strings.append(arg_string)
2062
2063 # replace arguments referencing files with the file content
2064 else:
2065 try:
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01002066 with open(arg_string[1:]) as args_file:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002067 arg_strings = []
2068 for arg_line in args_file.read().splitlines():
2069 for arg in self.convert_arg_line_to_args(arg_line):
2070 arg_strings.append(arg)
2071 arg_strings = self._read_args_from_files(arg_strings)
2072 new_arg_strings.extend(arg_strings)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002073 except OSError:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002074 err = _sys.exc_info()[1]
2075 self.error(str(err))
2076
2077 # return the modified argument list
2078 return new_arg_strings
2079
2080 def convert_arg_line_to_args(self, arg_line):
2081 return [arg_line]
2082
2083 def _match_argument(self, action, arg_strings_pattern):
2084 # match the pattern for this action to the arg strings
2085 nargs_pattern = self._get_nargs_pattern(action)
2086 match = _re.match(nargs_pattern, arg_strings_pattern)
2087
2088 # raise an exception if we weren't able to find a match
2089 if match is None:
2090 nargs_errors = {
2091 None: _('expected one argument'),
2092 OPTIONAL: _('expected at most one argument'),
2093 ONE_OR_MORE: _('expected at least one argument'),
2094 }
Éric Araujo12159152010-12-04 17:31:49 +00002095 default = ngettext('expected %s argument',
2096 'expected %s arguments',
2097 action.nargs) % action.nargs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002098 msg = nargs_errors.get(action.nargs, default)
2099 raise ArgumentError(action, msg)
2100
2101 # return the number of arguments matched
2102 return len(match.group(1))
2103
2104 def _match_arguments_partial(self, actions, arg_strings_pattern):
2105 # progressively shorten the actions list by slicing off the
2106 # final actions until we find a match
2107 result = []
2108 for i in range(len(actions), 0, -1):
2109 actions_slice = actions[:i]
2110 pattern = ''.join([self._get_nargs_pattern(action)
2111 for action in actions_slice])
2112 match = _re.match(pattern, arg_strings_pattern)
2113 if match is not None:
2114 result.extend([len(string) for string in match.groups()])
2115 break
2116
2117 # return the list of arg string counts
2118 return result
2119
2120 def _parse_optional(self, arg_string):
2121 # if it's an empty string, it was meant to be a positional
2122 if not arg_string:
2123 return None
2124
2125 # if it doesn't start with a prefix, it was meant to be positional
2126 if not arg_string[0] in self.prefix_chars:
2127 return None
2128
2129 # if the option string is present in the parser, return the action
2130 if arg_string in self._option_string_actions:
2131 action = self._option_string_actions[arg_string]
2132 return action, arg_string, None
2133
2134 # if it's just a single character, it was meant to be positional
2135 if len(arg_string) == 1:
2136 return None
2137
2138 # if the option string before the "=" is present, return the action
2139 if '=' in arg_string:
2140 option_string, explicit_arg = arg_string.split('=', 1)
2141 if option_string in self._option_string_actions:
2142 action = self._option_string_actions[option_string]
2143 return action, option_string, explicit_arg
2144
Miss Islington (bot)b1e4d1b2019-07-13 22:59:56 -07002145 if self.allow_abbrev or not arg_string.startswith('--'):
Berker Peksag8089cd62015-02-14 01:39:17 +02002146 # search through all possible prefixes of the option string
2147 # and all actions in the parser for possible interpretations
2148 option_tuples = self._get_option_tuples(arg_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002149
Berker Peksag8089cd62015-02-14 01:39:17 +02002150 # if multiple actions match, the option string was ambiguous
2151 if len(option_tuples) > 1:
2152 options = ', '.join([option_string
2153 for action, option_string, explicit_arg in option_tuples])
2154 args = {'option': arg_string, 'matches': options}
2155 msg = _('ambiguous option: %(option)s could match %(matches)s')
2156 self.error(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002157
Berker Peksag8089cd62015-02-14 01:39:17 +02002158 # if exactly one action matched, this segmentation is good,
2159 # so return the parsed action
2160 elif len(option_tuples) == 1:
2161 option_tuple, = option_tuples
2162 return option_tuple
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002163
2164 # if it was not found as an option, but it looks like a negative
2165 # number, it was meant to be positional
2166 # unless there are negative-number-like options
2167 if self._negative_number_matcher.match(arg_string):
2168 if not self._has_negative_number_optionals:
2169 return None
2170
2171 # if it contains a space, it was meant to be a positional
2172 if ' ' in arg_string:
2173 return None
2174
2175 # it was meant to be an optional but there is no such option
2176 # in this parser (though it might be a valid option in a subparser)
2177 return None, arg_string, None
2178
2179 def _get_option_tuples(self, option_string):
2180 result = []
2181
2182 # option strings starting with two prefix characters are only
2183 # split at the '='
2184 chars = self.prefix_chars
2185 if option_string[0] in chars and option_string[1] in chars:
2186 if '=' in option_string:
2187 option_prefix, explicit_arg = option_string.split('=', 1)
2188 else:
2189 option_prefix = option_string
2190 explicit_arg = None
2191 for option_string in self._option_string_actions:
2192 if option_string.startswith(option_prefix):
2193 action = self._option_string_actions[option_string]
2194 tup = action, option_string, explicit_arg
2195 result.append(tup)
2196
2197 # single character options can be concatenated with their arguments
2198 # but multiple character options always have to have their argument
2199 # separate
2200 elif option_string[0] in chars and option_string[1] not in chars:
2201 option_prefix = option_string
2202 explicit_arg = None
2203 short_option_prefix = option_string[:2]
2204 short_explicit_arg = option_string[2:]
2205
2206 for option_string in self._option_string_actions:
2207 if option_string == short_option_prefix:
2208 action = self._option_string_actions[option_string]
2209 tup = action, option_string, short_explicit_arg
2210 result.append(tup)
2211 elif option_string.startswith(option_prefix):
2212 action = self._option_string_actions[option_string]
2213 tup = action, option_string, explicit_arg
2214 result.append(tup)
2215
2216 # shouldn't ever get here
2217 else:
2218 self.error(_('unexpected option string: %s') % option_string)
2219
2220 # return the collected option tuples
2221 return result
2222
2223 def _get_nargs_pattern(self, action):
2224 # in all examples below, we have to allow for '--' args
2225 # which are represented as '-' in the pattern
2226 nargs = action.nargs
2227
2228 # the default (None) is assumed to be a single argument
2229 if nargs is None:
2230 nargs_pattern = '(-*A-*)'
2231
2232 # allow zero or one arguments
2233 elif nargs == OPTIONAL:
2234 nargs_pattern = '(-*A?-*)'
2235
2236 # allow zero or more arguments
2237 elif nargs == ZERO_OR_MORE:
2238 nargs_pattern = '(-*[A-]*)'
2239
2240 # allow one or more arguments
2241 elif nargs == ONE_OR_MORE:
2242 nargs_pattern = '(-*A[A-]*)'
2243
2244 # allow any number of options or arguments
2245 elif nargs == REMAINDER:
2246 nargs_pattern = '([-AO]*)'
2247
2248 # allow one argument followed by any number of options or arguments
2249 elif nargs == PARSER:
2250 nargs_pattern = '(-*A[-AO]*)'
2251
R. David Murray0f6b9d22017-09-06 20:25:40 -04002252 # suppress action, like nargs=0
2253 elif nargs == SUPPRESS:
2254 nargs_pattern = '(-*-*)'
2255
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002256 # all others should be integers
2257 else:
2258 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2259
2260 # if this is an optional action, -- is not allowed
2261 if action.option_strings:
2262 nargs_pattern = nargs_pattern.replace('-*', '')
2263 nargs_pattern = nargs_pattern.replace('-', '')
2264
2265 # return the pattern
2266 return nargs_pattern
2267
2268 # ========================
R. David Murray0f6b9d22017-09-06 20:25:40 -04002269 # Alt command line argument parsing, allowing free intermix
2270 # ========================
2271
2272 def parse_intermixed_args(self, args=None, namespace=None):
2273 args, argv = self.parse_known_intermixed_args(args, namespace)
2274 if argv:
2275 msg = _('unrecognized arguments: %s')
2276 self.error(msg % ' '.join(argv))
2277 return args
2278
2279 def parse_known_intermixed_args(self, args=None, namespace=None):
2280 # returns a namespace and list of extras
2281 #
2282 # positional can be freely intermixed with optionals. optionals are
2283 # first parsed with all positional arguments deactivated. The 'extras'
2284 # are then parsed. If the parser definition is incompatible with the
2285 # intermixed assumptions (e.g. use of REMAINDER, subparsers) a
2286 # TypeError is raised.
2287 #
2288 # positionals are 'deactivated' by setting nargs and default to
2289 # SUPPRESS. This blocks the addition of that positional to the
2290 # namespace
2291
2292 positionals = self._get_positional_actions()
2293 a = [action for action in positionals
2294 if action.nargs in [PARSER, REMAINDER]]
2295 if a:
2296 raise TypeError('parse_intermixed_args: positional arg'
2297 ' with nargs=%s'%a[0].nargs)
2298
2299 if [action.dest for group in self._mutually_exclusive_groups
2300 for action in group._group_actions if action in positionals]:
2301 raise TypeError('parse_intermixed_args: positional in'
2302 ' mutuallyExclusiveGroup')
2303
2304 try:
2305 save_usage = self.usage
2306 try:
2307 if self.usage is None:
2308 # capture the full usage for use in error messages
2309 self.usage = self.format_usage()[7:]
2310 for action in positionals:
2311 # deactivate positionals
2312 action.save_nargs = action.nargs
2313 # action.nargs = 0
2314 action.nargs = SUPPRESS
2315 action.save_default = action.default
2316 action.default = SUPPRESS
2317 namespace, remaining_args = self.parse_known_args(args,
2318 namespace)
2319 for action in positionals:
2320 # remove the empty positional values from namespace
2321 if (hasattr(namespace, action.dest)
2322 and getattr(namespace, action.dest)==[]):
2323 from warnings import warn
2324 warn('Do not expect %s in %s' % (action.dest, namespace))
2325 delattr(namespace, action.dest)
2326 finally:
2327 # restore nargs and usage before exiting
2328 for action in positionals:
2329 action.nargs = action.save_nargs
2330 action.default = action.save_default
2331 optionals = self._get_optional_actions()
2332 try:
2333 # parse positionals. optionals aren't normally required, but
2334 # they could be, so make sure they aren't.
2335 for action in optionals:
2336 action.save_required = action.required
2337 action.required = False
2338 for group in self._mutually_exclusive_groups:
2339 group.save_required = group.required
2340 group.required = False
2341 namespace, extras = self.parse_known_args(remaining_args,
2342 namespace)
2343 finally:
2344 # restore parser values before exiting
2345 for action in optionals:
2346 action.required = action.save_required
2347 for group in self._mutually_exclusive_groups:
2348 group.required = group.save_required
2349 finally:
2350 self.usage = save_usage
2351 return namespace, extras
2352
2353 # ========================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002354 # Value conversion methods
2355 # ========================
2356 def _get_values(self, action, arg_strings):
R David Murray00528e82012-07-21 22:48:35 -04002357 # for everything but PARSER, REMAINDER args, strip out first '--'
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002358 if action.nargs not in [PARSER, REMAINDER]:
R David Murray00528e82012-07-21 22:48:35 -04002359 try:
2360 arg_strings.remove('--')
2361 except ValueError:
2362 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002363
2364 # optional argument produces a default when not present
2365 if not arg_strings and action.nargs == OPTIONAL:
2366 if action.option_strings:
2367 value = action.const
2368 else:
2369 value = action.default
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00002370 if isinstance(value, str):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002371 value = self._get_value(action, value)
2372 self._check_value(action, value)
2373
2374 # when nargs='*' on a positional, if there were no command-line
2375 # args, use the default if it is anything other than None
2376 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2377 not action.option_strings):
2378 if action.default is not None:
2379 value = action.default
2380 else:
2381 value = arg_strings
2382 self._check_value(action, value)
2383
2384 # single argument or optional argument produces a single value
2385 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2386 arg_string, = arg_strings
2387 value = self._get_value(action, arg_string)
2388 self._check_value(action, value)
2389
2390 # REMAINDER arguments convert all values, checking none
2391 elif action.nargs == REMAINDER:
2392 value = [self._get_value(action, v) for v in arg_strings]
2393
2394 # PARSER arguments convert all values, but check only the first
2395 elif action.nargs == PARSER:
2396 value = [self._get_value(action, v) for v in arg_strings]
2397 self._check_value(action, value[0])
2398
R. David Murray0f6b9d22017-09-06 20:25:40 -04002399 # SUPPRESS argument does not put anything in the namespace
2400 elif action.nargs == SUPPRESS:
2401 value = SUPPRESS
2402
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002403 # all other types of nargs produce a list
2404 else:
2405 value = [self._get_value(action, v) for v in arg_strings]
2406 for v in value:
2407 self._check_value(action, v)
2408
2409 # return the converted value
2410 return value
2411
2412 def _get_value(self, action, arg_string):
2413 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02002414 if not callable(type_func):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002415 msg = _('%r is not callable')
2416 raise ArgumentError(action, msg % type_func)
2417
2418 # convert the value to the appropriate type
2419 try:
2420 result = type_func(arg_string)
2421
2422 # ArgumentTypeErrors indicate errors
2423 except ArgumentTypeError:
2424 name = getattr(action.type, '__name__', repr(action.type))
2425 msg = str(_sys.exc_info()[1])
2426 raise ArgumentError(action, msg)
2427
2428 # TypeErrors or ValueErrors also indicate errors
2429 except (TypeError, ValueError):
2430 name = getattr(action.type, '__name__', repr(action.type))
Éric Araujobb48a8b2010-12-03 19:41:00 +00002431 args = {'type': name, 'value': arg_string}
2432 msg = _('invalid %(type)s value: %(value)r')
2433 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002434
2435 # return the converted value
2436 return result
2437
2438 def _check_value(self, action, value):
2439 # converted value must be one of the choices (if specified)
Vinay Sajip9ae50502016-08-23 08:43:16 +01002440 if action.choices is not None and value not in action.choices:
2441 args = {'value': value,
2442 'choices': ', '.join(map(repr, action.choices))}
2443 msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2444 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002445
2446 # =======================
2447 # Help-formatting methods
2448 # =======================
2449 def format_usage(self):
2450 formatter = self._get_formatter()
2451 formatter.add_usage(self.usage, self._actions,
2452 self._mutually_exclusive_groups)
2453 return formatter.format_help()
2454
2455 def format_help(self):
2456 formatter = self._get_formatter()
2457
2458 # usage
2459 formatter.add_usage(self.usage, self._actions,
2460 self._mutually_exclusive_groups)
2461
2462 # description
2463 formatter.add_text(self.description)
2464
2465 # positionals, optionals and user-defined groups
2466 for action_group in self._action_groups:
2467 formatter.start_section(action_group.title)
2468 formatter.add_text(action_group.description)
2469 formatter.add_arguments(action_group._group_actions)
2470 formatter.end_section()
2471
2472 # epilog
2473 formatter.add_text(self.epilog)
2474
2475 # determine help from format above
2476 return formatter.format_help()
2477
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002478 def _get_formatter(self):
2479 return self.formatter_class(prog=self.prog)
2480
2481 # =====================
2482 # Help-printing methods
2483 # =====================
2484 def print_usage(self, file=None):
2485 if file is None:
2486 file = _sys.stdout
2487 self._print_message(self.format_usage(), file)
2488
2489 def print_help(self, file=None):
2490 if file is None:
2491 file = _sys.stdout
2492 self._print_message(self.format_help(), file)
2493
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002494 def _print_message(self, message, file=None):
2495 if message:
2496 if file is None:
2497 file = _sys.stderr
2498 file.write(message)
2499
2500 # ===============
2501 # Exiting methods
2502 # ===============
2503 def exit(self, status=0, message=None):
2504 if message:
2505 self._print_message(message, _sys.stderr)
2506 _sys.exit(status)
2507
2508 def error(self, message):
2509 """error(message: string)
2510
2511 Prints a usage message incorporating the message to stderr and
2512 exits.
2513
2514 If you override this in a subclass, it should not return -- it
2515 should either exit or raise an exception.
2516 """
2517 self.print_usage(_sys.stderr)
Éric Araujobb48a8b2010-12-03 19:41:00 +00002518 args = {'prog': self.prog, 'message': message}
2519 self.exit(2, _('%(prog)s: error: %(message)s\n') % args)