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