blob: b2db312b8fdfd9056bf8894333fcca3948cfa79d [file] [log] [blame]
Benjamin Peterson2b37fc42010-03-24 22:10:42 +00001# Author: Steven J. Bethard <steven.bethard@gmail.com>.
Raymond Hettinger496058f2019-08-29 21:04:37 -07002# New maintainer as of 29 August 2019: Raymond Hettinger <raymond.hettinger@gmail.com>
Benjamin Peterson698a18a2010-03-02 22:34:37 +00003
4"""Command-line parsing library
5
6This module is an optparse-inspired command-line parsing library that:
7
8 - handles both optional and positional arguments
9 - produces highly informative usage messages
10 - supports parsers that dispatch to sub-parsers
11
12The following is a simple usage example that sums integers from the
13command-line and writes the result to a file::
14
15 parser = argparse.ArgumentParser(
16 description='sum the integers at the command line')
17 parser.add_argument(
18 'integers', metavar='int', nargs='+', type=int,
19 help='an integer to be summed')
20 parser.add_argument(
21 '--log', default=sys.stdout, type=argparse.FileType('w'),
22 help='the file where the sum should be written')
23 args = parser.parse_args()
24 args.log.write('%s' % sum(args.integers))
25 args.log.close()
26
27The module contains the following public classes:
28
29 - ArgumentParser -- The main entry point for command-line parsing. As the
30 example above shows, the add_argument() method is used to populate
31 the parser with actions for optional and positional arguments. Then
32 the parse_args() method is invoked to convert the args at the
33 command-line into an object with attributes.
34
35 - ArgumentError -- The exception raised by ArgumentParser objects when
36 there are errors with the parser's actions. Errors raised while
37 parsing the command-line are caught by ArgumentParser and emitted
38 as command-line messages.
39
40 - FileType -- A factory for defining types of files to be created. As the
41 example above shows, instances of FileType are typically passed as
42 the type= argument of add_argument() calls.
43
44 - Action -- The base class for parser actions. Typically actions are
45 selected by passing strings like 'store_true' or 'append_const' to
46 the action= argument of add_argument(). However, for greater
47 customization of ArgumentParser actions, subclasses of Action may
48 be defined and passed as the action= argument.
49
50 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
51 ArgumentDefaultsHelpFormatter -- Formatter classes which
52 may be passed as the formatter_class= argument to the
53 ArgumentParser constructor. HelpFormatter is the default,
54 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
55 not to change the formatting for help text, and
56 ArgumentDefaultsHelpFormatter adds information about argument defaults
57 to the help.
58
59All other classes in this module are considered implementation details.
60(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
61considered public as object names -- the API of the formatter objects is
62still considered an implementation detail.)
63"""
64
65__version__ = '1.1'
66__all__ = [
67 'ArgumentParser',
68 'ArgumentError',
Steven Bethard72c55382010-11-01 15:23:12 +000069 'ArgumentTypeError',
Rémi Lapeyre6a517c62019-09-13 12:17:43 +020070 'BooleanOptionalAction',
Benjamin Peterson698a18a2010-03-02 22:34:37 +000071 'FileType',
72 'HelpFormatter',
Steven Bethard72c55382010-11-01 15:23:12 +000073 'ArgumentDefaultsHelpFormatter',
Benjamin Peterson698a18a2010-03-02 22:34:37 +000074 'RawDescriptionHelpFormatter',
75 'RawTextHelpFormatter',
Steven Bethard0331e902011-03-26 14:48:04 +010076 'MetavarTypeHelpFormatter',
Steven Bethard72c55382010-11-01 15:23:12 +000077 'Namespace',
78 'Action',
79 'ONE_OR_MORE',
80 'OPTIONAL',
81 'PARSER',
82 'REMAINDER',
83 'SUPPRESS',
84 'ZERO_OR_MORE',
Benjamin Peterson698a18a2010-03-02 22:34:37 +000085]
86
87
Benjamin Peterson698a18a2010-03-02 22:34:37 +000088import os as _os
89import re as _re
90import sys as _sys
Benjamin Peterson698a18a2010-03-02 22:34:37 +000091
Éric Araujo12159152010-12-04 17:31:49 +000092from gettext import gettext as _, ngettext
Benjamin Peterson698a18a2010-03-02 22:34:37 +000093
Benjamin Peterson698a18a2010-03-02 22:34:37 +000094SUPPRESS = '==SUPPRESS=='
95
96OPTIONAL = '?'
97ZERO_OR_MORE = '*'
98ONE_OR_MORE = '+'
99PARSER = 'A...'
100REMAINDER = '...'
Steven Bethardfca2e8a2010-11-02 12:47:22 +0000101_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000102
103# =============================
104# Utility functions and classes
105# =============================
106
107class _AttributeHolder(object):
108 """Abstract base class that provides __repr__.
109
110 The __repr__ method returns a string in the format::
111 ClassName(attr=name, attr=name, ...)
112 The attributes are determined either by a class-level attribute,
113 '_kwarg_names', or by inspecting the instance __dict__.
114 """
115
116 def __repr__(self):
117 type_name = type(self).__name__
118 arg_strings = []
Berker Peksag76b17142015-07-29 23:51:47 +0300119 star_args = {}
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000120 for arg in self._get_args():
121 arg_strings.append(repr(arg))
122 for name, value in self._get_kwargs():
Berker Peksag76b17142015-07-29 23:51:47 +0300123 if name.isidentifier():
124 arg_strings.append('%s=%r' % (name, value))
125 else:
126 star_args[name] = value
127 if star_args:
128 arg_strings.append('**%s' % repr(star_args))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000129 return '%s(%s)' % (type_name, ', '.join(arg_strings))
130
131 def _get_kwargs(self):
Raymond Hettinger96819532020-05-17 18:53:01 -0700132 return list(self.__dict__.items())
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000133
134 def _get_args(self):
135 return []
136
137
Serhiy Storchaka81108372017-09-26 00:55:55 +0300138def _copy_items(items):
139 if items is None:
140 return []
141 # The copy module is used only in the 'append' and 'append_const'
142 # actions, and it is needed only when the default value isn't a list.
143 # Delay its import for speeding up the common case.
144 if type(items) is list:
145 return items[:]
146 import copy
147 return copy.copy(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000148
149
150# ===============
151# Formatting Help
152# ===============
153
154class HelpFormatter(object):
155 """Formatter for generating usage messages and argument help strings.
156
157 Only the name of this class is considered a public API. All the methods
158 provided by the class are considered an implementation detail.
159 """
160
161 def __init__(self,
162 prog,
163 indent_increment=2,
164 max_help_position=24,
165 width=None):
166
167 # default setting for width
168 if width is None:
Raymond Hettingerb4e5eea2019-11-21 22:51:45 -0800169 import shutil
170 width = shutil.get_terminal_size().columns
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000171 width -= 2
172
173 self._prog = prog
174 self._indent_increment = indent_increment
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200175 self._max_help_position = min(max_help_position,
176 max(width - 20, indent_increment * 2))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000177 self._width = width
178
179 self._current_indent = 0
180 self._level = 0
181 self._action_max_length = 0
182
183 self._root_section = self._Section(self, None)
184 self._current_section = self._root_section
185
Xiang Zhang7fe28ad2017-01-22 14:37:22 +0800186 self._whitespace_matcher = _re.compile(r'\s+', _re.ASCII)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000187 self._long_break_matcher = _re.compile(r'\n\n\n+')
188
189 # ===============================
190 # Section and indentation methods
191 # ===============================
192 def _indent(self):
193 self._current_indent += self._indent_increment
194 self._level += 1
195
196 def _dedent(self):
197 self._current_indent -= self._indent_increment
198 assert self._current_indent >= 0, 'Indent decreased below 0.'
199 self._level -= 1
200
201 class _Section(object):
202
203 def __init__(self, formatter, parent, heading=None):
204 self.formatter = formatter
205 self.parent = parent
206 self.heading = heading
207 self.items = []
208
209 def format_help(self):
210 # format the indented section
211 if self.parent is not None:
212 self.formatter._indent()
213 join = self.formatter._join_parts
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000214 item_help = join([func(*args) for func, args in self.items])
215 if self.parent is not None:
216 self.formatter._dedent()
217
218 # return nothing if the section was empty
219 if not item_help:
220 return ''
221
222 # add the heading if the section was non-empty
223 if self.heading is not SUPPRESS and self.heading is not None:
224 current_indent = self.formatter._current_indent
225 heading = '%*s%s:\n' % (current_indent, '', self.heading)
226 else:
227 heading = ''
228
229 # join the section-initial newline, the heading and the help
230 return join(['\n', heading, item_help, '\n'])
231
232 def _add_item(self, func, args):
233 self._current_section.items.append((func, args))
234
235 # ========================
236 # Message building methods
237 # ========================
238 def start_section(self, heading):
239 self._indent()
240 section = self._Section(self, self._current_section, heading)
241 self._add_item(section.format_help, [])
242 self._current_section = section
243
244 def end_section(self):
245 self._current_section = self._current_section.parent
246 self._dedent()
247
248 def add_text(self, text):
249 if text is not SUPPRESS and text is not None:
250 self._add_item(self._format_text, [text])
251
252 def add_usage(self, usage, actions, groups, prefix=None):
253 if usage is not SUPPRESS:
254 args = usage, actions, groups, prefix
255 self._add_item(self._format_usage, args)
256
257 def add_argument(self, action):
258 if action.help is not SUPPRESS:
259
260 # find all invocations
261 get_invocation = self._format_action_invocation
262 invocations = [get_invocation(action)]
263 for subaction in self._iter_indented_subactions(action):
264 invocations.append(get_invocation(subaction))
265
266 # update the maximum item length
Raymond Hettingerb4e5eea2019-11-21 22:51:45 -0800267 invocation_length = max(map(len, invocations))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000268 action_length = invocation_length + self._current_indent
269 self._action_max_length = max(self._action_max_length,
270 action_length)
271
272 # add the item to the list
273 self._add_item(self._format_action, [action])
274
275 def add_arguments(self, actions):
276 for action in actions:
277 self.add_argument(action)
278
279 # =======================
280 # Help-formatting methods
281 # =======================
282 def format_help(self):
283 help = self._root_section.format_help()
284 if help:
285 help = self._long_break_matcher.sub('\n\n', help)
286 help = help.strip('\n') + '\n'
287 return help
288
289 def _join_parts(self, part_strings):
290 return ''.join([part
291 for part in part_strings
292 if part and part is not SUPPRESS])
293
294 def _format_usage(self, usage, actions, groups, prefix):
295 if prefix is None:
296 prefix = _('usage: ')
297
298 # if usage is specified, use that
299 if usage is not None:
300 usage = usage % dict(prog=self._prog)
301
302 # if no optionals or positionals are available, usage is just prog
303 elif usage is None and not actions:
304 usage = '%(prog)s' % dict(prog=self._prog)
305
306 # if optionals and positionals are available, calculate usage
307 elif usage is None:
308 prog = '%(prog)s' % dict(prog=self._prog)
309
310 # split optionals from positionals
311 optionals = []
312 positionals = []
313 for action in actions:
314 if action.option_strings:
315 optionals.append(action)
316 else:
317 positionals.append(action)
318
319 # build full usage string
320 format = self._format_actions_usage
321 action_usage = format(optionals + positionals, groups)
322 usage = ' '.join([s for s in [prog, action_usage] if s])
323
324 # wrap the usage parts if it's too long
325 text_width = self._width - self._current_indent
326 if len(prefix) + len(usage) > text_width:
327
328 # break usage into wrappable parts
wim glenn66f02aa2018-06-08 05:12:49 -0500329 part_regexp = (
330 r'\(.*?\)+(?=\s|$)|'
331 r'\[.*?\]+(?=\s|$)|'
332 r'\S+'
333 )
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000334 opt_usage = format(optionals, groups)
335 pos_usage = format(positionals, groups)
336 opt_parts = _re.findall(part_regexp, opt_usage)
337 pos_parts = _re.findall(part_regexp, pos_usage)
338 assert ' '.join(opt_parts) == opt_usage
339 assert ' '.join(pos_parts) == pos_usage
340
341 # helper for wrapping lines
342 def get_lines(parts, indent, prefix=None):
343 lines = []
344 line = []
345 if prefix is not None:
346 line_len = len(prefix) - 1
347 else:
348 line_len = len(indent) - 1
349 for part in parts:
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200350 if line_len + 1 + len(part) > text_width and line:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000351 lines.append(indent + ' '.join(line))
352 line = []
353 line_len = len(indent) - 1
354 line.append(part)
355 line_len += len(part) + 1
356 if line:
357 lines.append(indent + ' '.join(line))
358 if prefix is not None:
359 lines[0] = lines[0][len(indent):]
360 return lines
361
362 # if prog is short, follow it with optionals or positionals
363 if len(prefix) + len(prog) <= 0.75 * text_width:
364 indent = ' ' * (len(prefix) + len(prog) + 1)
365 if opt_parts:
366 lines = get_lines([prog] + opt_parts, indent, prefix)
367 lines.extend(get_lines(pos_parts, indent))
368 elif pos_parts:
369 lines = get_lines([prog] + pos_parts, indent, prefix)
370 else:
371 lines = [prog]
372
373 # if prog is long, put it on its own line
374 else:
375 indent = ' ' * len(prefix)
376 parts = opt_parts + pos_parts
377 lines = get_lines(parts, indent)
378 if len(lines) > 1:
379 lines = []
380 lines.extend(get_lines(opt_parts, indent))
381 lines.extend(get_lines(pos_parts, indent))
382 lines = [prog] + lines
383
384 # join lines into usage
385 usage = '\n'.join(lines)
386
387 # prefix with 'usage:'
388 return '%s%s\n\n' % (prefix, usage)
389
390 def _format_actions_usage(self, actions, groups):
391 # find group indices and identify actions in groups
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000392 group_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000393 inserts = {}
394 for group in groups:
Miss Islington (bot)8e4c9622021-12-15 04:20:04 -0800395 if not group._group_actions:
396 raise ValueError(f'empty group {group}')
397
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000398 try:
399 start = actions.index(group._group_actions[0])
400 except ValueError:
401 continue
402 else:
403 end = start + len(group._group_actions)
404 if actions[start:end] == group._group_actions:
405 for action in group._group_actions:
406 group_actions.add(action)
407 if not group.required:
Steven Bethard49998ee2010-11-01 16:29:26 +0000408 if start in inserts:
409 inserts[start] += ' ['
410 else:
411 inserts[start] = '['
Flavian Hautboisda27d9b2019-08-25 21:06:45 +0200412 if end in inserts:
413 inserts[end] += ']'
414 else:
415 inserts[end] = ']'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000416 else:
Steven Bethard49998ee2010-11-01 16:29:26 +0000417 if start in inserts:
418 inserts[start] += ' ('
419 else:
420 inserts[start] = '('
Flavian Hautboisda27d9b2019-08-25 21:06:45 +0200421 if end in inserts:
422 inserts[end] += ')'
423 else:
424 inserts[end] = ')'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000425 for i in range(start + 1, end):
426 inserts[i] = '|'
427
428 # collect all actions format strings
429 parts = []
430 for i, action in enumerate(actions):
431
432 # suppressed arguments are marked with None
433 # remove | separators for suppressed arguments
434 if action.help is SUPPRESS:
435 parts.append(None)
436 if inserts.get(i) == '|':
437 inserts.pop(i)
438 elif inserts.get(i + 1) == '|':
439 inserts.pop(i + 1)
440
441 # produce all arg strings
442 elif not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100443 default = self._get_default_metavar_for_positional(action)
444 part = self._format_args(action, default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000445
446 # if it's in a group, strip the outer []
447 if action in group_actions:
448 if part[0] == '[' and part[-1] == ']':
449 part = part[1:-1]
450
451 # add the action string to the list
452 parts.append(part)
453
454 # produce the first way to invoke the option in brackets
455 else:
456 option_string = action.option_strings[0]
457
458 # if the Optional doesn't take a value, format is:
459 # -s or --long
460 if action.nargs == 0:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200461 part = action.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000462
463 # if the Optional takes a value, format is:
464 # -s ARGS or --long ARGS
465 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100466 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000467 args_string = self._format_args(action, default)
468 part = '%s %s' % (option_string, args_string)
469
470 # make it look optional if it's not required or in a group
471 if not action.required and action not in group_actions:
472 part = '[%s]' % part
473
474 # add the action string to the list
475 parts.append(part)
476
477 # insert things at the necessary indices
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000478 for i in sorted(inserts, reverse=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000479 parts[i:i] = [inserts[i]]
480
481 # join all the action items with spaces
482 text = ' '.join([item for item in parts if item is not None])
483
484 # clean up separators for mutually exclusive groups
485 open = r'[\[(]'
486 close = r'[\])]'
487 text = _re.sub(r'(%s) ' % open, r'\1', text)
488 text = _re.sub(r' (%s)' % close, r'\1', text)
489 text = _re.sub(r'%s *%s' % (open, close), r'', text)
490 text = _re.sub(r'\(([^|]*)\)', r'\1', text)
491 text = text.strip()
492
493 # return the text
494 return text
495
496 def _format_text(self, text):
497 if '%(prog)' in text:
498 text = text % dict(prog=self._prog)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200499 text_width = max(self._width - self._current_indent, 11)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000500 indent = ' ' * self._current_indent
501 return self._fill_text(text, text_width, indent) + '\n\n'
502
503 def _format_action(self, action):
504 # determine the required width and the entry label
505 help_position = min(self._action_max_length + 2,
506 self._max_help_position)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200507 help_width = max(self._width - help_position, 11)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000508 action_width = help_position - self._current_indent - 2
509 action_header = self._format_action_invocation(action)
510
Georg Brandl2514f522014-10-20 08:36:02 +0200511 # no help; start on same line and add a final newline
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000512 if not action.help:
513 tup = self._current_indent, '', action_header
514 action_header = '%*s%s\n' % tup
515
516 # short action name; start on the same line and pad two spaces
517 elif len(action_header) <= action_width:
518 tup = self._current_indent, '', action_width, action_header
519 action_header = '%*s%-*s ' % tup
520 indent_first = 0
521
522 # long action name; start on the next line
523 else:
524 tup = self._current_indent, '', action_header
525 action_header = '%*s%s\n' % tup
526 indent_first = help_position
527
528 # collect the pieces of the action help
529 parts = [action_header]
530
531 # if there was help for the action, add lines of help text
Miss Islington (bot)fd2be6d2021-10-13 10:15:43 -0700532 if action.help and action.help.strip():
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000533 help_text = self._expand_help(action)
Miss Islington (bot)fd2be6d2021-10-13 10:15:43 -0700534 if help_text:
535 help_lines = self._split_lines(help_text, help_width)
536 parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
537 for line in help_lines[1:]:
538 parts.append('%*s%s\n' % (help_position, '', line))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000539
540 # or add a newline if the description doesn't end with one
541 elif not action_header.endswith('\n'):
542 parts.append('\n')
543
544 # if there are any sub-actions, add their help as well
545 for subaction in self._iter_indented_subactions(action):
546 parts.append(self._format_action(subaction))
547
548 # return a single string
549 return self._join_parts(parts)
550
551 def _format_action_invocation(self, action):
552 if not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100553 default = self._get_default_metavar_for_positional(action)
554 metavar, = self._metavar_formatter(action, default)(1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000555 return metavar
556
557 else:
558 parts = []
559
560 # if the Optional doesn't take a value, format is:
561 # -s, --long
562 if action.nargs == 0:
563 parts.extend(action.option_strings)
564
565 # if the Optional takes a value, format is:
566 # -s ARGS, --long ARGS
567 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100568 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000569 args_string = self._format_args(action, default)
570 for option_string in action.option_strings:
571 parts.append('%s %s' % (option_string, args_string))
572
573 return ', '.join(parts)
574
575 def _metavar_formatter(self, action, default_metavar):
576 if action.metavar is not None:
577 result = action.metavar
578 elif action.choices is not None:
579 choice_strs = [str(choice) for choice in action.choices]
580 result = '{%s}' % ','.join(choice_strs)
581 else:
582 result = default_metavar
583
584 def format(tuple_size):
585 if isinstance(result, tuple):
586 return result
587 else:
588 return (result, ) * tuple_size
589 return format
590
591 def _format_args(self, action, default_metavar):
592 get_metavar = self._metavar_formatter(action, default_metavar)
593 if action.nargs is None:
594 result = '%s' % get_metavar(1)
595 elif action.nargs == OPTIONAL:
596 result = '[%s]' % get_metavar(1)
597 elif action.nargs == ZERO_OR_MORE:
Brandt Buchera0ed99b2019-11-11 12:47:48 -0800598 metavar = get_metavar(1)
599 if len(metavar) == 2:
600 result = '[%s [%s ...]]' % metavar
601 else:
602 result = '[%s ...]' % metavar
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000603 elif action.nargs == ONE_OR_MORE:
604 result = '%s [%s ...]' % get_metavar(2)
605 elif action.nargs == REMAINDER:
606 result = '...'
607 elif action.nargs == PARSER:
608 result = '%s ...' % get_metavar(1)
R. David Murray0f6b9d22017-09-06 20:25:40 -0400609 elif action.nargs == SUPPRESS:
610 result = ''
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000611 else:
tmblweed4b3e9752019-08-01 21:57:13 -0700612 try:
613 formats = ['%s' for _ in range(action.nargs)]
614 except TypeError:
615 raise ValueError("invalid nargs value") from None
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000616 result = ' '.join(formats) % get_metavar(action.nargs)
617 return result
618
619 def _expand_help(self, action):
620 params = dict(vars(action), prog=self._prog)
621 for name in list(params):
622 if params[name] is SUPPRESS:
623 del params[name]
624 for name in list(params):
625 if hasattr(params[name], '__name__'):
626 params[name] = params[name].__name__
627 if params.get('choices') is not None:
628 choices_str = ', '.join([str(c) for c in params['choices']])
629 params['choices'] = choices_str
630 return self._get_help_string(action) % params
631
632 def _iter_indented_subactions(self, action):
633 try:
634 get_subactions = action._get_subactions
635 except AttributeError:
636 pass
637 else:
638 self._indent()
Philip Jenvey4993cc02012-10-01 12:53:43 -0700639 yield from get_subactions()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000640 self._dedent()
641
642 def _split_lines(self, text, width):
643 text = self._whitespace_matcher.sub(' ', text).strip()
Serhiy Storchaka81108372017-09-26 00:55:55 +0300644 # The textwrap module is used only for formatting help.
645 # Delay its import for speeding up the common usage of argparse.
646 import textwrap
647 return textwrap.wrap(text, width)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000648
649 def _fill_text(self, text, width, indent):
650 text = self._whitespace_matcher.sub(' ', text).strip()
Serhiy Storchaka81108372017-09-26 00:55:55 +0300651 import textwrap
652 return textwrap.fill(text, width,
653 initial_indent=indent,
654 subsequent_indent=indent)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000655
656 def _get_help_string(self, action):
657 return action.help
658
Steven Bethard0331e902011-03-26 14:48:04 +0100659 def _get_default_metavar_for_optional(self, action):
660 return action.dest.upper()
661
662 def _get_default_metavar_for_positional(self, action):
663 return action.dest
664
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000665
666class RawDescriptionHelpFormatter(HelpFormatter):
667 """Help message formatter which retains any formatting in descriptions.
668
669 Only the name of this class is considered a public API. All the methods
670 provided by the class are considered an implementation detail.
671 """
672
673 def _fill_text(self, text, width, indent):
Ezio Melottid8b509b2011-09-28 17:37:55 +0300674 return ''.join(indent + line for line in text.splitlines(keepends=True))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000675
676
677class RawTextHelpFormatter(RawDescriptionHelpFormatter):
678 """Help message formatter which retains formatting of all help text.
679
680 Only the name of this class is considered a public API. All the methods
681 provided by the class are considered an implementation detail.
682 """
683
684 def _split_lines(self, text, width):
685 return text.splitlines()
686
687
688class ArgumentDefaultsHelpFormatter(HelpFormatter):
689 """Help message formatter which adds default values to argument help.
690
691 Only the name of this class is considered a public API. All the methods
692 provided by the class are considered an implementation detail.
693 """
694
695 def _get_help_string(self, action):
696 help = action.help
697 if '%(default)' not in action.help:
698 if action.default is not SUPPRESS:
699 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
700 if action.option_strings or action.nargs in defaulting_nargs:
701 help += ' (default: %(default)s)'
702 return help
703
704
Steven Bethard0331e902011-03-26 14:48:04 +0100705class MetavarTypeHelpFormatter(HelpFormatter):
706 """Help message formatter which uses the argument 'type' as the default
707 metavar value (instead of the argument 'dest')
708
709 Only the name of this class is considered a public API. All the methods
710 provided by the class are considered an implementation detail.
711 """
712
713 def _get_default_metavar_for_optional(self, action):
714 return action.type.__name__
715
716 def _get_default_metavar_for_positional(self, action):
717 return action.type.__name__
718
719
720
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000721# =====================
722# Options and Arguments
723# =====================
724
725def _get_action_name(argument):
726 if argument is None:
727 return None
728 elif argument.option_strings:
729 return '/'.join(argument.option_strings)
730 elif argument.metavar not in (None, SUPPRESS):
731 return argument.metavar
732 elif argument.dest not in (None, SUPPRESS):
733 return argument.dest
Miss Islington (bot)c5899922021-07-23 06:27:05 -0700734 elif argument.choices:
735 return '{' + ','.join(argument.choices) + '}'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000736 else:
737 return None
738
739
740class ArgumentError(Exception):
741 """An error from creating or using an argument (optional or positional).
742
743 The string value of this exception is the message, augmented with
744 information about the argument that caused it.
745 """
746
747 def __init__(self, argument, message):
748 self.argument_name = _get_action_name(argument)
749 self.message = message
750
751 def __str__(self):
752 if self.argument_name is None:
753 format = '%(message)s'
754 else:
755 format = 'argument %(argument_name)s: %(message)s'
756 return format % dict(message=self.message,
757 argument_name=self.argument_name)
758
759
760class ArgumentTypeError(Exception):
761 """An error from trying to convert a command line string to a type."""
762 pass
763
764
765# ==============
766# Action classes
767# ==============
768
769class Action(_AttributeHolder):
770 """Information about how to convert command line strings to Python objects.
771
772 Action objects are used by an ArgumentParser to represent the information
773 needed to parse a single argument from one or more strings from the
774 command line. The keyword arguments to the Action constructor are also
775 all attributes of Action instances.
776
777 Keyword Arguments:
778
779 - option_strings -- A list of command-line option strings which
780 should be associated with this action.
781
782 - dest -- The name of the attribute to hold the created object(s)
783
784 - nargs -- The number of command-line arguments that should be
785 consumed. By default, one argument will be consumed and a single
786 value will be produced. Other values include:
787 - N (an integer) consumes N arguments (and produces a list)
788 - '?' consumes zero or one arguments
789 - '*' consumes zero or more arguments (and produces a list)
790 - '+' consumes one or more arguments (and produces a list)
791 Note that the difference between the default and nargs=1 is that
792 with the default, a single value will be produced, while with
793 nargs=1, a list containing a single value will be produced.
794
795 - const -- The value to be produced if the option is specified and the
796 option uses an action that takes no values.
797
798 - default -- The value to be produced if the option is not specified.
799
R David Murray15cd9a02012-07-21 17:04:25 -0400800 - type -- A callable that accepts a single string argument, and
801 returns the converted value. The standard Python types str, int,
802 float, and complex are useful examples of such callables. If None,
803 str is used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000804
805 - choices -- A container of values that should be allowed. If not None,
806 after a command-line argument has been converted to the appropriate
807 type, an exception will be raised if it is not a member of this
808 collection.
809
810 - required -- True if the action must always be specified at the
811 command line. This is only meaningful for optional command-line
812 arguments.
813
814 - help -- The help string describing the argument.
815
816 - metavar -- The name to be used for the option's argument with the
817 help string. If None, the 'dest' value will be used as the name.
818 """
819
820 def __init__(self,
821 option_strings,
822 dest,
823 nargs=None,
824 const=None,
825 default=None,
826 type=None,
827 choices=None,
828 required=False,
829 help=None,
830 metavar=None):
831 self.option_strings = option_strings
832 self.dest = dest
833 self.nargs = nargs
834 self.const = const
835 self.default = default
836 self.type = type
837 self.choices = choices
838 self.required = required
839 self.help = help
840 self.metavar = metavar
841
842 def _get_kwargs(self):
843 names = [
844 'option_strings',
845 'dest',
846 'nargs',
847 'const',
848 'default',
849 'type',
850 'choices',
851 'help',
852 'metavar',
853 ]
854 return [(name, getattr(self, name)) for name in names]
855
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200856 def format_usage(self):
857 return self.option_strings[0]
858
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000859 def __call__(self, parser, namespace, values, option_string=None):
860 raise NotImplementedError(_('.__call__() not defined'))
861
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200862class BooleanOptionalAction(Action):
863 def __init__(self,
864 option_strings,
865 dest,
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200866 default=None,
867 type=None,
868 choices=None,
869 required=False,
870 help=None,
871 metavar=None):
872
873 _option_strings = []
874 for option_string in option_strings:
875 _option_strings.append(option_string)
876
877 if option_string.startswith('--'):
878 option_string = '--no-' + option_string[2:]
879 _option_strings.append(option_string)
880
881 if help is not None and default is not None:
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -0700882 help += " (default: %(default)s)"
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200883
884 super().__init__(
885 option_strings=_option_strings,
886 dest=dest,
887 nargs=0,
888 default=default,
889 type=type,
890 choices=choices,
891 required=required,
892 help=help,
893 metavar=metavar)
894
895 def __call__(self, parser, namespace, values, option_string=None):
896 if option_string in self.option_strings:
897 setattr(namespace, self.dest, not option_string.startswith('--no-'))
898
899 def format_usage(self):
900 return ' | '.join(self.option_strings)
901
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000902
903class _StoreAction(Action):
904
905 def __init__(self,
906 option_strings,
907 dest,
908 nargs=None,
909 const=None,
910 default=None,
911 type=None,
912 choices=None,
913 required=False,
914 help=None,
915 metavar=None):
916 if nargs == 0:
tmblweed4b3e9752019-08-01 21:57:13 -0700917 raise ValueError('nargs for store actions must be != 0; if you '
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000918 'have nothing to store, actions such as store '
919 'true or store const may be more appropriate')
920 if const is not None and nargs != OPTIONAL:
921 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
922 super(_StoreAction, self).__init__(
923 option_strings=option_strings,
924 dest=dest,
925 nargs=nargs,
926 const=const,
927 default=default,
928 type=type,
929 choices=choices,
930 required=required,
931 help=help,
932 metavar=metavar)
933
934 def __call__(self, parser, namespace, values, option_string=None):
935 setattr(namespace, self.dest, values)
936
937
938class _StoreConstAction(Action):
939
940 def __init__(self,
941 option_strings,
942 dest,
943 const,
944 default=None,
945 required=False,
946 help=None,
947 metavar=None):
948 super(_StoreConstAction, self).__init__(
949 option_strings=option_strings,
950 dest=dest,
951 nargs=0,
952 const=const,
953 default=default,
954 required=required,
955 help=help)
956
957 def __call__(self, parser, namespace, values, option_string=None):
958 setattr(namespace, self.dest, self.const)
959
960
961class _StoreTrueAction(_StoreConstAction):
962
963 def __init__(self,
964 option_strings,
965 dest,
966 default=False,
967 required=False,
968 help=None):
969 super(_StoreTrueAction, self).__init__(
970 option_strings=option_strings,
971 dest=dest,
972 const=True,
973 default=default,
974 required=required,
975 help=help)
976
977
978class _StoreFalseAction(_StoreConstAction):
979
980 def __init__(self,
981 option_strings,
982 dest,
983 default=True,
984 required=False,
985 help=None):
986 super(_StoreFalseAction, self).__init__(
987 option_strings=option_strings,
988 dest=dest,
989 const=False,
990 default=default,
991 required=required,
992 help=help)
993
994
995class _AppendAction(Action):
996
997 def __init__(self,
998 option_strings,
999 dest,
1000 nargs=None,
1001 const=None,
1002 default=None,
1003 type=None,
1004 choices=None,
1005 required=False,
1006 help=None,
1007 metavar=None):
1008 if nargs == 0:
tmblweed4b3e9752019-08-01 21:57:13 -07001009 raise ValueError('nargs for append actions must be != 0; if arg '
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001010 'strings are not supplying the value to append, '
1011 'the append const action may be more appropriate')
1012 if const is not None and nargs != OPTIONAL:
1013 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
1014 super(_AppendAction, self).__init__(
1015 option_strings=option_strings,
1016 dest=dest,
1017 nargs=nargs,
1018 const=const,
1019 default=default,
1020 type=type,
1021 choices=choices,
1022 required=required,
1023 help=help,
1024 metavar=metavar)
1025
1026 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001027 items = getattr(namespace, self.dest, None)
1028 items = _copy_items(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001029 items.append(values)
1030 setattr(namespace, self.dest, items)
1031
1032
1033class _AppendConstAction(Action):
1034
1035 def __init__(self,
1036 option_strings,
1037 dest,
1038 const,
1039 default=None,
1040 required=False,
1041 help=None,
1042 metavar=None):
1043 super(_AppendConstAction, self).__init__(
1044 option_strings=option_strings,
1045 dest=dest,
1046 nargs=0,
1047 const=const,
1048 default=default,
1049 required=required,
1050 help=help,
1051 metavar=metavar)
1052
1053 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001054 items = getattr(namespace, self.dest, None)
1055 items = _copy_items(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001056 items.append(self.const)
1057 setattr(namespace, self.dest, items)
1058
1059
1060class _CountAction(Action):
1061
1062 def __init__(self,
1063 option_strings,
1064 dest,
1065 default=None,
1066 required=False,
1067 help=None):
1068 super(_CountAction, self).__init__(
1069 option_strings=option_strings,
1070 dest=dest,
1071 nargs=0,
1072 default=default,
1073 required=required,
1074 help=help)
1075
1076 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001077 count = getattr(namespace, self.dest, None)
1078 if count is None:
1079 count = 0
1080 setattr(namespace, self.dest, count + 1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001081
1082
1083class _HelpAction(Action):
1084
1085 def __init__(self,
1086 option_strings,
1087 dest=SUPPRESS,
1088 default=SUPPRESS,
1089 help=None):
1090 super(_HelpAction, self).__init__(
1091 option_strings=option_strings,
1092 dest=dest,
1093 default=default,
1094 nargs=0,
1095 help=help)
1096
1097 def __call__(self, parser, namespace, values, option_string=None):
1098 parser.print_help()
1099 parser.exit()
1100
1101
1102class _VersionAction(Action):
1103
1104 def __init__(self,
1105 option_strings,
1106 version=None,
1107 dest=SUPPRESS,
1108 default=SUPPRESS,
Steven Bethard50fe5932010-05-24 03:47:38 +00001109 help="show program's version number and exit"):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001110 super(_VersionAction, self).__init__(
1111 option_strings=option_strings,
1112 dest=dest,
1113 default=default,
1114 nargs=0,
1115 help=help)
1116 self.version = version
1117
1118 def __call__(self, parser, namespace, values, option_string=None):
1119 version = self.version
1120 if version is None:
1121 version = parser.version
1122 formatter = parser._get_formatter()
1123 formatter.add_text(version)
Eli Benderskycdac5512013-09-06 06:49:15 -07001124 parser._print_message(formatter.format_help(), _sys.stdout)
1125 parser.exit()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001126
1127
1128class _SubParsersAction(Action):
1129
1130 class _ChoicesPseudoAction(Action):
1131
Steven Bethardfd311a72010-12-18 11:19:23 +00001132 def __init__(self, name, aliases, help):
1133 metavar = dest = name
1134 if aliases:
1135 metavar += ' (%s)' % ', '.join(aliases)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001136 sup = super(_SubParsersAction._ChoicesPseudoAction, self)
Steven Bethardfd311a72010-12-18 11:19:23 +00001137 sup.__init__(option_strings=[], dest=dest, help=help,
1138 metavar=metavar)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001139
1140 def __init__(self,
1141 option_strings,
1142 prog,
1143 parser_class,
1144 dest=SUPPRESS,
Ned Deily8ebf5ce2018-05-23 21:55:15 -04001145 required=False,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001146 help=None,
1147 metavar=None):
1148
1149 self._prog_prefix = prog
1150 self._parser_class = parser_class
Raymond Hettinger05565ed2018-01-11 22:20:33 -08001151 self._name_parser_map = {}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001152 self._choices_actions = []
1153
1154 super(_SubParsersAction, self).__init__(
1155 option_strings=option_strings,
1156 dest=dest,
1157 nargs=PARSER,
1158 choices=self._name_parser_map,
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001159 required=required,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001160 help=help,
1161 metavar=metavar)
1162
1163 def add_parser(self, name, **kwargs):
1164 # set prog from the existing prefix
1165 if kwargs.get('prog') is None:
1166 kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1167
Steven Bethardfd311a72010-12-18 11:19:23 +00001168 aliases = kwargs.pop('aliases', ())
1169
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001170 # create a pseudo-action to hold the choice help
1171 if 'help' in kwargs:
1172 help = kwargs.pop('help')
Steven Bethardfd311a72010-12-18 11:19:23 +00001173 choice_action = self._ChoicesPseudoAction(name, aliases, help)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001174 self._choices_actions.append(choice_action)
1175
1176 # create the parser and add it to the map
1177 parser = self._parser_class(**kwargs)
1178 self._name_parser_map[name] = parser
Steven Bethardfd311a72010-12-18 11:19:23 +00001179
1180 # make parser available under aliases also
1181 for alias in aliases:
1182 self._name_parser_map[alias] = parser
1183
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001184 return parser
1185
1186 def _get_subactions(self):
1187 return self._choices_actions
1188
1189 def __call__(self, parser, namespace, values, option_string=None):
1190 parser_name = values[0]
1191 arg_strings = values[1:]
1192
1193 # set the parser name if requested
1194 if self.dest is not SUPPRESS:
1195 setattr(namespace, self.dest, parser_name)
1196
1197 # select the parser
1198 try:
1199 parser = self._name_parser_map[parser_name]
1200 except KeyError:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001201 args = {'parser_name': parser_name,
1202 'choices': ', '.join(self._name_parser_map)}
1203 msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001204 raise ArgumentError(self, msg)
1205
1206 # parse all the remaining options into the namespace
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001207 # store any unrecognized options on the object, so that the top
1208 # level parser can decide what to do with them
R David Murray7570cbd2014-10-17 19:55:11 -04001209
1210 # In case this subparser defines new defaults, we parse them
1211 # in a new namespace object and then update the original
1212 # namespace for the relevant parts.
1213 subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
1214 for key, value in vars(subnamespace).items():
Miss Islington (bot)e4c5a5e2021-11-12 10:44:55 -08001215 setattr(namespace, key, value)
R David Murray7570cbd2014-10-17 19:55:11 -04001216
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001217 if arg_strings:
1218 vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1219 getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001220
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001221class _ExtendAction(_AppendAction):
1222 def __call__(self, parser, namespace, values, option_string=None):
1223 items = getattr(namespace, self.dest, None)
1224 items = _copy_items(items)
1225 items.extend(values)
1226 setattr(namespace, self.dest, items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001227
1228# ==============
1229# Type classes
1230# ==============
1231
1232class FileType(object):
1233 """Factory for creating file object types
1234
1235 Instances of FileType are typically passed as type= arguments to the
1236 ArgumentParser add_argument() method.
1237
1238 Keyword Arguments:
1239 - mode -- A string indicating how the file is to be opened. Accepts the
1240 same values as the builtin open() function.
1241 - bufsize -- The file's desired buffer size. Accepts the same values as
1242 the builtin open() function.
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001243 - encoding -- The file's encoding. Accepts the same values as the
Terry Jan Reedy8e7586b2013-03-11 18:38:13 -04001244 builtin open() function.
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001245 - errors -- A string indicating how encoding and decoding errors are to
1246 be handled. Accepts the same value as the builtin open() function.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001247 """
1248
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001249 def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001250 self._mode = mode
1251 self._bufsize = bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001252 self._encoding = encoding
1253 self._errors = errors
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001254
1255 def __call__(self, string):
1256 # the special argument "-" means sys.std{in,out}
1257 if string == '-':
1258 if 'r' in self._mode:
1259 return _sys.stdin
1260 elif 'w' in self._mode:
1261 return _sys.stdout
1262 else:
Éric Araujoa9c7a8f2010-12-03 19:19:17 +00001263 msg = _('argument "-" with mode %r') % self._mode
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001264 raise ValueError(msg)
1265
1266 # all other arguments are used as file names
Steven Bethardb0270112011-01-24 21:02:50 +00001267 try:
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001268 return open(string, self._mode, self._bufsize, self._encoding,
1269 self._errors)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001270 except OSError as e:
Jakub Kulík42671ae2019-09-13 11:25:32 +02001271 args = {'filename': string, 'error': e}
1272 message = _("can't open '%(filename)s': %(error)s")
1273 raise ArgumentTypeError(message % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001274
1275 def __repr__(self):
Steven Bethardb0270112011-01-24 21:02:50 +00001276 args = self._mode, self._bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001277 kwargs = [('encoding', self._encoding), ('errors', self._errors)]
1278 args_str = ', '.join([repr(arg) for arg in args if arg != -1] +
1279 ['%s=%r' % (kw, arg) for kw, arg in kwargs
1280 if arg is not None])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001281 return '%s(%s)' % (type(self).__name__, args_str)
1282
1283# ===========================
1284# Optional and Positional Parsing
1285# ===========================
1286
1287class Namespace(_AttributeHolder):
1288 """Simple object for storing attributes.
1289
1290 Implements equality by attribute names and values, and provides a simple
1291 string representation.
1292 """
1293
1294 def __init__(self, **kwargs):
1295 for name in kwargs:
1296 setattr(self, name, kwargs[name])
1297
1298 def __eq__(self, other):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07001299 if not isinstance(other, Namespace):
1300 return NotImplemented
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001301 return vars(self) == vars(other)
1302
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001303 def __contains__(self, key):
1304 return key in self.__dict__
1305
1306
1307class _ActionsContainer(object):
1308
1309 def __init__(self,
1310 description,
1311 prefix_chars,
1312 argument_default,
1313 conflict_handler):
1314 super(_ActionsContainer, self).__init__()
1315
1316 self.description = description
1317 self.argument_default = argument_default
1318 self.prefix_chars = prefix_chars
1319 self.conflict_handler = conflict_handler
1320
1321 # set up registries
1322 self._registries = {}
1323
1324 # register actions
1325 self.register('action', None, _StoreAction)
1326 self.register('action', 'store', _StoreAction)
1327 self.register('action', 'store_const', _StoreConstAction)
1328 self.register('action', 'store_true', _StoreTrueAction)
1329 self.register('action', 'store_false', _StoreFalseAction)
1330 self.register('action', 'append', _AppendAction)
1331 self.register('action', 'append_const', _AppendConstAction)
1332 self.register('action', 'count', _CountAction)
1333 self.register('action', 'help', _HelpAction)
1334 self.register('action', 'version', _VersionAction)
1335 self.register('action', 'parsers', _SubParsersAction)
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001336 self.register('action', 'extend', _ExtendAction)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001337
1338 # raise an exception if the conflict handler is invalid
1339 self._get_handler()
1340
1341 # action storage
1342 self._actions = []
1343 self._option_string_actions = {}
1344
1345 # groups
1346 self._action_groups = []
1347 self._mutually_exclusive_groups = []
1348
1349 # defaults storage
1350 self._defaults = {}
1351
1352 # determines whether an "option" looks like a negative number
1353 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1354
1355 # whether or not there are any optionals that look like negative
1356 # numbers -- uses a list so it can be shared and edited
1357 self._has_negative_number_optionals = []
1358
1359 # ====================
1360 # Registration methods
1361 # ====================
1362 def register(self, registry_name, value, object):
1363 registry = self._registries.setdefault(registry_name, {})
1364 registry[value] = object
1365
1366 def _registry_get(self, registry_name, value, default=None):
1367 return self._registries[registry_name].get(value, default)
1368
1369 # ==================================
1370 # Namespace default accessor methods
1371 # ==================================
1372 def set_defaults(self, **kwargs):
1373 self._defaults.update(kwargs)
1374
1375 # if these defaults match any existing arguments, replace
1376 # the previous default on the object with the new one
1377 for action in self._actions:
1378 if action.dest in kwargs:
1379 action.default = kwargs[action.dest]
1380
1381 def get_default(self, dest):
1382 for action in self._actions:
1383 if action.dest == dest and action.default is not None:
1384 return action.default
1385 return self._defaults.get(dest, None)
1386
1387
1388 # =======================
1389 # Adding argument actions
1390 # =======================
1391 def add_argument(self, *args, **kwargs):
1392 """
1393 add_argument(dest, ..., name=value, ...)
1394 add_argument(option_string, option_string, ..., name=value, ...)
1395 """
1396
1397 # if no positional args are supplied or only one is supplied and
1398 # it doesn't look like an option string, parse a positional
1399 # argument
1400 chars = self.prefix_chars
1401 if not args or len(args) == 1 and args[0][0] not in chars:
1402 if args and 'dest' in kwargs:
1403 raise ValueError('dest supplied twice for positional argument')
1404 kwargs = self._get_positional_kwargs(*args, **kwargs)
1405
1406 # otherwise, we're adding an optional argument
1407 else:
1408 kwargs = self._get_optional_kwargs(*args, **kwargs)
1409
1410 # if no default was supplied, use the parser-level default
1411 if 'default' not in kwargs:
1412 dest = kwargs['dest']
1413 if dest in self._defaults:
1414 kwargs['default'] = self._defaults[dest]
1415 elif self.argument_default is not None:
1416 kwargs['default'] = self.argument_default
1417
1418 # create the action object, and add it to the parser
1419 action_class = self._pop_action_class(kwargs)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001420 if not callable(action_class):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001421 raise ValueError('unknown action "%s"' % (action_class,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001422 action = action_class(**kwargs)
1423
1424 # raise an error if the action type is not callable
1425 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001426 if not callable(type_func):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001427 raise ValueError('%r is not callable' % (type_func,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001428
zygocephalus03d58312019-06-07 23:08:36 +03001429 if type_func is FileType:
1430 raise ValueError('%r is a FileType class object, instance of it'
1431 ' must be passed' % (type_func,))
1432
Steven Bethard8d9a4622011-03-26 17:33:56 +01001433 # raise an error if the metavar does not match the type
1434 if hasattr(self, "_get_formatter"):
1435 try:
1436 self._get_formatter()._format_args(action, None)
1437 except TypeError:
1438 raise ValueError("length of metavar tuple does not match nargs")
1439
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001440 return self._add_action(action)
1441
1442 def add_argument_group(self, *args, **kwargs):
1443 group = _ArgumentGroup(self, *args, **kwargs)
1444 self._action_groups.append(group)
1445 return group
1446
1447 def add_mutually_exclusive_group(self, **kwargs):
1448 group = _MutuallyExclusiveGroup(self, **kwargs)
1449 self._mutually_exclusive_groups.append(group)
1450 return group
1451
1452 def _add_action(self, action):
1453 # resolve any conflicts
1454 self._check_conflict(action)
1455
1456 # add to actions list
1457 self._actions.append(action)
1458 action.container = self
1459
1460 # index the action by any option strings it has
1461 for option_string in action.option_strings:
1462 self._option_string_actions[option_string] = action
1463
1464 # set the flag if any option strings look like negative numbers
1465 for option_string in action.option_strings:
1466 if self._negative_number_matcher.match(option_string):
1467 if not self._has_negative_number_optionals:
1468 self._has_negative_number_optionals.append(True)
1469
1470 # return the created action
1471 return action
1472
1473 def _remove_action(self, action):
1474 self._actions.remove(action)
1475
1476 def _add_container_actions(self, container):
1477 # collect groups by titles
1478 title_group_map = {}
1479 for group in self._action_groups:
1480 if group.title in title_group_map:
1481 msg = _('cannot merge actions - two groups are named %r')
1482 raise ValueError(msg % (group.title))
1483 title_group_map[group.title] = group
1484
1485 # map each action to its group
1486 group_map = {}
1487 for group in container._action_groups:
1488
1489 # if a group with the title exists, use that, otherwise
1490 # create a new group matching the container's group
1491 if group.title not in title_group_map:
1492 title_group_map[group.title] = self.add_argument_group(
1493 title=group.title,
1494 description=group.description,
1495 conflict_handler=group.conflict_handler)
1496
1497 # map the actions to their new group
1498 for action in group._group_actions:
1499 group_map[action] = title_group_map[group.title]
1500
1501 # add container's mutually exclusive groups
1502 # NOTE: if add_mutually_exclusive_group ever gains title= and
1503 # description= then this code will need to be expanded as above
1504 for group in container._mutually_exclusive_groups:
1505 mutex_group = self.add_mutually_exclusive_group(
1506 required=group.required)
1507
1508 # map the actions to their new mutex group
1509 for action in group._group_actions:
1510 group_map[action] = mutex_group
1511
1512 # add all actions to this container or their group
1513 for action in container._actions:
1514 group_map.get(action, self)._add_action(action)
1515
1516 def _get_positional_kwargs(self, dest, **kwargs):
1517 # make sure required is not specified
1518 if 'required' in kwargs:
1519 msg = _("'required' is an invalid argument for positionals")
1520 raise TypeError(msg)
1521
1522 # mark positional arguments as required if at least one is
1523 # always required
1524 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1525 kwargs['required'] = True
1526 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1527 kwargs['required'] = True
1528
1529 # return the keyword arguments with no option strings
1530 return dict(kwargs, dest=dest, option_strings=[])
1531
1532 def _get_optional_kwargs(self, *args, **kwargs):
1533 # determine short and long option strings
1534 option_strings = []
1535 long_option_strings = []
1536 for option_string in args:
1537 # error on strings that don't start with an appropriate prefix
1538 if not option_string[0] in self.prefix_chars:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001539 args = {'option': option_string,
1540 'prefix_chars': self.prefix_chars}
1541 msg = _('invalid option string %(option)r: '
1542 'must start with a character %(prefix_chars)r')
1543 raise ValueError(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001544
1545 # strings starting with two prefix characters are long options
1546 option_strings.append(option_string)
Shashank Parekhb9600b02019-06-21 08:32:22 +05301547 if len(option_string) > 1 and option_string[1] in self.prefix_chars:
1548 long_option_strings.append(option_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001549
1550 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1551 dest = kwargs.pop('dest', None)
1552 if dest is None:
1553 if long_option_strings:
1554 dest_option_string = long_option_strings[0]
1555 else:
1556 dest_option_string = option_strings[0]
1557 dest = dest_option_string.lstrip(self.prefix_chars)
1558 if not dest:
1559 msg = _('dest= is required for options like %r')
1560 raise ValueError(msg % option_string)
1561 dest = dest.replace('-', '_')
1562
1563 # return the updated keyword arguments
1564 return dict(kwargs, dest=dest, option_strings=option_strings)
1565
1566 def _pop_action_class(self, kwargs, default=None):
1567 action = kwargs.pop('action', default)
1568 return self._registry_get('action', action, action)
1569
1570 def _get_handler(self):
1571 # determine function from conflict handler string
1572 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1573 try:
1574 return getattr(self, handler_func_name)
1575 except AttributeError:
1576 msg = _('invalid conflict_resolution value: %r')
1577 raise ValueError(msg % self.conflict_handler)
1578
1579 def _check_conflict(self, action):
1580
1581 # find all options that conflict with this option
1582 confl_optionals = []
1583 for option_string in action.option_strings:
1584 if option_string in self._option_string_actions:
1585 confl_optional = self._option_string_actions[option_string]
1586 confl_optionals.append((option_string, confl_optional))
1587
1588 # resolve any conflicts
1589 if confl_optionals:
1590 conflict_handler = self._get_handler()
1591 conflict_handler(action, confl_optionals)
1592
1593 def _handle_conflict_error(self, action, conflicting_actions):
Éric Araujo12159152010-12-04 17:31:49 +00001594 message = ngettext('conflicting option string: %s',
1595 'conflicting option strings: %s',
1596 len(conflicting_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001597 conflict_string = ', '.join([option_string
1598 for option_string, action
1599 in conflicting_actions])
1600 raise ArgumentError(action, message % conflict_string)
1601
1602 def _handle_conflict_resolve(self, action, conflicting_actions):
1603
1604 # remove all conflicting options
1605 for option_string, action in conflicting_actions:
1606
1607 # remove the conflicting option
1608 action.option_strings.remove(option_string)
1609 self._option_string_actions.pop(option_string, None)
1610
1611 # if the option now has no option string, remove it from the
1612 # container holding it
1613 if not action.option_strings:
1614 action.container._remove_action(action)
1615
1616
1617class _ArgumentGroup(_ActionsContainer):
1618
1619 def __init__(self, container, title=None, description=None, **kwargs):
1620 # add any missing keyword arguments by checking the container
1621 update = kwargs.setdefault
1622 update('conflict_handler', container.conflict_handler)
1623 update('prefix_chars', container.prefix_chars)
1624 update('argument_default', container.argument_default)
1625 super_init = super(_ArgumentGroup, self).__init__
1626 super_init(description=description, **kwargs)
1627
1628 # group attributes
1629 self.title = title
1630 self._group_actions = []
1631
1632 # share most attributes with the container
1633 self._registries = container._registries
1634 self._actions = container._actions
1635 self._option_string_actions = container._option_string_actions
1636 self._defaults = container._defaults
1637 self._has_negative_number_optionals = \
1638 container._has_negative_number_optionals
Georg Brandl0f6b47a2011-01-30 12:19:35 +00001639 self._mutually_exclusive_groups = container._mutually_exclusive_groups
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001640
1641 def _add_action(self, action):
1642 action = super(_ArgumentGroup, self)._add_action(action)
1643 self._group_actions.append(action)
1644 return action
1645
1646 def _remove_action(self, action):
1647 super(_ArgumentGroup, self)._remove_action(action)
1648 self._group_actions.remove(action)
1649
1650
1651class _MutuallyExclusiveGroup(_ArgumentGroup):
1652
1653 def __init__(self, container, required=False):
1654 super(_MutuallyExclusiveGroup, self).__init__(container)
1655 self.required = required
1656 self._container = container
1657
1658 def _add_action(self, action):
1659 if action.required:
1660 msg = _('mutually exclusive arguments must be optional')
1661 raise ValueError(msg)
1662 action = self._container._add_action(action)
1663 self._group_actions.append(action)
1664 return action
1665
1666 def _remove_action(self, action):
1667 self._container._remove_action(action)
1668 self._group_actions.remove(action)
1669
1670
1671class ArgumentParser(_AttributeHolder, _ActionsContainer):
1672 """Object for parsing command line strings into Python objects.
1673
1674 Keyword Arguments:
1675 - prog -- The name of the program (default: sys.argv[0])
1676 - usage -- A usage message (default: auto-generated from arguments)
1677 - description -- A description of what the program does
1678 - epilog -- Text following the argument descriptions
1679 - parents -- Parsers whose arguments should be copied into this one
1680 - formatter_class -- HelpFormatter class for printing help messages
1681 - prefix_chars -- Characters that prefix optional arguments
1682 - fromfile_prefix_chars -- Characters that prefix files containing
1683 additional arguments
1684 - argument_default -- The default value for all arguments
1685 - conflict_handler -- String indicating how to handle conflicts
1686 - add_help -- Add a -h/-help option
Berker Peksag8089cd62015-02-14 01:39:17 +02001687 - allow_abbrev -- Allow long options to be abbreviated unambiguously
Hai Shif5456382019-09-12 05:56:05 -05001688 - exit_on_error -- Determines whether or not ArgumentParser exits with
1689 error info when an error occurs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001690 """
1691
1692 def __init__(self,
1693 prog=None,
1694 usage=None,
1695 description=None,
1696 epilog=None,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001697 parents=[],
1698 formatter_class=HelpFormatter,
1699 prefix_chars='-',
1700 fromfile_prefix_chars=None,
1701 argument_default=None,
1702 conflict_handler='error',
Berker Peksag8089cd62015-02-14 01:39:17 +02001703 add_help=True,
Hai Shif5456382019-09-12 05:56:05 -05001704 allow_abbrev=True,
1705 exit_on_error=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001706
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001707 superinit = super(ArgumentParser, self).__init__
1708 superinit(description=description,
1709 prefix_chars=prefix_chars,
1710 argument_default=argument_default,
1711 conflict_handler=conflict_handler)
1712
1713 # default setting for prog
1714 if prog is None:
1715 prog = _os.path.basename(_sys.argv[0])
1716
1717 self.prog = prog
1718 self.usage = usage
1719 self.epilog = epilog
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001720 self.formatter_class = formatter_class
1721 self.fromfile_prefix_chars = fromfile_prefix_chars
1722 self.add_help = add_help
Berker Peksag8089cd62015-02-14 01:39:17 +02001723 self.allow_abbrev = allow_abbrev
Hai Shif5456382019-09-12 05:56:05 -05001724 self.exit_on_error = exit_on_error
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001725
1726 add_group = self.add_argument_group
1727 self._positionals = add_group(_('positional arguments'))
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001728 self._optionals = add_group(_('options'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001729 self._subparsers = None
1730
1731 # register types
1732 def identity(string):
1733 return string
1734 self.register('type', None, identity)
1735
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001736 # add help argument if necessary
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001737 # (using explicit default to override global argument_default)
R. David Murray88c49fe2010-08-03 17:56:09 +00001738 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001739 if self.add_help:
1740 self.add_argument(
R. David Murray88c49fe2010-08-03 17:56:09 +00001741 default_prefix+'h', default_prefix*2+'help',
1742 action='help', default=SUPPRESS,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001743 help=_('show this help message and exit'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001744
1745 # add parent arguments and defaults
1746 for parent in parents:
1747 self._add_container_actions(parent)
1748 try:
1749 defaults = parent._defaults
1750 except AttributeError:
1751 pass
1752 else:
1753 self._defaults.update(defaults)
1754
1755 # =======================
1756 # Pretty __repr__ methods
1757 # =======================
1758 def _get_kwargs(self):
1759 names = [
1760 'prog',
1761 'usage',
1762 'description',
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001763 'formatter_class',
1764 'conflict_handler',
1765 'add_help',
1766 ]
1767 return [(name, getattr(self, name)) for name in names]
1768
1769 # ==================================
1770 # Optional/Positional adding methods
1771 # ==================================
1772 def add_subparsers(self, **kwargs):
1773 if self._subparsers is not None:
1774 self.error(_('cannot have multiple subparser arguments'))
1775
1776 # add the parser class to the arguments if it's not present
1777 kwargs.setdefault('parser_class', type(self))
1778
1779 if 'title' in kwargs or 'description' in kwargs:
1780 title = _(kwargs.pop('title', 'subcommands'))
1781 description = _(kwargs.pop('description', None))
1782 self._subparsers = self.add_argument_group(title, description)
1783 else:
1784 self._subparsers = self._positionals
1785
1786 # prog defaults to the usage message of this parser, skipping
1787 # optional arguments and with no "usage:" prefix
1788 if kwargs.get('prog') is None:
1789 formatter = self._get_formatter()
1790 positionals = self._get_positional_actions()
1791 groups = self._mutually_exclusive_groups
1792 formatter.add_usage(self.usage, positionals, groups, '')
1793 kwargs['prog'] = formatter.format_help().strip()
1794
1795 # create the parsers action and add it to the positionals list
1796 parsers_class = self._pop_action_class(kwargs, 'parsers')
1797 action = parsers_class(option_strings=[], **kwargs)
1798 self._subparsers._add_action(action)
1799
1800 # return the created parsers action
1801 return action
1802
1803 def _add_action(self, action):
1804 if action.option_strings:
1805 self._optionals._add_action(action)
1806 else:
1807 self._positionals._add_action(action)
1808 return action
1809
1810 def _get_optional_actions(self):
1811 return [action
1812 for action in self._actions
1813 if action.option_strings]
1814
1815 def _get_positional_actions(self):
1816 return [action
1817 for action in self._actions
1818 if not action.option_strings]
1819
1820 # =====================================
1821 # Command line argument parsing methods
1822 # =====================================
1823 def parse_args(self, args=None, namespace=None):
1824 args, argv = self.parse_known_args(args, namespace)
1825 if argv:
1826 msg = _('unrecognized arguments: %s')
1827 self.error(msg % ' '.join(argv))
1828 return args
1829
1830 def parse_known_args(self, args=None, namespace=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001831 if args is None:
R David Murrayb5228282012-09-08 12:08:01 -04001832 # args default to the system args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001833 args = _sys.argv[1:]
R David Murrayb5228282012-09-08 12:08:01 -04001834 else:
1835 # make sure that args are mutable
1836 args = list(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001837
1838 # default Namespace built from parser defaults
1839 if namespace is None:
1840 namespace = Namespace()
1841
1842 # add any action defaults that aren't present
1843 for action in self._actions:
1844 if action.dest is not SUPPRESS:
1845 if not hasattr(namespace, action.dest):
1846 if action.default is not SUPPRESS:
R David Murray6fb8fb12012-08-31 22:45:20 -04001847 setattr(namespace, action.dest, action.default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001848
Miss Islington (bot)e4c5a5e2021-11-12 10:44:55 -08001849 # add any parser defaults that aren't present
1850 for dest in self._defaults:
1851 if not hasattr(namespace, dest):
1852 setattr(namespace, dest, self._defaults[dest])
1853
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001854 # parse the arguments and exit if there are any errors
Hai Shif5456382019-09-12 05:56:05 -05001855 if self.exit_on_error:
1856 try:
1857 namespace, args = self._parse_known_args(args, namespace)
1858 except ArgumentError:
1859 err = _sys.exc_info()[1]
1860 self.error(str(err))
1861 else:
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001862 namespace, args = self._parse_known_args(args, namespace)
Hai Shif5456382019-09-12 05:56:05 -05001863
1864 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1865 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1866 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1867 return namespace, args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001868
1869 def _parse_known_args(self, arg_strings, namespace):
1870 # replace arg strings that are file references
1871 if self.fromfile_prefix_chars is not None:
1872 arg_strings = self._read_args_from_files(arg_strings)
1873
1874 # map all mutually exclusive arguments to the other arguments
1875 # they can't occur with
1876 action_conflicts = {}
1877 for mutex_group in self._mutually_exclusive_groups:
1878 group_actions = mutex_group._group_actions
1879 for i, mutex_action in enumerate(mutex_group._group_actions):
1880 conflicts = action_conflicts.setdefault(mutex_action, [])
1881 conflicts.extend(group_actions[:i])
1882 conflicts.extend(group_actions[i + 1:])
1883
1884 # find all option indices, and determine the arg_string_pattern
1885 # which has an 'O' if there is an option at an index,
1886 # an 'A' if there is an argument, or a '-' if there is a '--'
1887 option_string_indices = {}
1888 arg_string_pattern_parts = []
1889 arg_strings_iter = iter(arg_strings)
1890 for i, arg_string in enumerate(arg_strings_iter):
1891
1892 # all args after -- are non-options
1893 if arg_string == '--':
1894 arg_string_pattern_parts.append('-')
1895 for arg_string in arg_strings_iter:
1896 arg_string_pattern_parts.append('A')
1897
1898 # otherwise, add the arg to the arg strings
1899 # and note the index if it was an option
1900 else:
1901 option_tuple = self._parse_optional(arg_string)
1902 if option_tuple is None:
1903 pattern = 'A'
1904 else:
1905 option_string_indices[i] = option_tuple
1906 pattern = 'O'
1907 arg_string_pattern_parts.append(pattern)
1908
1909 # join the pieces together to form the pattern
1910 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1911
1912 # converts arg strings to the appropriate and then takes the action
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00001913 seen_actions = set()
1914 seen_non_default_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001915
1916 def take_action(action, argument_strings, option_string=None):
1917 seen_actions.add(action)
1918 argument_values = self._get_values(action, argument_strings)
1919
1920 # error if this argument is not allowed with other previously
1921 # seen arguments, assuming that actions that use the default
1922 # value don't really count as "present"
1923 if argument_values is not action.default:
1924 seen_non_default_actions.add(action)
1925 for conflict_action in action_conflicts.get(action, []):
1926 if conflict_action in seen_non_default_actions:
1927 msg = _('not allowed with argument %s')
1928 action_name = _get_action_name(conflict_action)
1929 raise ArgumentError(action, msg % action_name)
1930
1931 # take the action if we didn't receive a SUPPRESS value
1932 # (e.g. from a default)
1933 if argument_values is not SUPPRESS:
1934 action(self, namespace, argument_values, option_string)
1935
1936 # function to convert arg_strings into an optional action
1937 def consume_optional(start_index):
1938
1939 # get the optional identified at this index
1940 option_tuple = option_string_indices[start_index]
1941 action, option_string, explicit_arg = option_tuple
1942
1943 # identify additional optionals in the same arg string
1944 # (e.g. -xyz is the same as -x -y -z if no args are required)
1945 match_argument = self._match_argument
1946 action_tuples = []
1947 while True:
1948
1949 # if we found no optional action, skip it
1950 if action is None:
1951 extras.append(arg_strings[start_index])
1952 return start_index + 1
1953
1954 # if there is an explicit argument, try to match the
1955 # optional's string arguments to only this
1956 if explicit_arg is not None:
1957 arg_count = match_argument(action, 'A')
1958
1959 # if the action is a single-dash option and takes no
1960 # arguments, try to parse more single-dash options out
1961 # of the tail of the option string
1962 chars = self.prefix_chars
1963 if arg_count == 0 and option_string[1] not in chars:
1964 action_tuples.append((action, [], option_string))
Steven Bethard1ca45a52010-11-01 15:57:36 +00001965 char = option_string[0]
1966 option_string = char + explicit_arg[0]
1967 new_explicit_arg = explicit_arg[1:] or None
1968 optionals_map = self._option_string_actions
1969 if option_string in optionals_map:
1970 action = optionals_map[option_string]
1971 explicit_arg = new_explicit_arg
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001972 else:
1973 msg = _('ignored explicit argument %r')
1974 raise ArgumentError(action, msg % explicit_arg)
1975
1976 # if the action expect exactly one argument, we've
1977 # successfully matched the option; exit the loop
1978 elif arg_count == 1:
1979 stop = start_index + 1
1980 args = [explicit_arg]
1981 action_tuples.append((action, args, option_string))
1982 break
1983
1984 # error if a double-dash option did not use the
1985 # explicit argument
1986 else:
1987 msg = _('ignored explicit argument %r')
1988 raise ArgumentError(action, msg % explicit_arg)
1989
1990 # if there is no explicit argument, try to match the
1991 # optional's string arguments with the following strings
1992 # if successful, exit the loop
1993 else:
1994 start = start_index + 1
1995 selected_patterns = arg_strings_pattern[start:]
1996 arg_count = match_argument(action, selected_patterns)
1997 stop = start + arg_count
1998 args = arg_strings[start:stop]
1999 action_tuples.append((action, args, option_string))
2000 break
2001
2002 # add the Optional to the list and return the index at which
2003 # the Optional's string args stopped
2004 assert action_tuples
2005 for action, args, option_string in action_tuples:
2006 take_action(action, args, option_string)
2007 return stop
2008
2009 # the list of Positionals left to be parsed; this is modified
2010 # by consume_positionals()
2011 positionals = self._get_positional_actions()
2012
2013 # function to convert arg_strings into positional actions
2014 def consume_positionals(start_index):
2015 # match as many Positionals as possible
2016 match_partial = self._match_arguments_partial
2017 selected_pattern = arg_strings_pattern[start_index:]
2018 arg_counts = match_partial(positionals, selected_pattern)
2019
2020 # slice off the appropriate arg strings for each Positional
2021 # and add the Positional and its args to the list
2022 for action, arg_count in zip(positionals, arg_counts):
2023 args = arg_strings[start_index: start_index + arg_count]
2024 start_index += arg_count
2025 take_action(action, args)
2026
2027 # slice off the Positionals that we just parsed and return the
2028 # index at which the Positionals' string args stopped
2029 positionals[:] = positionals[len(arg_counts):]
2030 return start_index
2031
2032 # consume Positionals and Optionals alternately, until we have
2033 # passed the last option string
2034 extras = []
2035 start_index = 0
2036 if option_string_indices:
2037 max_option_string_index = max(option_string_indices)
2038 else:
2039 max_option_string_index = -1
2040 while start_index <= max_option_string_index:
2041
2042 # consume any Positionals preceding the next option
2043 next_option_string_index = min([
2044 index
2045 for index in option_string_indices
2046 if index >= start_index])
2047 if start_index != next_option_string_index:
2048 positionals_end_index = consume_positionals(start_index)
2049
2050 # only try to parse the next optional if we didn't consume
2051 # the option string during the positionals parsing
2052 if positionals_end_index > start_index:
2053 start_index = positionals_end_index
2054 continue
2055 else:
2056 start_index = positionals_end_index
2057
2058 # if we consumed all the positionals we could and we're not
2059 # at the index of an option string, there were extra arguments
2060 if start_index not in option_string_indices:
2061 strings = arg_strings[start_index:next_option_string_index]
2062 extras.extend(strings)
2063 start_index = next_option_string_index
2064
2065 # consume the next optional and any arguments for it
2066 start_index = consume_optional(start_index)
2067
2068 # consume any positionals following the last Optional
2069 stop_index = consume_positionals(start_index)
2070
2071 # if we didn't consume all the argument strings, there were extras
2072 extras.extend(arg_strings[stop_index:])
2073
R David Murray64b0ef12012-08-31 23:09:34 -04002074 # make sure all required actions were present and also convert
2075 # action defaults which were not given as arguments
2076 required_actions = []
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002077 for action in self._actions:
R David Murray6fb8fb12012-08-31 22:45:20 -04002078 if action not in seen_actions:
2079 if action.required:
R David Murray64b0ef12012-08-31 23:09:34 -04002080 required_actions.append(_get_action_name(action))
R David Murray6fb8fb12012-08-31 22:45:20 -04002081 else:
2082 # Convert action default now instead of doing it before
2083 # parsing arguments to avoid calling convert functions
2084 # twice (which may fail) if the argument was given, but
2085 # only if it was defined already in the namespace
2086 if (action.default is not None and
Barry Warsawd89774e2012-09-12 15:31:38 -04002087 isinstance(action.default, str) and
R David Murray64b0ef12012-08-31 23:09:34 -04002088 hasattr(namespace, action.dest) and
2089 action.default is getattr(namespace, action.dest)):
R David Murray6fb8fb12012-08-31 22:45:20 -04002090 setattr(namespace, action.dest,
2091 self._get_value(action, action.default))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002092
R David Murrayf97c59a2011-06-09 12:34:07 -04002093 if required_actions:
2094 self.error(_('the following arguments are required: %s') %
2095 ', '.join(required_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002096
2097 # make sure all required groups had one option present
2098 for group in self._mutually_exclusive_groups:
2099 if group.required:
2100 for action in group._group_actions:
2101 if action in seen_non_default_actions:
2102 break
2103
2104 # if no actions were used, report the error
2105 else:
2106 names = [_get_action_name(action)
2107 for action in group._group_actions
2108 if action.help is not SUPPRESS]
2109 msg = _('one of the arguments %s is required')
2110 self.error(msg % ' '.join(names))
2111
2112 # return the updated namespace and the extra arguments
2113 return namespace, extras
2114
2115 def _read_args_from_files(self, arg_strings):
2116 # expand arguments referencing files
2117 new_arg_strings = []
2118 for arg_string in arg_strings:
2119
2120 # for regular arguments, just add them back into the list
R David Murrayb94082a2012-07-21 22:20:11 -04002121 if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002122 new_arg_strings.append(arg_string)
2123
2124 # replace arguments referencing files with the file content
2125 else:
2126 try:
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01002127 with open(arg_string[1:]) as args_file:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002128 arg_strings = []
2129 for arg_line in args_file.read().splitlines():
2130 for arg in self.convert_arg_line_to_args(arg_line):
2131 arg_strings.append(arg)
2132 arg_strings = self._read_args_from_files(arg_strings)
2133 new_arg_strings.extend(arg_strings)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002134 except OSError:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002135 err = _sys.exc_info()[1]
2136 self.error(str(err))
2137
2138 # return the modified argument list
2139 return new_arg_strings
2140
2141 def convert_arg_line_to_args(self, arg_line):
2142 return [arg_line]
2143
2144 def _match_argument(self, action, arg_strings_pattern):
2145 # match the pattern for this action to the arg strings
2146 nargs_pattern = self._get_nargs_pattern(action)
2147 match = _re.match(nargs_pattern, arg_strings_pattern)
2148
2149 # raise an exception if we weren't able to find a match
2150 if match is None:
2151 nargs_errors = {
2152 None: _('expected one argument'),
2153 OPTIONAL: _('expected at most one argument'),
2154 ONE_OR_MORE: _('expected at least one argument'),
2155 }
Federico Bondbe5c79e2019-11-20 10:29:29 -03002156 msg = nargs_errors.get(action.nargs)
2157 if msg is None:
2158 msg = ngettext('expected %s argument',
Éric Araujo12159152010-12-04 17:31:49 +00002159 'expected %s arguments',
2160 action.nargs) % action.nargs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002161 raise ArgumentError(action, msg)
2162
2163 # return the number of arguments matched
2164 return len(match.group(1))
2165
2166 def _match_arguments_partial(self, actions, arg_strings_pattern):
2167 # progressively shorten the actions list by slicing off the
2168 # final actions until we find a match
2169 result = []
2170 for i in range(len(actions), 0, -1):
2171 actions_slice = actions[:i]
2172 pattern = ''.join([self._get_nargs_pattern(action)
2173 for action in actions_slice])
2174 match = _re.match(pattern, arg_strings_pattern)
2175 if match is not None:
2176 result.extend([len(string) for string in match.groups()])
2177 break
2178
2179 # return the list of arg string counts
2180 return result
2181
2182 def _parse_optional(self, arg_string):
2183 # if it's an empty string, it was meant to be a positional
2184 if not arg_string:
2185 return None
2186
2187 # if it doesn't start with a prefix, it was meant to be positional
2188 if not arg_string[0] in self.prefix_chars:
2189 return None
2190
2191 # if the option string is present in the parser, return the action
2192 if arg_string in self._option_string_actions:
2193 action = self._option_string_actions[arg_string]
2194 return action, arg_string, None
2195
2196 # if it's just a single character, it was meant to be positional
2197 if len(arg_string) == 1:
2198 return None
2199
2200 # if the option string before the "=" is present, return the action
2201 if '=' in arg_string:
2202 option_string, explicit_arg = arg_string.split('=', 1)
2203 if option_string in self._option_string_actions:
2204 action = self._option_string_actions[option_string]
2205 return action, option_string, explicit_arg
2206
Kyle Meyer8edfc472020-02-18 04:48:57 -05002207 # search through all possible prefixes of the option string
2208 # and all actions in the parser for possible interpretations
2209 option_tuples = self._get_option_tuples(arg_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002210
Kyle Meyer8edfc472020-02-18 04:48:57 -05002211 # if multiple actions match, the option string was ambiguous
2212 if len(option_tuples) > 1:
2213 options = ', '.join([option_string
2214 for action, option_string, explicit_arg in option_tuples])
2215 args = {'option': arg_string, 'matches': options}
2216 msg = _('ambiguous option: %(option)s could match %(matches)s')
2217 self.error(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002218
Kyle Meyer8edfc472020-02-18 04:48:57 -05002219 # if exactly one action matched, this segmentation is good,
2220 # so return the parsed action
2221 elif len(option_tuples) == 1:
2222 option_tuple, = option_tuples
2223 return option_tuple
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002224
2225 # if it was not found as an option, but it looks like a negative
2226 # number, it was meant to be positional
2227 # unless there are negative-number-like options
2228 if self._negative_number_matcher.match(arg_string):
2229 if not self._has_negative_number_optionals:
2230 return None
2231
2232 # if it contains a space, it was meant to be a positional
2233 if ' ' in arg_string:
2234 return None
2235
2236 # it was meant to be an optional but there is no such option
2237 # in this parser (though it might be a valid option in a subparser)
2238 return None, arg_string, None
2239
2240 def _get_option_tuples(self, option_string):
2241 result = []
2242
2243 # option strings starting with two prefix characters are only
2244 # split at the '='
2245 chars = self.prefix_chars
2246 if option_string[0] in chars and option_string[1] in chars:
Kyle Meyer8edfc472020-02-18 04:48:57 -05002247 if self.allow_abbrev:
2248 if '=' in option_string:
2249 option_prefix, explicit_arg = option_string.split('=', 1)
2250 else:
2251 option_prefix = option_string
2252 explicit_arg = None
2253 for option_string in self._option_string_actions:
2254 if option_string.startswith(option_prefix):
2255 action = self._option_string_actions[option_string]
2256 tup = action, option_string, explicit_arg
2257 result.append(tup)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002258
2259 # single character options can be concatenated with their arguments
2260 # but multiple character options always have to have their argument
2261 # separate
2262 elif option_string[0] in chars and option_string[1] not in chars:
2263 option_prefix = option_string
2264 explicit_arg = None
2265 short_option_prefix = option_string[:2]
2266 short_explicit_arg = option_string[2:]
2267
2268 for option_string in self._option_string_actions:
2269 if option_string == short_option_prefix:
2270 action = self._option_string_actions[option_string]
2271 tup = action, option_string, short_explicit_arg
2272 result.append(tup)
2273 elif option_string.startswith(option_prefix):
2274 action = self._option_string_actions[option_string]
2275 tup = action, option_string, explicit_arg
2276 result.append(tup)
2277
2278 # shouldn't ever get here
2279 else:
2280 self.error(_('unexpected option string: %s') % option_string)
2281
2282 # return the collected option tuples
2283 return result
2284
2285 def _get_nargs_pattern(self, action):
2286 # in all examples below, we have to allow for '--' args
2287 # which are represented as '-' in the pattern
2288 nargs = action.nargs
2289
2290 # the default (None) is assumed to be a single argument
2291 if nargs is None:
2292 nargs_pattern = '(-*A-*)'
2293
2294 # allow zero or one arguments
2295 elif nargs == OPTIONAL:
2296 nargs_pattern = '(-*A?-*)'
2297
2298 # allow zero or more arguments
2299 elif nargs == ZERO_OR_MORE:
2300 nargs_pattern = '(-*[A-]*)'
2301
2302 # allow one or more arguments
2303 elif nargs == ONE_OR_MORE:
2304 nargs_pattern = '(-*A[A-]*)'
2305
2306 # allow any number of options or arguments
2307 elif nargs == REMAINDER:
2308 nargs_pattern = '([-AO]*)'
2309
2310 # allow one argument followed by any number of options or arguments
2311 elif nargs == PARSER:
2312 nargs_pattern = '(-*A[-AO]*)'
2313
R. David Murray0f6b9d22017-09-06 20:25:40 -04002314 # suppress action, like nargs=0
2315 elif nargs == SUPPRESS:
2316 nargs_pattern = '(-*-*)'
2317
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002318 # all others should be integers
2319 else:
2320 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2321
2322 # if this is an optional action, -- is not allowed
2323 if action.option_strings:
2324 nargs_pattern = nargs_pattern.replace('-*', '')
2325 nargs_pattern = nargs_pattern.replace('-', '')
2326
2327 # return the pattern
2328 return nargs_pattern
2329
2330 # ========================
R. David Murray0f6b9d22017-09-06 20:25:40 -04002331 # Alt command line argument parsing, allowing free intermix
2332 # ========================
2333
2334 def parse_intermixed_args(self, args=None, namespace=None):
2335 args, argv = self.parse_known_intermixed_args(args, namespace)
2336 if argv:
2337 msg = _('unrecognized arguments: %s')
2338 self.error(msg % ' '.join(argv))
2339 return args
2340
2341 def parse_known_intermixed_args(self, args=None, namespace=None):
2342 # returns a namespace and list of extras
2343 #
2344 # positional can be freely intermixed with optionals. optionals are
2345 # first parsed with all positional arguments deactivated. The 'extras'
2346 # are then parsed. If the parser definition is incompatible with the
2347 # intermixed assumptions (e.g. use of REMAINDER, subparsers) a
2348 # TypeError is raised.
2349 #
2350 # positionals are 'deactivated' by setting nargs and default to
2351 # SUPPRESS. This blocks the addition of that positional to the
2352 # namespace
2353
2354 positionals = self._get_positional_actions()
2355 a = [action for action in positionals
2356 if action.nargs in [PARSER, REMAINDER]]
2357 if a:
2358 raise TypeError('parse_intermixed_args: positional arg'
2359 ' with nargs=%s'%a[0].nargs)
2360
2361 if [action.dest for group in self._mutually_exclusive_groups
2362 for action in group._group_actions if action in positionals]:
2363 raise TypeError('parse_intermixed_args: positional in'
2364 ' mutuallyExclusiveGroup')
2365
2366 try:
2367 save_usage = self.usage
2368 try:
2369 if self.usage is None:
2370 # capture the full usage for use in error messages
2371 self.usage = self.format_usage()[7:]
2372 for action in positionals:
2373 # deactivate positionals
2374 action.save_nargs = action.nargs
2375 # action.nargs = 0
2376 action.nargs = SUPPRESS
2377 action.save_default = action.default
2378 action.default = SUPPRESS
2379 namespace, remaining_args = self.parse_known_args(args,
2380 namespace)
2381 for action in positionals:
2382 # remove the empty positional values from namespace
2383 if (hasattr(namespace, action.dest)
2384 and getattr(namespace, action.dest)==[]):
2385 from warnings import warn
2386 warn('Do not expect %s in %s' % (action.dest, namespace))
2387 delattr(namespace, action.dest)
2388 finally:
2389 # restore nargs and usage before exiting
2390 for action in positionals:
2391 action.nargs = action.save_nargs
2392 action.default = action.save_default
2393 optionals = self._get_optional_actions()
2394 try:
2395 # parse positionals. optionals aren't normally required, but
2396 # they could be, so make sure they aren't.
2397 for action in optionals:
2398 action.save_required = action.required
2399 action.required = False
2400 for group in self._mutually_exclusive_groups:
2401 group.save_required = group.required
2402 group.required = False
2403 namespace, extras = self.parse_known_args(remaining_args,
2404 namespace)
2405 finally:
2406 # restore parser values before exiting
2407 for action in optionals:
2408 action.required = action.save_required
2409 for group in self._mutually_exclusive_groups:
2410 group.required = group.save_required
2411 finally:
2412 self.usage = save_usage
2413 return namespace, extras
2414
2415 # ========================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002416 # Value conversion methods
2417 # ========================
2418 def _get_values(self, action, arg_strings):
R David Murray00528e82012-07-21 22:48:35 -04002419 # for everything but PARSER, REMAINDER args, strip out first '--'
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002420 if action.nargs not in [PARSER, REMAINDER]:
R David Murray00528e82012-07-21 22:48:35 -04002421 try:
2422 arg_strings.remove('--')
2423 except ValueError:
2424 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002425
2426 # optional argument produces a default when not present
2427 if not arg_strings and action.nargs == OPTIONAL:
2428 if action.option_strings:
2429 value = action.const
2430 else:
2431 value = action.default
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00002432 if isinstance(value, str):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002433 value = self._get_value(action, value)
2434 self._check_value(action, value)
2435
2436 # when nargs='*' on a positional, if there were no command-line
2437 # args, use the default if it is anything other than None
2438 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2439 not action.option_strings):
2440 if action.default is not None:
2441 value = action.default
2442 else:
2443 value = arg_strings
2444 self._check_value(action, value)
2445
2446 # single argument or optional argument produces a single value
2447 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2448 arg_string, = arg_strings
2449 value = self._get_value(action, arg_string)
2450 self._check_value(action, value)
2451
2452 # REMAINDER arguments convert all values, checking none
2453 elif action.nargs == REMAINDER:
2454 value = [self._get_value(action, v) for v in arg_strings]
2455
2456 # PARSER arguments convert all values, but check only the first
2457 elif action.nargs == PARSER:
2458 value = [self._get_value(action, v) for v in arg_strings]
2459 self._check_value(action, value[0])
2460
R. David Murray0f6b9d22017-09-06 20:25:40 -04002461 # SUPPRESS argument does not put anything in the namespace
2462 elif action.nargs == SUPPRESS:
2463 value = SUPPRESS
2464
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002465 # all other types of nargs produce a list
2466 else:
2467 value = [self._get_value(action, v) for v in arg_strings]
2468 for v in value:
2469 self._check_value(action, v)
2470
2471 # return the converted value
2472 return value
2473
2474 def _get_value(self, action, arg_string):
2475 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02002476 if not callable(type_func):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002477 msg = _('%r is not callable')
2478 raise ArgumentError(action, msg % type_func)
2479
2480 # convert the value to the appropriate type
2481 try:
2482 result = type_func(arg_string)
2483
2484 # ArgumentTypeErrors indicate errors
2485 except ArgumentTypeError:
2486 name = getattr(action.type, '__name__', repr(action.type))
2487 msg = str(_sys.exc_info()[1])
2488 raise ArgumentError(action, msg)
2489
2490 # TypeErrors or ValueErrors also indicate errors
2491 except (TypeError, ValueError):
2492 name = getattr(action.type, '__name__', repr(action.type))
Éric Araujobb48a8b2010-12-03 19:41:00 +00002493 args = {'type': name, 'value': arg_string}
2494 msg = _('invalid %(type)s value: %(value)r')
2495 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002496
2497 # return the converted value
2498 return result
2499
2500 def _check_value(self, action, value):
2501 # converted value must be one of the choices (if specified)
Vinay Sajip9ae50502016-08-23 08:43:16 +01002502 if action.choices is not None and value not in action.choices:
2503 args = {'value': value,
2504 'choices': ', '.join(map(repr, action.choices))}
2505 msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2506 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002507
2508 # =======================
2509 # Help-formatting methods
2510 # =======================
2511 def format_usage(self):
2512 formatter = self._get_formatter()
2513 formatter.add_usage(self.usage, self._actions,
2514 self._mutually_exclusive_groups)
2515 return formatter.format_help()
2516
2517 def format_help(self):
2518 formatter = self._get_formatter()
2519
2520 # usage
2521 formatter.add_usage(self.usage, self._actions,
2522 self._mutually_exclusive_groups)
2523
2524 # description
2525 formatter.add_text(self.description)
2526
2527 # positionals, optionals and user-defined groups
2528 for action_group in self._action_groups:
2529 formatter.start_section(action_group.title)
2530 formatter.add_text(action_group.description)
2531 formatter.add_arguments(action_group._group_actions)
2532 formatter.end_section()
2533
2534 # epilog
2535 formatter.add_text(self.epilog)
2536
2537 # determine help from format above
2538 return formatter.format_help()
2539
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002540 def _get_formatter(self):
2541 return self.formatter_class(prog=self.prog)
2542
2543 # =====================
2544 # Help-printing methods
2545 # =====================
2546 def print_usage(self, file=None):
2547 if file is None:
2548 file = _sys.stdout
2549 self._print_message(self.format_usage(), file)
2550
2551 def print_help(self, file=None):
2552 if file is None:
2553 file = _sys.stdout
2554 self._print_message(self.format_help(), file)
2555
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002556 def _print_message(self, message, file=None):
2557 if message:
2558 if file is None:
2559 file = _sys.stderr
2560 file.write(message)
2561
2562 # ===============
2563 # Exiting methods
2564 # ===============
2565 def exit(self, status=0, message=None):
2566 if message:
2567 self._print_message(message, _sys.stderr)
2568 _sys.exit(status)
2569
2570 def error(self, message):
2571 """error(message: string)
2572
2573 Prints a usage message incorporating the message to stderr and
2574 exits.
2575
2576 If you override this in a subclass, it should not return -- it
2577 should either exit or raise an exception.
2578 """
2579 self.print_usage(_sys.stderr)
Éric Araujobb48a8b2010-12-03 19:41:00 +00002580 args = {'prog': self.prog, 'message': message}
2581 self.exit(2, _('%(prog)s: error: %(message)s\n') % args)