blob: e590225c8eb8d33adb76ae1af23d9dde1cfdc35c [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:
Miss Islington (bot)8750dfe2019-09-13 02:45:27 -07001217 args = {'filename': string, 'error': e}
1218 message = _("can't open '%(filename)s': %(error)s")
1219 raise ArgumentTypeError(message % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001220
1221 def __repr__(self):
Steven Bethardb0270112011-01-24 21:02:50 +00001222 args = self._mode, self._bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001223 kwargs = [('encoding', self._encoding), ('errors', self._errors)]
1224 args_str = ', '.join([repr(arg) for arg in args if arg != -1] +
1225 ['%s=%r' % (kw, arg) for kw, arg in kwargs
1226 if arg is not None])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001227 return '%s(%s)' % (type(self).__name__, args_str)
1228
1229# ===========================
1230# Optional and Positional Parsing
1231# ===========================
1232
1233class Namespace(_AttributeHolder):
1234 """Simple object for storing attributes.
1235
1236 Implements equality by attribute names and values, and provides a simple
1237 string representation.
1238 """
1239
1240 def __init__(self, **kwargs):
1241 for name in kwargs:
1242 setattr(self, name, kwargs[name])
1243
1244 def __eq__(self, other):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07001245 if not isinstance(other, Namespace):
1246 return NotImplemented
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001247 return vars(self) == vars(other)
1248
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001249 def __contains__(self, key):
1250 return key in self.__dict__
1251
1252
1253class _ActionsContainer(object):
1254
1255 def __init__(self,
1256 description,
1257 prefix_chars,
1258 argument_default,
1259 conflict_handler):
1260 super(_ActionsContainer, self).__init__()
1261
1262 self.description = description
1263 self.argument_default = argument_default
1264 self.prefix_chars = prefix_chars
1265 self.conflict_handler = conflict_handler
1266
1267 # set up registries
1268 self._registries = {}
1269
1270 # register actions
1271 self.register('action', None, _StoreAction)
1272 self.register('action', 'store', _StoreAction)
1273 self.register('action', 'store_const', _StoreConstAction)
1274 self.register('action', 'store_true', _StoreTrueAction)
1275 self.register('action', 'store_false', _StoreFalseAction)
1276 self.register('action', 'append', _AppendAction)
1277 self.register('action', 'append_const', _AppendConstAction)
1278 self.register('action', 'count', _CountAction)
1279 self.register('action', 'help', _HelpAction)
1280 self.register('action', 'version', _VersionAction)
1281 self.register('action', 'parsers', _SubParsersAction)
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001282 self.register('action', 'extend', _ExtendAction)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001283
1284 # raise an exception if the conflict handler is invalid
1285 self._get_handler()
1286
1287 # action storage
1288 self._actions = []
1289 self._option_string_actions = {}
1290
1291 # groups
1292 self._action_groups = []
1293 self._mutually_exclusive_groups = []
1294
1295 # defaults storage
1296 self._defaults = {}
1297
1298 # determines whether an "option" looks like a negative number
1299 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1300
1301 # whether or not there are any optionals that look like negative
1302 # numbers -- uses a list so it can be shared and edited
1303 self._has_negative_number_optionals = []
1304
1305 # ====================
1306 # Registration methods
1307 # ====================
1308 def register(self, registry_name, value, object):
1309 registry = self._registries.setdefault(registry_name, {})
1310 registry[value] = object
1311
1312 def _registry_get(self, registry_name, value, default=None):
1313 return self._registries[registry_name].get(value, default)
1314
1315 # ==================================
1316 # Namespace default accessor methods
1317 # ==================================
1318 def set_defaults(self, **kwargs):
1319 self._defaults.update(kwargs)
1320
1321 # if these defaults match any existing arguments, replace
1322 # the previous default on the object with the new one
1323 for action in self._actions:
1324 if action.dest in kwargs:
1325 action.default = kwargs[action.dest]
1326
1327 def get_default(self, dest):
1328 for action in self._actions:
1329 if action.dest == dest and action.default is not None:
1330 return action.default
1331 return self._defaults.get(dest, None)
1332
1333
1334 # =======================
1335 # Adding argument actions
1336 # =======================
1337 def add_argument(self, *args, **kwargs):
1338 """
1339 add_argument(dest, ..., name=value, ...)
1340 add_argument(option_string, option_string, ..., name=value, ...)
1341 """
1342
1343 # if no positional args are supplied or only one is supplied and
1344 # it doesn't look like an option string, parse a positional
1345 # argument
1346 chars = self.prefix_chars
1347 if not args or len(args) == 1 and args[0][0] not in chars:
1348 if args and 'dest' in kwargs:
1349 raise ValueError('dest supplied twice for positional argument')
1350 kwargs = self._get_positional_kwargs(*args, **kwargs)
1351
1352 # otherwise, we're adding an optional argument
1353 else:
1354 kwargs = self._get_optional_kwargs(*args, **kwargs)
1355
1356 # if no default was supplied, use the parser-level default
1357 if 'default' not in kwargs:
1358 dest = kwargs['dest']
1359 if dest in self._defaults:
1360 kwargs['default'] = self._defaults[dest]
1361 elif self.argument_default is not None:
1362 kwargs['default'] = self.argument_default
1363
1364 # create the action object, and add it to the parser
1365 action_class = self._pop_action_class(kwargs)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001366 if not callable(action_class):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001367 raise ValueError('unknown action "%s"' % (action_class,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001368 action = action_class(**kwargs)
1369
1370 # raise an error if the action type is not callable
1371 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001372 if not callable(type_func):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001373 raise ValueError('%r is not callable' % (type_func,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001374
Miss Islington (bot)606ac582019-06-07 14:11:59 -07001375 if type_func is FileType:
1376 raise ValueError('%r is a FileType class object, instance of it'
1377 ' must be passed' % (type_func,))
1378
Steven Bethard8d9a4622011-03-26 17:33:56 +01001379 # raise an error if the metavar does not match the type
1380 if hasattr(self, "_get_formatter"):
1381 try:
1382 self._get_formatter()._format_args(action, None)
1383 except TypeError:
1384 raise ValueError("length of metavar tuple does not match nargs")
1385
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001386 return self._add_action(action)
1387
1388 def add_argument_group(self, *args, **kwargs):
1389 group = _ArgumentGroup(self, *args, **kwargs)
1390 self._action_groups.append(group)
1391 return group
1392
1393 def add_mutually_exclusive_group(self, **kwargs):
1394 group = _MutuallyExclusiveGroup(self, **kwargs)
1395 self._mutually_exclusive_groups.append(group)
1396 return group
1397
1398 def _add_action(self, action):
1399 # resolve any conflicts
1400 self._check_conflict(action)
1401
1402 # add to actions list
1403 self._actions.append(action)
1404 action.container = self
1405
1406 # index the action by any option strings it has
1407 for option_string in action.option_strings:
1408 self._option_string_actions[option_string] = action
1409
1410 # set the flag if any option strings look like negative numbers
1411 for option_string in action.option_strings:
1412 if self._negative_number_matcher.match(option_string):
1413 if not self._has_negative_number_optionals:
1414 self._has_negative_number_optionals.append(True)
1415
1416 # return the created action
1417 return action
1418
1419 def _remove_action(self, action):
1420 self._actions.remove(action)
1421
1422 def _add_container_actions(self, container):
1423 # collect groups by titles
1424 title_group_map = {}
1425 for group in self._action_groups:
1426 if group.title in title_group_map:
1427 msg = _('cannot merge actions - two groups are named %r')
1428 raise ValueError(msg % (group.title))
1429 title_group_map[group.title] = group
1430
1431 # map each action to its group
1432 group_map = {}
1433 for group in container._action_groups:
1434
1435 # if a group with the title exists, use that, otherwise
1436 # create a new group matching the container's group
1437 if group.title not in title_group_map:
1438 title_group_map[group.title] = self.add_argument_group(
1439 title=group.title,
1440 description=group.description,
1441 conflict_handler=group.conflict_handler)
1442
1443 # map the actions to their new group
1444 for action in group._group_actions:
1445 group_map[action] = title_group_map[group.title]
1446
1447 # add container's mutually exclusive groups
1448 # NOTE: if add_mutually_exclusive_group ever gains title= and
1449 # description= then this code will need to be expanded as above
1450 for group in container._mutually_exclusive_groups:
1451 mutex_group = self.add_mutually_exclusive_group(
1452 required=group.required)
1453
1454 # map the actions to their new mutex group
1455 for action in group._group_actions:
1456 group_map[action] = mutex_group
1457
1458 # add all actions to this container or their group
1459 for action in container._actions:
1460 group_map.get(action, self)._add_action(action)
1461
1462 def _get_positional_kwargs(self, dest, **kwargs):
1463 # make sure required is not specified
1464 if 'required' in kwargs:
1465 msg = _("'required' is an invalid argument for positionals")
1466 raise TypeError(msg)
1467
1468 # mark positional arguments as required if at least one is
1469 # always required
1470 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1471 kwargs['required'] = True
1472 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1473 kwargs['required'] = True
1474
1475 # return the keyword arguments with no option strings
1476 return dict(kwargs, dest=dest, option_strings=[])
1477
1478 def _get_optional_kwargs(self, *args, **kwargs):
1479 # determine short and long option strings
1480 option_strings = []
1481 long_option_strings = []
1482 for option_string in args:
1483 # error on strings that don't start with an appropriate prefix
1484 if not option_string[0] in self.prefix_chars:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001485 args = {'option': option_string,
1486 'prefix_chars': self.prefix_chars}
1487 msg = _('invalid option string %(option)r: '
1488 'must start with a character %(prefix_chars)r')
1489 raise ValueError(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001490
1491 # strings starting with two prefix characters are long options
1492 option_strings.append(option_string)
1493 if option_string[0] in self.prefix_chars:
1494 if len(option_string) > 1:
1495 if option_string[1] in self.prefix_chars:
1496 long_option_strings.append(option_string)
1497
1498 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1499 dest = kwargs.pop('dest', None)
1500 if dest is None:
1501 if long_option_strings:
1502 dest_option_string = long_option_strings[0]
1503 else:
1504 dest_option_string = option_strings[0]
1505 dest = dest_option_string.lstrip(self.prefix_chars)
1506 if not dest:
1507 msg = _('dest= is required for options like %r')
1508 raise ValueError(msg % option_string)
1509 dest = dest.replace('-', '_')
1510
1511 # return the updated keyword arguments
1512 return dict(kwargs, dest=dest, option_strings=option_strings)
1513
1514 def _pop_action_class(self, kwargs, default=None):
1515 action = kwargs.pop('action', default)
1516 return self._registry_get('action', action, action)
1517
1518 def _get_handler(self):
1519 # determine function from conflict handler string
1520 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1521 try:
1522 return getattr(self, handler_func_name)
1523 except AttributeError:
1524 msg = _('invalid conflict_resolution value: %r')
1525 raise ValueError(msg % self.conflict_handler)
1526
1527 def _check_conflict(self, action):
1528
1529 # find all options that conflict with this option
1530 confl_optionals = []
1531 for option_string in action.option_strings:
1532 if option_string in self._option_string_actions:
1533 confl_optional = self._option_string_actions[option_string]
1534 confl_optionals.append((option_string, confl_optional))
1535
1536 # resolve any conflicts
1537 if confl_optionals:
1538 conflict_handler = self._get_handler()
1539 conflict_handler(action, confl_optionals)
1540
1541 def _handle_conflict_error(self, action, conflicting_actions):
Éric Araujo12159152010-12-04 17:31:49 +00001542 message = ngettext('conflicting option string: %s',
1543 'conflicting option strings: %s',
1544 len(conflicting_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001545 conflict_string = ', '.join([option_string
1546 for option_string, action
1547 in conflicting_actions])
1548 raise ArgumentError(action, message % conflict_string)
1549
1550 def _handle_conflict_resolve(self, action, conflicting_actions):
1551
1552 # remove all conflicting options
1553 for option_string, action in conflicting_actions:
1554
1555 # remove the conflicting option
1556 action.option_strings.remove(option_string)
1557 self._option_string_actions.pop(option_string, None)
1558
1559 # if the option now has no option string, remove it from the
1560 # container holding it
1561 if not action.option_strings:
1562 action.container._remove_action(action)
1563
1564
1565class _ArgumentGroup(_ActionsContainer):
1566
1567 def __init__(self, container, title=None, description=None, **kwargs):
1568 # add any missing keyword arguments by checking the container
1569 update = kwargs.setdefault
1570 update('conflict_handler', container.conflict_handler)
1571 update('prefix_chars', container.prefix_chars)
1572 update('argument_default', container.argument_default)
1573 super_init = super(_ArgumentGroup, self).__init__
1574 super_init(description=description, **kwargs)
1575
1576 # group attributes
1577 self.title = title
1578 self._group_actions = []
1579
1580 # share most attributes with the container
1581 self._registries = container._registries
1582 self._actions = container._actions
1583 self._option_string_actions = container._option_string_actions
1584 self._defaults = container._defaults
1585 self._has_negative_number_optionals = \
1586 container._has_negative_number_optionals
Georg Brandl0f6b47a2011-01-30 12:19:35 +00001587 self._mutually_exclusive_groups = container._mutually_exclusive_groups
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001588
1589 def _add_action(self, action):
1590 action = super(_ArgumentGroup, self)._add_action(action)
1591 self._group_actions.append(action)
1592 return action
1593
1594 def _remove_action(self, action):
1595 super(_ArgumentGroup, self)._remove_action(action)
1596 self._group_actions.remove(action)
1597
1598
1599class _MutuallyExclusiveGroup(_ArgumentGroup):
1600
1601 def __init__(self, container, required=False):
1602 super(_MutuallyExclusiveGroup, self).__init__(container)
1603 self.required = required
1604 self._container = container
1605
1606 def _add_action(self, action):
1607 if action.required:
1608 msg = _('mutually exclusive arguments must be optional')
1609 raise ValueError(msg)
1610 action = self._container._add_action(action)
1611 self._group_actions.append(action)
1612 return action
1613
1614 def _remove_action(self, action):
1615 self._container._remove_action(action)
1616 self._group_actions.remove(action)
1617
1618
1619class ArgumentParser(_AttributeHolder, _ActionsContainer):
1620 """Object for parsing command line strings into Python objects.
1621
1622 Keyword Arguments:
1623 - prog -- The name of the program (default: sys.argv[0])
1624 - usage -- A usage message (default: auto-generated from arguments)
1625 - description -- A description of what the program does
1626 - epilog -- Text following the argument descriptions
1627 - parents -- Parsers whose arguments should be copied into this one
1628 - formatter_class -- HelpFormatter class for printing help messages
1629 - prefix_chars -- Characters that prefix optional arguments
1630 - fromfile_prefix_chars -- Characters that prefix files containing
1631 additional arguments
1632 - argument_default -- The default value for all arguments
1633 - conflict_handler -- String indicating how to handle conflicts
1634 - add_help -- Add a -h/-help option
Berker Peksag8089cd62015-02-14 01:39:17 +02001635 - allow_abbrev -- Allow long options to be abbreviated unambiguously
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001636 """
1637
1638 def __init__(self,
1639 prog=None,
1640 usage=None,
1641 description=None,
1642 epilog=None,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001643 parents=[],
1644 formatter_class=HelpFormatter,
1645 prefix_chars='-',
1646 fromfile_prefix_chars=None,
1647 argument_default=None,
1648 conflict_handler='error',
Berker Peksag8089cd62015-02-14 01:39:17 +02001649 add_help=True,
1650 allow_abbrev=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001651
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001652 superinit = super(ArgumentParser, self).__init__
1653 superinit(description=description,
1654 prefix_chars=prefix_chars,
1655 argument_default=argument_default,
1656 conflict_handler=conflict_handler)
1657
1658 # default setting for prog
1659 if prog is None:
1660 prog = _os.path.basename(_sys.argv[0])
1661
1662 self.prog = prog
1663 self.usage = usage
1664 self.epilog = epilog
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001665 self.formatter_class = formatter_class
1666 self.fromfile_prefix_chars = fromfile_prefix_chars
1667 self.add_help = add_help
Berker Peksag8089cd62015-02-14 01:39:17 +02001668 self.allow_abbrev = allow_abbrev
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001669
1670 add_group = self.add_argument_group
1671 self._positionals = add_group(_('positional arguments'))
1672 self._optionals = add_group(_('optional arguments'))
1673 self._subparsers = None
1674
1675 # register types
1676 def identity(string):
1677 return string
1678 self.register('type', None, identity)
1679
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001680 # add help argument if necessary
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001681 # (using explicit default to override global argument_default)
R. David Murray88c49fe2010-08-03 17:56:09 +00001682 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001683 if self.add_help:
1684 self.add_argument(
R. David Murray88c49fe2010-08-03 17:56:09 +00001685 default_prefix+'h', default_prefix*2+'help',
1686 action='help', default=SUPPRESS,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001687 help=_('show this help message and exit'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001688
1689 # add parent arguments and defaults
1690 for parent in parents:
1691 self._add_container_actions(parent)
1692 try:
1693 defaults = parent._defaults
1694 except AttributeError:
1695 pass
1696 else:
1697 self._defaults.update(defaults)
1698
1699 # =======================
1700 # Pretty __repr__ methods
1701 # =======================
1702 def _get_kwargs(self):
1703 names = [
1704 'prog',
1705 'usage',
1706 'description',
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001707 'formatter_class',
1708 'conflict_handler',
1709 'add_help',
1710 ]
1711 return [(name, getattr(self, name)) for name in names]
1712
1713 # ==================================
1714 # Optional/Positional adding methods
1715 # ==================================
1716 def add_subparsers(self, **kwargs):
1717 if self._subparsers is not None:
1718 self.error(_('cannot have multiple subparser arguments'))
1719
1720 # add the parser class to the arguments if it's not present
1721 kwargs.setdefault('parser_class', type(self))
1722
1723 if 'title' in kwargs or 'description' in kwargs:
1724 title = _(kwargs.pop('title', 'subcommands'))
1725 description = _(kwargs.pop('description', None))
1726 self._subparsers = self.add_argument_group(title, description)
1727 else:
1728 self._subparsers = self._positionals
1729
1730 # prog defaults to the usage message of this parser, skipping
1731 # optional arguments and with no "usage:" prefix
1732 if kwargs.get('prog') is None:
1733 formatter = self._get_formatter()
1734 positionals = self._get_positional_actions()
1735 groups = self._mutually_exclusive_groups
1736 formatter.add_usage(self.usage, positionals, groups, '')
1737 kwargs['prog'] = formatter.format_help().strip()
1738
1739 # create the parsers action and add it to the positionals list
1740 parsers_class = self._pop_action_class(kwargs, 'parsers')
1741 action = parsers_class(option_strings=[], **kwargs)
1742 self._subparsers._add_action(action)
1743
1744 # return the created parsers action
1745 return action
1746
1747 def _add_action(self, action):
1748 if action.option_strings:
1749 self._optionals._add_action(action)
1750 else:
1751 self._positionals._add_action(action)
1752 return action
1753
1754 def _get_optional_actions(self):
1755 return [action
1756 for action in self._actions
1757 if action.option_strings]
1758
1759 def _get_positional_actions(self):
1760 return [action
1761 for action in self._actions
1762 if not action.option_strings]
1763
1764 # =====================================
1765 # Command line argument parsing methods
1766 # =====================================
1767 def parse_args(self, args=None, namespace=None):
1768 args, argv = self.parse_known_args(args, namespace)
1769 if argv:
1770 msg = _('unrecognized arguments: %s')
1771 self.error(msg % ' '.join(argv))
1772 return args
1773
1774 def parse_known_args(self, args=None, namespace=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001775 if args is None:
R David Murrayb5228282012-09-08 12:08:01 -04001776 # args default to the system args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001777 args = _sys.argv[1:]
R David Murrayb5228282012-09-08 12:08:01 -04001778 else:
1779 # make sure that args are mutable
1780 args = list(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001781
1782 # default Namespace built from parser defaults
1783 if namespace is None:
1784 namespace = Namespace()
1785
1786 # add any action defaults that aren't present
1787 for action in self._actions:
1788 if action.dest is not SUPPRESS:
1789 if not hasattr(namespace, action.dest):
1790 if action.default is not SUPPRESS:
R David Murray6fb8fb12012-08-31 22:45:20 -04001791 setattr(namespace, action.dest, action.default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001792
1793 # add any parser defaults that aren't present
1794 for dest in self._defaults:
1795 if not hasattr(namespace, dest):
1796 setattr(namespace, dest, self._defaults[dest])
1797
1798 # parse the arguments and exit if there are any errors
1799 try:
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001800 namespace, args = self._parse_known_args(args, namespace)
1801 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1802 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1803 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1804 return namespace, args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001805 except ArgumentError:
1806 err = _sys.exc_info()[1]
1807 self.error(str(err))
1808
1809 def _parse_known_args(self, arg_strings, namespace):
1810 # replace arg strings that are file references
1811 if self.fromfile_prefix_chars is not None:
1812 arg_strings = self._read_args_from_files(arg_strings)
1813
1814 # map all mutually exclusive arguments to the other arguments
1815 # they can't occur with
1816 action_conflicts = {}
1817 for mutex_group in self._mutually_exclusive_groups:
1818 group_actions = mutex_group._group_actions
1819 for i, mutex_action in enumerate(mutex_group._group_actions):
1820 conflicts = action_conflicts.setdefault(mutex_action, [])
1821 conflicts.extend(group_actions[:i])
1822 conflicts.extend(group_actions[i + 1:])
1823
1824 # find all option indices, and determine the arg_string_pattern
1825 # which has an 'O' if there is an option at an index,
1826 # an 'A' if there is an argument, or a '-' if there is a '--'
1827 option_string_indices = {}
1828 arg_string_pattern_parts = []
1829 arg_strings_iter = iter(arg_strings)
1830 for i, arg_string in enumerate(arg_strings_iter):
1831
1832 # all args after -- are non-options
1833 if arg_string == '--':
1834 arg_string_pattern_parts.append('-')
1835 for arg_string in arg_strings_iter:
1836 arg_string_pattern_parts.append('A')
1837
1838 # otherwise, add the arg to the arg strings
1839 # and note the index if it was an option
1840 else:
1841 option_tuple = self._parse_optional(arg_string)
1842 if option_tuple is None:
1843 pattern = 'A'
1844 else:
1845 option_string_indices[i] = option_tuple
1846 pattern = 'O'
1847 arg_string_pattern_parts.append(pattern)
1848
1849 # join the pieces together to form the pattern
1850 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1851
1852 # converts arg strings to the appropriate and then takes the action
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00001853 seen_actions = set()
1854 seen_non_default_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001855
1856 def take_action(action, argument_strings, option_string=None):
1857 seen_actions.add(action)
1858 argument_values = self._get_values(action, argument_strings)
1859
1860 # error if this argument is not allowed with other previously
1861 # seen arguments, assuming that actions that use the default
1862 # value don't really count as "present"
1863 if argument_values is not action.default:
1864 seen_non_default_actions.add(action)
1865 for conflict_action in action_conflicts.get(action, []):
1866 if conflict_action in seen_non_default_actions:
1867 msg = _('not allowed with argument %s')
1868 action_name = _get_action_name(conflict_action)
1869 raise ArgumentError(action, msg % action_name)
1870
1871 # take the action if we didn't receive a SUPPRESS value
1872 # (e.g. from a default)
1873 if argument_values is not SUPPRESS:
1874 action(self, namespace, argument_values, option_string)
1875
1876 # function to convert arg_strings into an optional action
1877 def consume_optional(start_index):
1878
1879 # get the optional identified at this index
1880 option_tuple = option_string_indices[start_index]
1881 action, option_string, explicit_arg = option_tuple
1882
1883 # identify additional optionals in the same arg string
1884 # (e.g. -xyz is the same as -x -y -z if no args are required)
1885 match_argument = self._match_argument
1886 action_tuples = []
1887 while True:
1888
1889 # if we found no optional action, skip it
1890 if action is None:
1891 extras.append(arg_strings[start_index])
1892 return start_index + 1
1893
1894 # if there is an explicit argument, try to match the
1895 # optional's string arguments to only this
1896 if explicit_arg is not None:
1897 arg_count = match_argument(action, 'A')
1898
1899 # if the action is a single-dash option and takes no
1900 # arguments, try to parse more single-dash options out
1901 # of the tail of the option string
1902 chars = self.prefix_chars
1903 if arg_count == 0 and option_string[1] not in chars:
1904 action_tuples.append((action, [], option_string))
Steven Bethard1ca45a52010-11-01 15:57:36 +00001905 char = option_string[0]
1906 option_string = char + explicit_arg[0]
1907 new_explicit_arg = explicit_arg[1:] or None
1908 optionals_map = self._option_string_actions
1909 if option_string in optionals_map:
1910 action = optionals_map[option_string]
1911 explicit_arg = new_explicit_arg
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001912 else:
1913 msg = _('ignored explicit argument %r')
1914 raise ArgumentError(action, msg % explicit_arg)
1915
1916 # if the action expect exactly one argument, we've
1917 # successfully matched the option; exit the loop
1918 elif arg_count == 1:
1919 stop = start_index + 1
1920 args = [explicit_arg]
1921 action_tuples.append((action, args, option_string))
1922 break
1923
1924 # error if a double-dash option did not use the
1925 # explicit argument
1926 else:
1927 msg = _('ignored explicit argument %r')
1928 raise ArgumentError(action, msg % explicit_arg)
1929
1930 # if there is no explicit argument, try to match the
1931 # optional's string arguments with the following strings
1932 # if successful, exit the loop
1933 else:
1934 start = start_index + 1
1935 selected_patterns = arg_strings_pattern[start:]
1936 arg_count = match_argument(action, selected_patterns)
1937 stop = start + arg_count
1938 args = arg_strings[start:stop]
1939 action_tuples.append((action, args, option_string))
1940 break
1941
1942 # add the Optional to the list and return the index at which
1943 # the Optional's string args stopped
1944 assert action_tuples
1945 for action, args, option_string in action_tuples:
1946 take_action(action, args, option_string)
1947 return stop
1948
1949 # the list of Positionals left to be parsed; this is modified
1950 # by consume_positionals()
1951 positionals = self._get_positional_actions()
1952
1953 # function to convert arg_strings into positional actions
1954 def consume_positionals(start_index):
1955 # match as many Positionals as possible
1956 match_partial = self._match_arguments_partial
1957 selected_pattern = arg_strings_pattern[start_index:]
1958 arg_counts = match_partial(positionals, selected_pattern)
1959
1960 # slice off the appropriate arg strings for each Positional
1961 # and add the Positional and its args to the list
1962 for action, arg_count in zip(positionals, arg_counts):
1963 args = arg_strings[start_index: start_index + arg_count]
1964 start_index += arg_count
1965 take_action(action, args)
1966
1967 # slice off the Positionals that we just parsed and return the
1968 # index at which the Positionals' string args stopped
1969 positionals[:] = positionals[len(arg_counts):]
1970 return start_index
1971
1972 # consume Positionals and Optionals alternately, until we have
1973 # passed the last option string
1974 extras = []
1975 start_index = 0
1976 if option_string_indices:
1977 max_option_string_index = max(option_string_indices)
1978 else:
1979 max_option_string_index = -1
1980 while start_index <= max_option_string_index:
1981
1982 # consume any Positionals preceding the next option
1983 next_option_string_index = min([
1984 index
1985 for index in option_string_indices
1986 if index >= start_index])
1987 if start_index != next_option_string_index:
1988 positionals_end_index = consume_positionals(start_index)
1989
1990 # only try to parse the next optional if we didn't consume
1991 # the option string during the positionals parsing
1992 if positionals_end_index > start_index:
1993 start_index = positionals_end_index
1994 continue
1995 else:
1996 start_index = positionals_end_index
1997
1998 # if we consumed all the positionals we could and we're not
1999 # at the index of an option string, there were extra arguments
2000 if start_index not in option_string_indices:
2001 strings = arg_strings[start_index:next_option_string_index]
2002 extras.extend(strings)
2003 start_index = next_option_string_index
2004
2005 # consume the next optional and any arguments for it
2006 start_index = consume_optional(start_index)
2007
2008 # consume any positionals following the last Optional
2009 stop_index = consume_positionals(start_index)
2010
2011 # if we didn't consume all the argument strings, there were extras
2012 extras.extend(arg_strings[stop_index:])
2013
R David Murray64b0ef12012-08-31 23:09:34 -04002014 # make sure all required actions were present and also convert
2015 # action defaults which were not given as arguments
2016 required_actions = []
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002017 for action in self._actions:
R David Murray6fb8fb12012-08-31 22:45:20 -04002018 if action not in seen_actions:
2019 if action.required:
R David Murray64b0ef12012-08-31 23:09:34 -04002020 required_actions.append(_get_action_name(action))
R David Murray6fb8fb12012-08-31 22:45:20 -04002021 else:
2022 # Convert action default now instead of doing it before
2023 # parsing arguments to avoid calling convert functions
2024 # twice (which may fail) if the argument was given, but
2025 # only if it was defined already in the namespace
2026 if (action.default is not None and
Barry Warsawd89774e2012-09-12 15:31:38 -04002027 isinstance(action.default, str) and
R David Murray64b0ef12012-08-31 23:09:34 -04002028 hasattr(namespace, action.dest) and
2029 action.default is getattr(namespace, action.dest)):
R David Murray6fb8fb12012-08-31 22:45:20 -04002030 setattr(namespace, action.dest,
2031 self._get_value(action, action.default))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002032
R David Murrayf97c59a2011-06-09 12:34:07 -04002033 if required_actions:
2034 self.error(_('the following arguments are required: %s') %
2035 ', '.join(required_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002036
2037 # make sure all required groups had one option present
2038 for group in self._mutually_exclusive_groups:
2039 if group.required:
2040 for action in group._group_actions:
2041 if action in seen_non_default_actions:
2042 break
2043
2044 # if no actions were used, report the error
2045 else:
2046 names = [_get_action_name(action)
2047 for action in group._group_actions
2048 if action.help is not SUPPRESS]
2049 msg = _('one of the arguments %s is required')
2050 self.error(msg % ' '.join(names))
2051
2052 # return the updated namespace and the extra arguments
2053 return namespace, extras
2054
2055 def _read_args_from_files(self, arg_strings):
2056 # expand arguments referencing files
2057 new_arg_strings = []
2058 for arg_string in arg_strings:
2059
2060 # for regular arguments, just add them back into the list
R David Murrayb94082a2012-07-21 22:20:11 -04002061 if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002062 new_arg_strings.append(arg_string)
2063
2064 # replace arguments referencing files with the file content
2065 else:
2066 try:
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01002067 with open(arg_string[1:]) as args_file:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002068 arg_strings = []
2069 for arg_line in args_file.read().splitlines():
2070 for arg in self.convert_arg_line_to_args(arg_line):
2071 arg_strings.append(arg)
2072 arg_strings = self._read_args_from_files(arg_strings)
2073 new_arg_strings.extend(arg_strings)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002074 except OSError:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002075 err = _sys.exc_info()[1]
2076 self.error(str(err))
2077
2078 # return the modified argument list
2079 return new_arg_strings
2080
2081 def convert_arg_line_to_args(self, arg_line):
2082 return [arg_line]
2083
2084 def _match_argument(self, action, arg_strings_pattern):
2085 # match the pattern for this action to the arg strings
2086 nargs_pattern = self._get_nargs_pattern(action)
2087 match = _re.match(nargs_pattern, arg_strings_pattern)
2088
2089 # raise an exception if we weren't able to find a match
2090 if match is None:
2091 nargs_errors = {
2092 None: _('expected one argument'),
2093 OPTIONAL: _('expected at most one argument'),
2094 ONE_OR_MORE: _('expected at least one argument'),
2095 }
Éric Araujo12159152010-12-04 17:31:49 +00002096 default = ngettext('expected %s argument',
2097 'expected %s arguments',
2098 action.nargs) % action.nargs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002099 msg = nargs_errors.get(action.nargs, default)
2100 raise ArgumentError(action, msg)
2101
2102 # return the number of arguments matched
2103 return len(match.group(1))
2104
2105 def _match_arguments_partial(self, actions, arg_strings_pattern):
2106 # progressively shorten the actions list by slicing off the
2107 # final actions until we find a match
2108 result = []
2109 for i in range(len(actions), 0, -1):
2110 actions_slice = actions[:i]
2111 pattern = ''.join([self._get_nargs_pattern(action)
2112 for action in actions_slice])
2113 match = _re.match(pattern, arg_strings_pattern)
2114 if match is not None:
2115 result.extend([len(string) for string in match.groups()])
2116 break
2117
2118 # return the list of arg string counts
2119 return result
2120
2121 def _parse_optional(self, arg_string):
2122 # if it's an empty string, it was meant to be a positional
2123 if not arg_string:
2124 return None
2125
2126 # if it doesn't start with a prefix, it was meant to be positional
2127 if not arg_string[0] in self.prefix_chars:
2128 return None
2129
2130 # if the option string is present in the parser, return the action
2131 if arg_string in self._option_string_actions:
2132 action = self._option_string_actions[arg_string]
2133 return action, arg_string, None
2134
2135 # if it's just a single character, it was meant to be positional
2136 if len(arg_string) == 1:
2137 return None
2138
2139 # if the option string before the "=" is present, return the action
2140 if '=' in arg_string:
2141 option_string, explicit_arg = arg_string.split('=', 1)
2142 if option_string in self._option_string_actions:
2143 action = self._option_string_actions[option_string]
2144 return action, option_string, explicit_arg
2145
Miss Islington (bot)b1e4d1b2019-07-13 22:59:56 -07002146 if self.allow_abbrev or not arg_string.startswith('--'):
Berker Peksag8089cd62015-02-14 01:39:17 +02002147 # search through all possible prefixes of the option string
2148 # and all actions in the parser for possible interpretations
2149 option_tuples = self._get_option_tuples(arg_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002150
Berker Peksag8089cd62015-02-14 01:39:17 +02002151 # if multiple actions match, the option string was ambiguous
2152 if len(option_tuples) > 1:
2153 options = ', '.join([option_string
2154 for action, option_string, explicit_arg in option_tuples])
2155 args = {'option': arg_string, 'matches': options}
2156 msg = _('ambiguous option: %(option)s could match %(matches)s')
2157 self.error(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002158
Berker Peksag8089cd62015-02-14 01:39:17 +02002159 # if exactly one action matched, this segmentation is good,
2160 # so return the parsed action
2161 elif len(option_tuples) == 1:
2162 option_tuple, = option_tuples
2163 return option_tuple
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002164
2165 # if it was not found as an option, but it looks like a negative
2166 # number, it was meant to be positional
2167 # unless there are negative-number-like options
2168 if self._negative_number_matcher.match(arg_string):
2169 if not self._has_negative_number_optionals:
2170 return None
2171
2172 # if it contains a space, it was meant to be a positional
2173 if ' ' in arg_string:
2174 return None
2175
2176 # it was meant to be an optional but there is no such option
2177 # in this parser (though it might be a valid option in a subparser)
2178 return None, arg_string, None
2179
2180 def _get_option_tuples(self, option_string):
2181 result = []
2182
2183 # option strings starting with two prefix characters are only
2184 # split at the '='
2185 chars = self.prefix_chars
2186 if option_string[0] in chars and option_string[1] in chars:
2187 if '=' in option_string:
2188 option_prefix, explicit_arg = option_string.split('=', 1)
2189 else:
2190 option_prefix = option_string
2191 explicit_arg = None
2192 for option_string in self._option_string_actions:
2193 if option_string.startswith(option_prefix):
2194 action = self._option_string_actions[option_string]
2195 tup = action, option_string, explicit_arg
2196 result.append(tup)
2197
2198 # single character options can be concatenated with their arguments
2199 # but multiple character options always have to have their argument
2200 # separate
2201 elif option_string[0] in chars and option_string[1] not in chars:
2202 option_prefix = option_string
2203 explicit_arg = None
2204 short_option_prefix = option_string[:2]
2205 short_explicit_arg = option_string[2:]
2206
2207 for option_string in self._option_string_actions:
2208 if option_string == short_option_prefix:
2209 action = self._option_string_actions[option_string]
2210 tup = action, option_string, short_explicit_arg
2211 result.append(tup)
2212 elif option_string.startswith(option_prefix):
2213 action = self._option_string_actions[option_string]
2214 tup = action, option_string, explicit_arg
2215 result.append(tup)
2216
2217 # shouldn't ever get here
2218 else:
2219 self.error(_('unexpected option string: %s') % option_string)
2220
2221 # return the collected option tuples
2222 return result
2223
2224 def _get_nargs_pattern(self, action):
2225 # in all examples below, we have to allow for '--' args
2226 # which are represented as '-' in the pattern
2227 nargs = action.nargs
2228
2229 # the default (None) is assumed to be a single argument
2230 if nargs is None:
2231 nargs_pattern = '(-*A-*)'
2232
2233 # allow zero or one arguments
2234 elif nargs == OPTIONAL:
2235 nargs_pattern = '(-*A?-*)'
2236
2237 # allow zero or more arguments
2238 elif nargs == ZERO_OR_MORE:
2239 nargs_pattern = '(-*[A-]*)'
2240
2241 # allow one or more arguments
2242 elif nargs == ONE_OR_MORE:
2243 nargs_pattern = '(-*A[A-]*)'
2244
2245 # allow any number of options or arguments
2246 elif nargs == REMAINDER:
2247 nargs_pattern = '([-AO]*)'
2248
2249 # allow one argument followed by any number of options or arguments
2250 elif nargs == PARSER:
2251 nargs_pattern = '(-*A[-AO]*)'
2252
R. David Murray0f6b9d22017-09-06 20:25:40 -04002253 # suppress action, like nargs=0
2254 elif nargs == SUPPRESS:
2255 nargs_pattern = '(-*-*)'
2256
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002257 # all others should be integers
2258 else:
2259 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2260
2261 # if this is an optional action, -- is not allowed
2262 if action.option_strings:
2263 nargs_pattern = nargs_pattern.replace('-*', '')
2264 nargs_pattern = nargs_pattern.replace('-', '')
2265
2266 # return the pattern
2267 return nargs_pattern
2268
2269 # ========================
R. David Murray0f6b9d22017-09-06 20:25:40 -04002270 # Alt command line argument parsing, allowing free intermix
2271 # ========================
2272
2273 def parse_intermixed_args(self, args=None, namespace=None):
2274 args, argv = self.parse_known_intermixed_args(args, namespace)
2275 if argv:
2276 msg = _('unrecognized arguments: %s')
2277 self.error(msg % ' '.join(argv))
2278 return args
2279
2280 def parse_known_intermixed_args(self, args=None, namespace=None):
2281 # returns a namespace and list of extras
2282 #
2283 # positional can be freely intermixed with optionals. optionals are
2284 # first parsed with all positional arguments deactivated. The 'extras'
2285 # are then parsed. If the parser definition is incompatible with the
2286 # intermixed assumptions (e.g. use of REMAINDER, subparsers) a
2287 # TypeError is raised.
2288 #
2289 # positionals are 'deactivated' by setting nargs and default to
2290 # SUPPRESS. This blocks the addition of that positional to the
2291 # namespace
2292
2293 positionals = self._get_positional_actions()
2294 a = [action for action in positionals
2295 if action.nargs in [PARSER, REMAINDER]]
2296 if a:
2297 raise TypeError('parse_intermixed_args: positional arg'
2298 ' with nargs=%s'%a[0].nargs)
2299
2300 if [action.dest for group in self._mutually_exclusive_groups
2301 for action in group._group_actions if action in positionals]:
2302 raise TypeError('parse_intermixed_args: positional in'
2303 ' mutuallyExclusiveGroup')
2304
2305 try:
2306 save_usage = self.usage
2307 try:
2308 if self.usage is None:
2309 # capture the full usage for use in error messages
2310 self.usage = self.format_usage()[7:]
2311 for action in positionals:
2312 # deactivate positionals
2313 action.save_nargs = action.nargs
2314 # action.nargs = 0
2315 action.nargs = SUPPRESS
2316 action.save_default = action.default
2317 action.default = SUPPRESS
2318 namespace, remaining_args = self.parse_known_args(args,
2319 namespace)
2320 for action in positionals:
2321 # remove the empty positional values from namespace
2322 if (hasattr(namespace, action.dest)
2323 and getattr(namespace, action.dest)==[]):
2324 from warnings import warn
2325 warn('Do not expect %s in %s' % (action.dest, namespace))
2326 delattr(namespace, action.dest)
2327 finally:
2328 # restore nargs and usage before exiting
2329 for action in positionals:
2330 action.nargs = action.save_nargs
2331 action.default = action.save_default
2332 optionals = self._get_optional_actions()
2333 try:
2334 # parse positionals. optionals aren't normally required, but
2335 # they could be, so make sure they aren't.
2336 for action in optionals:
2337 action.save_required = action.required
2338 action.required = False
2339 for group in self._mutually_exclusive_groups:
2340 group.save_required = group.required
2341 group.required = False
2342 namespace, extras = self.parse_known_args(remaining_args,
2343 namespace)
2344 finally:
2345 # restore parser values before exiting
2346 for action in optionals:
2347 action.required = action.save_required
2348 for group in self._mutually_exclusive_groups:
2349 group.required = group.save_required
2350 finally:
2351 self.usage = save_usage
2352 return namespace, extras
2353
2354 # ========================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002355 # Value conversion methods
2356 # ========================
2357 def _get_values(self, action, arg_strings):
R David Murray00528e82012-07-21 22:48:35 -04002358 # for everything but PARSER, REMAINDER args, strip out first '--'
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002359 if action.nargs not in [PARSER, REMAINDER]:
R David Murray00528e82012-07-21 22:48:35 -04002360 try:
2361 arg_strings.remove('--')
2362 except ValueError:
2363 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002364
2365 # optional argument produces a default when not present
2366 if not arg_strings and action.nargs == OPTIONAL:
2367 if action.option_strings:
2368 value = action.const
2369 else:
2370 value = action.default
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00002371 if isinstance(value, str):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002372 value = self._get_value(action, value)
2373 self._check_value(action, value)
2374
2375 # when nargs='*' on a positional, if there were no command-line
2376 # args, use the default if it is anything other than None
2377 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2378 not action.option_strings):
2379 if action.default is not None:
2380 value = action.default
2381 else:
2382 value = arg_strings
2383 self._check_value(action, value)
2384
2385 # single argument or optional argument produces a single value
2386 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2387 arg_string, = arg_strings
2388 value = self._get_value(action, arg_string)
2389 self._check_value(action, value)
2390
2391 # REMAINDER arguments convert all values, checking none
2392 elif action.nargs == REMAINDER:
2393 value = [self._get_value(action, v) for v in arg_strings]
2394
2395 # PARSER arguments convert all values, but check only the first
2396 elif action.nargs == PARSER:
2397 value = [self._get_value(action, v) for v in arg_strings]
2398 self._check_value(action, value[0])
2399
R. David Murray0f6b9d22017-09-06 20:25:40 -04002400 # SUPPRESS argument does not put anything in the namespace
2401 elif action.nargs == SUPPRESS:
2402 value = SUPPRESS
2403
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002404 # all other types of nargs produce a list
2405 else:
2406 value = [self._get_value(action, v) for v in arg_strings]
2407 for v in value:
2408 self._check_value(action, v)
2409
2410 # return the converted value
2411 return value
2412
2413 def _get_value(self, action, arg_string):
2414 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02002415 if not callable(type_func):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002416 msg = _('%r is not callable')
2417 raise ArgumentError(action, msg % type_func)
2418
2419 # convert the value to the appropriate type
2420 try:
2421 result = type_func(arg_string)
2422
2423 # ArgumentTypeErrors indicate errors
2424 except ArgumentTypeError:
2425 name = getattr(action.type, '__name__', repr(action.type))
2426 msg = str(_sys.exc_info()[1])
2427 raise ArgumentError(action, msg)
2428
2429 # TypeErrors or ValueErrors also indicate errors
2430 except (TypeError, ValueError):
2431 name = getattr(action.type, '__name__', repr(action.type))
Éric Araujobb48a8b2010-12-03 19:41:00 +00002432 args = {'type': name, 'value': arg_string}
2433 msg = _('invalid %(type)s value: %(value)r')
2434 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002435
2436 # return the converted value
2437 return result
2438
2439 def _check_value(self, action, value):
2440 # converted value must be one of the choices (if specified)
Vinay Sajip9ae50502016-08-23 08:43:16 +01002441 if action.choices is not None and value not in action.choices:
2442 args = {'value': value,
2443 'choices': ', '.join(map(repr, action.choices))}
2444 msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2445 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002446
2447 # =======================
2448 # Help-formatting methods
2449 # =======================
2450 def format_usage(self):
2451 formatter = self._get_formatter()
2452 formatter.add_usage(self.usage, self._actions,
2453 self._mutually_exclusive_groups)
2454 return formatter.format_help()
2455
2456 def format_help(self):
2457 formatter = self._get_formatter()
2458
2459 # usage
2460 formatter.add_usage(self.usage, self._actions,
2461 self._mutually_exclusive_groups)
2462
2463 # description
2464 formatter.add_text(self.description)
2465
2466 # positionals, optionals and user-defined groups
2467 for action_group in self._action_groups:
2468 formatter.start_section(action_group.title)
2469 formatter.add_text(action_group.description)
2470 formatter.add_arguments(action_group._group_actions)
2471 formatter.end_section()
2472
2473 # epilog
2474 formatter.add_text(self.epilog)
2475
2476 # determine help from format above
2477 return formatter.format_help()
2478
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002479 def _get_formatter(self):
2480 return self.formatter_class(prog=self.prog)
2481
2482 # =====================
2483 # Help-printing methods
2484 # =====================
2485 def print_usage(self, file=None):
2486 if file is None:
2487 file = _sys.stdout
2488 self._print_message(self.format_usage(), file)
2489
2490 def print_help(self, file=None):
2491 if file is None:
2492 file = _sys.stdout
2493 self._print_message(self.format_help(), file)
2494
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002495 def _print_message(self, message, file=None):
2496 if message:
2497 if file is None:
2498 file = _sys.stderr
2499 file.write(message)
2500
2501 # ===============
2502 # Exiting methods
2503 # ===============
2504 def exit(self, status=0, message=None):
2505 if message:
2506 self._print_message(message, _sys.stderr)
2507 _sys.exit(status)
2508
2509 def error(self, message):
2510 """error(message: string)
2511
2512 Prints a usage message incorporating the message to stderr and
2513 exits.
2514
2515 If you override this in a subclass, it should not return -- it
2516 should either exit or raise an exception.
2517 """
2518 self.print_usage(_sys.stderr)
Éric Araujobb48a8b2010-12-03 19:41:00 +00002519 args = {'prog': self.prog, 'message': message}
2520 self.exit(2, _('%(prog)s: error: %(message)s\n') % args)