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