blob: f1f6f3227bd17fb27d6de3df4ae3659aa0dfb229 [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:
395 try:
396 start = actions.index(group._group_actions[0])
397 except ValueError:
398 continue
399 else:
400 end = start + len(group._group_actions)
401 if actions[start:end] == group._group_actions:
402 for action in group._group_actions:
403 group_actions.add(action)
404 if not group.required:
Steven Bethard49998ee2010-11-01 16:29:26 +0000405 if start in inserts:
406 inserts[start] += ' ['
407 else:
408 inserts[start] = '['
Flavian Hautboisda27d9b2019-08-25 21:06:45 +0200409 if end in inserts:
410 inserts[end] += ']'
411 else:
412 inserts[end] = ']'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000413 else:
Steven Bethard49998ee2010-11-01 16:29:26 +0000414 if start in inserts:
415 inserts[start] += ' ('
416 else:
417 inserts[start] = '('
Flavian Hautboisda27d9b2019-08-25 21:06:45 +0200418 if end in inserts:
419 inserts[end] += ')'
420 else:
421 inserts[end] = ')'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000422 for i in range(start + 1, end):
423 inserts[i] = '|'
424
425 # collect all actions format strings
426 parts = []
427 for i, action in enumerate(actions):
428
429 # suppressed arguments are marked with None
430 # remove | separators for suppressed arguments
431 if action.help is SUPPRESS:
432 parts.append(None)
433 if inserts.get(i) == '|':
434 inserts.pop(i)
435 elif inserts.get(i + 1) == '|':
436 inserts.pop(i + 1)
437
438 # produce all arg strings
439 elif not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100440 default = self._get_default_metavar_for_positional(action)
441 part = self._format_args(action, default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000442
443 # if it's in a group, strip the outer []
444 if action in group_actions:
445 if part[0] == '[' and part[-1] == ']':
446 part = part[1:-1]
447
448 # add the action string to the list
449 parts.append(part)
450
451 # produce the first way to invoke the option in brackets
452 else:
453 option_string = action.option_strings[0]
454
455 # if the Optional doesn't take a value, format is:
456 # -s or --long
457 if action.nargs == 0:
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200458 part = action.format_usage()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000459
460 # if the Optional takes a value, format is:
461 # -s ARGS or --long ARGS
462 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100463 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000464 args_string = self._format_args(action, default)
465 part = '%s %s' % (option_string, args_string)
466
467 # make it look optional if it's not required or in a group
468 if not action.required and action not in group_actions:
469 part = '[%s]' % part
470
471 # add the action string to the list
472 parts.append(part)
473
474 # insert things at the necessary indices
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000475 for i in sorted(inserts, reverse=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000476 parts[i:i] = [inserts[i]]
477
478 # join all the action items with spaces
479 text = ' '.join([item for item in parts if item is not None])
480
481 # clean up separators for mutually exclusive groups
482 open = r'[\[(]'
483 close = r'[\])]'
484 text = _re.sub(r'(%s) ' % open, r'\1', text)
485 text = _re.sub(r' (%s)' % close, r'\1', text)
486 text = _re.sub(r'%s *%s' % (open, close), r'', text)
487 text = _re.sub(r'\(([^|]*)\)', r'\1', text)
488 text = text.strip()
489
490 # return the text
491 return text
492
493 def _format_text(self, text):
494 if '%(prog)' in text:
495 text = text % dict(prog=self._prog)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200496 text_width = max(self._width - self._current_indent, 11)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000497 indent = ' ' * self._current_indent
498 return self._fill_text(text, text_width, indent) + '\n\n'
499
500 def _format_action(self, action):
501 # determine the required width and the entry label
502 help_position = min(self._action_max_length + 2,
503 self._max_help_position)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200504 help_width = max(self._width - help_position, 11)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000505 action_width = help_position - self._current_indent - 2
506 action_header = self._format_action_invocation(action)
507
Georg Brandl2514f522014-10-20 08:36:02 +0200508 # no help; start on same line and add a final newline
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000509 if not action.help:
510 tup = self._current_indent, '', action_header
511 action_header = '%*s%s\n' % tup
512
513 # short action name; start on the same line and pad two spaces
514 elif len(action_header) <= action_width:
515 tup = self._current_indent, '', action_width, action_header
516 action_header = '%*s%-*s ' % tup
517 indent_first = 0
518
519 # long action name; start on the next line
520 else:
521 tup = self._current_indent, '', action_header
522 action_header = '%*s%s\n' % tup
523 indent_first = help_position
524
525 # collect the pieces of the action help
526 parts = [action_header]
527
528 # if there was help for the action, add lines of help text
Miss Islington (bot)fd2be6d2021-10-13 10:15:43 -0700529 if action.help and action.help.strip():
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000530 help_text = self._expand_help(action)
Miss Islington (bot)fd2be6d2021-10-13 10:15:43 -0700531 if help_text:
532 help_lines = self._split_lines(help_text, help_width)
533 parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
534 for line in help_lines[1:]:
535 parts.append('%*s%s\n' % (help_position, '', line))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000536
537 # or add a newline if the description doesn't end with one
538 elif not action_header.endswith('\n'):
539 parts.append('\n')
540
541 # if there are any sub-actions, add their help as well
542 for subaction in self._iter_indented_subactions(action):
543 parts.append(self._format_action(subaction))
544
545 # return a single string
546 return self._join_parts(parts)
547
548 def _format_action_invocation(self, action):
549 if not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100550 default = self._get_default_metavar_for_positional(action)
551 metavar, = self._metavar_formatter(action, default)(1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000552 return metavar
553
554 else:
555 parts = []
556
557 # if the Optional doesn't take a value, format is:
558 # -s, --long
559 if action.nargs == 0:
560 parts.extend(action.option_strings)
561
562 # if the Optional takes a value, format is:
563 # -s ARGS, --long ARGS
564 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100565 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000566 args_string = self._format_args(action, default)
567 for option_string in action.option_strings:
568 parts.append('%s %s' % (option_string, args_string))
569
570 return ', '.join(parts)
571
572 def _metavar_formatter(self, action, default_metavar):
573 if action.metavar is not None:
574 result = action.metavar
575 elif action.choices is not None:
576 choice_strs = [str(choice) for choice in action.choices]
577 result = '{%s}' % ','.join(choice_strs)
578 else:
579 result = default_metavar
580
581 def format(tuple_size):
582 if isinstance(result, tuple):
583 return result
584 else:
585 return (result, ) * tuple_size
586 return format
587
588 def _format_args(self, action, default_metavar):
589 get_metavar = self._metavar_formatter(action, default_metavar)
590 if action.nargs is None:
591 result = '%s' % get_metavar(1)
592 elif action.nargs == OPTIONAL:
593 result = '[%s]' % get_metavar(1)
594 elif action.nargs == ZERO_OR_MORE:
Brandt Buchera0ed99b2019-11-11 12:47:48 -0800595 metavar = get_metavar(1)
596 if len(metavar) == 2:
597 result = '[%s [%s ...]]' % metavar
598 else:
599 result = '[%s ...]' % metavar
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000600 elif action.nargs == ONE_OR_MORE:
601 result = '%s [%s ...]' % get_metavar(2)
602 elif action.nargs == REMAINDER:
603 result = '...'
604 elif action.nargs == PARSER:
605 result = '%s ...' % get_metavar(1)
R. David Murray0f6b9d22017-09-06 20:25:40 -0400606 elif action.nargs == SUPPRESS:
607 result = ''
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000608 else:
tmblweed4b3e9752019-08-01 21:57:13 -0700609 try:
610 formats = ['%s' for _ in range(action.nargs)]
611 except TypeError:
612 raise ValueError("invalid nargs value") from None
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000613 result = ' '.join(formats) % get_metavar(action.nargs)
614 return result
615
616 def _expand_help(self, action):
617 params = dict(vars(action), prog=self._prog)
618 for name in list(params):
619 if params[name] is SUPPRESS:
620 del params[name]
621 for name in list(params):
622 if hasattr(params[name], '__name__'):
623 params[name] = params[name].__name__
624 if params.get('choices') is not None:
625 choices_str = ', '.join([str(c) for c in params['choices']])
626 params['choices'] = choices_str
627 return self._get_help_string(action) % params
628
629 def _iter_indented_subactions(self, action):
630 try:
631 get_subactions = action._get_subactions
632 except AttributeError:
633 pass
634 else:
635 self._indent()
Philip Jenvey4993cc02012-10-01 12:53:43 -0700636 yield from get_subactions()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000637 self._dedent()
638
639 def _split_lines(self, text, width):
640 text = self._whitespace_matcher.sub(' ', text).strip()
Serhiy Storchaka81108372017-09-26 00:55:55 +0300641 # The textwrap module is used only for formatting help.
642 # Delay its import for speeding up the common usage of argparse.
643 import textwrap
644 return textwrap.wrap(text, width)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000645
646 def _fill_text(self, text, width, indent):
647 text = self._whitespace_matcher.sub(' ', text).strip()
Serhiy Storchaka81108372017-09-26 00:55:55 +0300648 import textwrap
649 return textwrap.fill(text, width,
650 initial_indent=indent,
651 subsequent_indent=indent)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000652
653 def _get_help_string(self, action):
654 return action.help
655
Steven Bethard0331e902011-03-26 14:48:04 +0100656 def _get_default_metavar_for_optional(self, action):
657 return action.dest.upper()
658
659 def _get_default_metavar_for_positional(self, action):
660 return action.dest
661
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000662
663class RawDescriptionHelpFormatter(HelpFormatter):
664 """Help message formatter which retains any formatting in descriptions.
665
666 Only the name of this class is considered a public API. All the methods
667 provided by the class are considered an implementation detail.
668 """
669
670 def _fill_text(self, text, width, indent):
Ezio Melottid8b509b2011-09-28 17:37:55 +0300671 return ''.join(indent + line for line in text.splitlines(keepends=True))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000672
673
674class RawTextHelpFormatter(RawDescriptionHelpFormatter):
675 """Help message formatter which retains formatting of all help text.
676
677 Only the name of this class is considered a public API. All the methods
678 provided by the class are considered an implementation detail.
679 """
680
681 def _split_lines(self, text, width):
682 return text.splitlines()
683
684
685class ArgumentDefaultsHelpFormatter(HelpFormatter):
686 """Help message formatter which adds default values to argument help.
687
688 Only the name of this class is considered a public API. All the methods
689 provided by the class are considered an implementation detail.
690 """
691
692 def _get_help_string(self, action):
693 help = action.help
694 if '%(default)' not in action.help:
695 if action.default is not SUPPRESS:
696 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
697 if action.option_strings or action.nargs in defaulting_nargs:
698 help += ' (default: %(default)s)'
699 return help
700
701
Steven Bethard0331e902011-03-26 14:48:04 +0100702class MetavarTypeHelpFormatter(HelpFormatter):
703 """Help message formatter which uses the argument 'type' as the default
704 metavar value (instead of the argument 'dest')
705
706 Only the name of this class is considered a public API. All the methods
707 provided by the class are considered an implementation detail.
708 """
709
710 def _get_default_metavar_for_optional(self, action):
711 return action.type.__name__
712
713 def _get_default_metavar_for_positional(self, action):
714 return action.type.__name__
715
716
717
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000718# =====================
719# Options and Arguments
720# =====================
721
722def _get_action_name(argument):
723 if argument is None:
724 return None
725 elif argument.option_strings:
726 return '/'.join(argument.option_strings)
727 elif argument.metavar not in (None, SUPPRESS):
728 return argument.metavar
729 elif argument.dest not in (None, SUPPRESS):
730 return argument.dest
Miss Islington (bot)c5899922021-07-23 06:27:05 -0700731 elif argument.choices:
732 return '{' + ','.join(argument.choices) + '}'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000733 else:
734 return None
735
736
737class ArgumentError(Exception):
738 """An error from creating or using an argument (optional or positional).
739
740 The string value of this exception is the message, augmented with
741 information about the argument that caused it.
742 """
743
744 def __init__(self, argument, message):
745 self.argument_name = _get_action_name(argument)
746 self.message = message
747
748 def __str__(self):
749 if self.argument_name is None:
750 format = '%(message)s'
751 else:
752 format = 'argument %(argument_name)s: %(message)s'
753 return format % dict(message=self.message,
754 argument_name=self.argument_name)
755
756
757class ArgumentTypeError(Exception):
758 """An error from trying to convert a command line string to a type."""
759 pass
760
761
762# ==============
763# Action classes
764# ==============
765
766class Action(_AttributeHolder):
767 """Information about how to convert command line strings to Python objects.
768
769 Action objects are used by an ArgumentParser to represent the information
770 needed to parse a single argument from one or more strings from the
771 command line. The keyword arguments to the Action constructor are also
772 all attributes of Action instances.
773
774 Keyword Arguments:
775
776 - option_strings -- A list of command-line option strings which
777 should be associated with this action.
778
779 - dest -- The name of the attribute to hold the created object(s)
780
781 - nargs -- The number of command-line arguments that should be
782 consumed. By default, one argument will be consumed and a single
783 value will be produced. Other values include:
784 - N (an integer) consumes N arguments (and produces a list)
785 - '?' consumes zero or one arguments
786 - '*' consumes zero or more arguments (and produces a list)
787 - '+' consumes one or more arguments (and produces a list)
788 Note that the difference between the default and nargs=1 is that
789 with the default, a single value will be produced, while with
790 nargs=1, a list containing a single value will be produced.
791
792 - const -- The value to be produced if the option is specified and the
793 option uses an action that takes no values.
794
795 - default -- The value to be produced if the option is not specified.
796
R David Murray15cd9a02012-07-21 17:04:25 -0400797 - type -- A callable that accepts a single string argument, and
798 returns the converted value. The standard Python types str, int,
799 float, and complex are useful examples of such callables. If None,
800 str is used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000801
802 - choices -- A container of values that should be allowed. If not None,
803 after a command-line argument has been converted to the appropriate
804 type, an exception will be raised if it is not a member of this
805 collection.
806
807 - required -- True if the action must always be specified at the
808 command line. This is only meaningful for optional command-line
809 arguments.
810
811 - help -- The help string describing the argument.
812
813 - metavar -- The name to be used for the option's argument with the
814 help string. If None, the 'dest' value will be used as the name.
815 """
816
817 def __init__(self,
818 option_strings,
819 dest,
820 nargs=None,
821 const=None,
822 default=None,
823 type=None,
824 choices=None,
825 required=False,
826 help=None,
827 metavar=None):
828 self.option_strings = option_strings
829 self.dest = dest
830 self.nargs = nargs
831 self.const = const
832 self.default = default
833 self.type = type
834 self.choices = choices
835 self.required = required
836 self.help = help
837 self.metavar = metavar
838
839 def _get_kwargs(self):
840 names = [
841 'option_strings',
842 'dest',
843 'nargs',
844 'const',
845 'default',
846 'type',
847 'choices',
848 'help',
849 'metavar',
850 ]
851 return [(name, getattr(self, name)) for name in names]
852
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200853 def format_usage(self):
854 return self.option_strings[0]
855
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000856 def __call__(self, parser, namespace, values, option_string=None):
857 raise NotImplementedError(_('.__call__() not defined'))
858
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200859class BooleanOptionalAction(Action):
860 def __init__(self,
861 option_strings,
862 dest,
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200863 default=None,
864 type=None,
865 choices=None,
866 required=False,
867 help=None,
868 metavar=None):
869
870 _option_strings = []
871 for option_string in option_strings:
872 _option_strings.append(option_string)
873
874 if option_string.startswith('--'):
875 option_string = '--no-' + option_string[2:]
876 _option_strings.append(option_string)
877
878 if help is not None and default is not None:
Miss Islington (bot)6f6648e2021-08-17 02:40:41 -0700879 help += " (default: %(default)s)"
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200880
881 super().__init__(
882 option_strings=_option_strings,
883 dest=dest,
884 nargs=0,
885 default=default,
886 type=type,
887 choices=choices,
888 required=required,
889 help=help,
890 metavar=metavar)
891
892 def __call__(self, parser, namespace, values, option_string=None):
893 if option_string in self.option_strings:
894 setattr(namespace, self.dest, not option_string.startswith('--no-'))
895
896 def format_usage(self):
897 return ' | '.join(self.option_strings)
898
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000899
900class _StoreAction(Action):
901
902 def __init__(self,
903 option_strings,
904 dest,
905 nargs=None,
906 const=None,
907 default=None,
908 type=None,
909 choices=None,
910 required=False,
911 help=None,
912 metavar=None):
913 if nargs == 0:
tmblweed4b3e9752019-08-01 21:57:13 -0700914 raise ValueError('nargs for store actions must be != 0; if you '
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000915 'have nothing to store, actions such as store '
916 'true or store const may be more appropriate')
917 if const is not None and nargs != OPTIONAL:
918 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
919 super(_StoreAction, self).__init__(
920 option_strings=option_strings,
921 dest=dest,
922 nargs=nargs,
923 const=const,
924 default=default,
925 type=type,
926 choices=choices,
927 required=required,
928 help=help,
929 metavar=metavar)
930
931 def __call__(self, parser, namespace, values, option_string=None):
932 setattr(namespace, self.dest, values)
933
934
935class _StoreConstAction(Action):
936
937 def __init__(self,
938 option_strings,
939 dest,
940 const,
941 default=None,
942 required=False,
943 help=None,
944 metavar=None):
945 super(_StoreConstAction, self).__init__(
946 option_strings=option_strings,
947 dest=dest,
948 nargs=0,
949 const=const,
950 default=default,
951 required=required,
952 help=help)
953
954 def __call__(self, parser, namespace, values, option_string=None):
955 setattr(namespace, self.dest, self.const)
956
957
958class _StoreTrueAction(_StoreConstAction):
959
960 def __init__(self,
961 option_strings,
962 dest,
963 default=False,
964 required=False,
965 help=None):
966 super(_StoreTrueAction, self).__init__(
967 option_strings=option_strings,
968 dest=dest,
969 const=True,
970 default=default,
971 required=required,
972 help=help)
973
974
975class _StoreFalseAction(_StoreConstAction):
976
977 def __init__(self,
978 option_strings,
979 dest,
980 default=True,
981 required=False,
982 help=None):
983 super(_StoreFalseAction, self).__init__(
984 option_strings=option_strings,
985 dest=dest,
986 const=False,
987 default=default,
988 required=required,
989 help=help)
990
991
992class _AppendAction(Action):
993
994 def __init__(self,
995 option_strings,
996 dest,
997 nargs=None,
998 const=None,
999 default=None,
1000 type=None,
1001 choices=None,
1002 required=False,
1003 help=None,
1004 metavar=None):
1005 if nargs == 0:
tmblweed4b3e9752019-08-01 21:57:13 -07001006 raise ValueError('nargs for append actions must be != 0; if arg '
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001007 'strings are not supplying the value to append, '
1008 'the append const action may be more appropriate')
1009 if const is not None and nargs != OPTIONAL:
1010 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
1011 super(_AppendAction, self).__init__(
1012 option_strings=option_strings,
1013 dest=dest,
1014 nargs=nargs,
1015 const=const,
1016 default=default,
1017 type=type,
1018 choices=choices,
1019 required=required,
1020 help=help,
1021 metavar=metavar)
1022
1023 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001024 items = getattr(namespace, self.dest, None)
1025 items = _copy_items(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001026 items.append(values)
1027 setattr(namespace, self.dest, items)
1028
1029
1030class _AppendConstAction(Action):
1031
1032 def __init__(self,
1033 option_strings,
1034 dest,
1035 const,
1036 default=None,
1037 required=False,
1038 help=None,
1039 metavar=None):
1040 super(_AppendConstAction, self).__init__(
1041 option_strings=option_strings,
1042 dest=dest,
1043 nargs=0,
1044 const=const,
1045 default=default,
1046 required=required,
1047 help=help,
1048 metavar=metavar)
1049
1050 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001051 items = getattr(namespace, self.dest, None)
1052 items = _copy_items(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001053 items.append(self.const)
1054 setattr(namespace, self.dest, items)
1055
1056
1057class _CountAction(Action):
1058
1059 def __init__(self,
1060 option_strings,
1061 dest,
1062 default=None,
1063 required=False,
1064 help=None):
1065 super(_CountAction, self).__init__(
1066 option_strings=option_strings,
1067 dest=dest,
1068 nargs=0,
1069 default=default,
1070 required=required,
1071 help=help)
1072
1073 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001074 count = getattr(namespace, self.dest, None)
1075 if count is None:
1076 count = 0
1077 setattr(namespace, self.dest, count + 1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001078
1079
1080class _HelpAction(Action):
1081
1082 def __init__(self,
1083 option_strings,
1084 dest=SUPPRESS,
1085 default=SUPPRESS,
1086 help=None):
1087 super(_HelpAction, self).__init__(
1088 option_strings=option_strings,
1089 dest=dest,
1090 default=default,
1091 nargs=0,
1092 help=help)
1093
1094 def __call__(self, parser, namespace, values, option_string=None):
1095 parser.print_help()
1096 parser.exit()
1097
1098
1099class _VersionAction(Action):
1100
1101 def __init__(self,
1102 option_strings,
1103 version=None,
1104 dest=SUPPRESS,
1105 default=SUPPRESS,
Steven Bethard50fe5932010-05-24 03:47:38 +00001106 help="show program's version number and exit"):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001107 super(_VersionAction, self).__init__(
1108 option_strings=option_strings,
1109 dest=dest,
1110 default=default,
1111 nargs=0,
1112 help=help)
1113 self.version = version
1114
1115 def __call__(self, parser, namespace, values, option_string=None):
1116 version = self.version
1117 if version is None:
1118 version = parser.version
1119 formatter = parser._get_formatter()
1120 formatter.add_text(version)
Eli Benderskycdac5512013-09-06 06:49:15 -07001121 parser._print_message(formatter.format_help(), _sys.stdout)
1122 parser.exit()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001123
1124
1125class _SubParsersAction(Action):
1126
1127 class _ChoicesPseudoAction(Action):
1128
Steven Bethardfd311a72010-12-18 11:19:23 +00001129 def __init__(self, name, aliases, help):
1130 metavar = dest = name
1131 if aliases:
1132 metavar += ' (%s)' % ', '.join(aliases)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001133 sup = super(_SubParsersAction._ChoicesPseudoAction, self)
Steven Bethardfd311a72010-12-18 11:19:23 +00001134 sup.__init__(option_strings=[], dest=dest, help=help,
1135 metavar=metavar)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001136
1137 def __init__(self,
1138 option_strings,
1139 prog,
1140 parser_class,
1141 dest=SUPPRESS,
Ned Deily8ebf5ce2018-05-23 21:55:15 -04001142 required=False,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001143 help=None,
1144 metavar=None):
1145
1146 self._prog_prefix = prog
1147 self._parser_class = parser_class
Raymond Hettinger05565ed2018-01-11 22:20:33 -08001148 self._name_parser_map = {}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001149 self._choices_actions = []
1150
1151 super(_SubParsersAction, self).__init__(
1152 option_strings=option_strings,
1153 dest=dest,
1154 nargs=PARSER,
1155 choices=self._name_parser_map,
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001156 required=required,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001157 help=help,
1158 metavar=metavar)
1159
1160 def add_parser(self, name, **kwargs):
1161 # set prog from the existing prefix
1162 if kwargs.get('prog') is None:
1163 kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1164
Steven Bethardfd311a72010-12-18 11:19:23 +00001165 aliases = kwargs.pop('aliases', ())
1166
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001167 # create a pseudo-action to hold the choice help
1168 if 'help' in kwargs:
1169 help = kwargs.pop('help')
Steven Bethardfd311a72010-12-18 11:19:23 +00001170 choice_action = self._ChoicesPseudoAction(name, aliases, help)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001171 self._choices_actions.append(choice_action)
1172
1173 # create the parser and add it to the map
1174 parser = self._parser_class(**kwargs)
1175 self._name_parser_map[name] = parser
Steven Bethardfd311a72010-12-18 11:19:23 +00001176
1177 # make parser available under aliases also
1178 for alias in aliases:
1179 self._name_parser_map[alias] = parser
1180
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001181 return parser
1182
1183 def _get_subactions(self):
1184 return self._choices_actions
1185
1186 def __call__(self, parser, namespace, values, option_string=None):
1187 parser_name = values[0]
1188 arg_strings = values[1:]
1189
1190 # set the parser name if requested
1191 if self.dest is not SUPPRESS:
1192 setattr(namespace, self.dest, parser_name)
1193
1194 # select the parser
1195 try:
1196 parser = self._name_parser_map[parser_name]
1197 except KeyError:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001198 args = {'parser_name': parser_name,
1199 'choices': ', '.join(self._name_parser_map)}
1200 msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001201 raise ArgumentError(self, msg)
1202
1203 # parse all the remaining options into the namespace
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001204 # store any unrecognized options on the object, so that the top
1205 # level parser can decide what to do with them
R David Murray7570cbd2014-10-17 19:55:11 -04001206
1207 # In case this subparser defines new defaults, we parse them
1208 # in a new namespace object and then update the original
1209 # namespace for the relevant parts.
1210 subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
1211 for key, value in vars(subnamespace).items():
Miss Islington (bot)6e4101a2021-09-17 23:47:16 -07001212 if not hasattr(namespace, key):
1213 setattr(namespace, key, value)
R David Murray7570cbd2014-10-17 19:55:11 -04001214
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001215 if arg_strings:
1216 vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1217 getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001218
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001219class _ExtendAction(_AppendAction):
1220 def __call__(self, parser, namespace, values, option_string=None):
1221 items = getattr(namespace, self.dest, None)
1222 items = _copy_items(items)
1223 items.extend(values)
1224 setattr(namespace, self.dest, items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001225
1226# ==============
1227# Type classes
1228# ==============
1229
1230class FileType(object):
1231 """Factory for creating file object types
1232
1233 Instances of FileType are typically passed as type= arguments to the
1234 ArgumentParser add_argument() method.
1235
1236 Keyword Arguments:
1237 - mode -- A string indicating how the file is to be opened. Accepts the
1238 same values as the builtin open() function.
1239 - bufsize -- The file's desired buffer size. Accepts the same values as
1240 the builtin open() function.
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001241 - encoding -- The file's encoding. Accepts the same values as the
Terry Jan Reedy8e7586b2013-03-11 18:38:13 -04001242 builtin open() function.
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001243 - errors -- A string indicating how encoding and decoding errors are to
1244 be handled. Accepts the same value as the builtin open() function.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001245 """
1246
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001247 def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001248 self._mode = mode
1249 self._bufsize = bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001250 self._encoding = encoding
1251 self._errors = errors
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001252
1253 def __call__(self, string):
1254 # the special argument "-" means sys.std{in,out}
1255 if string == '-':
1256 if 'r' in self._mode:
1257 return _sys.stdin
1258 elif 'w' in self._mode:
1259 return _sys.stdout
1260 else:
Éric Araujoa9c7a8f2010-12-03 19:19:17 +00001261 msg = _('argument "-" with mode %r') % self._mode
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001262 raise ValueError(msg)
1263
1264 # all other arguments are used as file names
Steven Bethardb0270112011-01-24 21:02:50 +00001265 try:
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001266 return open(string, self._mode, self._bufsize, self._encoding,
1267 self._errors)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001268 except OSError as e:
Jakub Kulík42671ae2019-09-13 11:25:32 +02001269 args = {'filename': string, 'error': e}
1270 message = _("can't open '%(filename)s': %(error)s")
1271 raise ArgumentTypeError(message % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001272
1273 def __repr__(self):
Steven Bethardb0270112011-01-24 21:02:50 +00001274 args = self._mode, self._bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001275 kwargs = [('encoding', self._encoding), ('errors', self._errors)]
1276 args_str = ', '.join([repr(arg) for arg in args if arg != -1] +
1277 ['%s=%r' % (kw, arg) for kw, arg in kwargs
1278 if arg is not None])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001279 return '%s(%s)' % (type(self).__name__, args_str)
1280
1281# ===========================
1282# Optional and Positional Parsing
1283# ===========================
1284
1285class Namespace(_AttributeHolder):
1286 """Simple object for storing attributes.
1287
1288 Implements equality by attribute names and values, and provides a simple
1289 string representation.
1290 """
1291
1292 def __init__(self, **kwargs):
1293 for name in kwargs:
1294 setattr(self, name, kwargs[name])
1295
1296 def __eq__(self, other):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07001297 if not isinstance(other, Namespace):
1298 return NotImplemented
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001299 return vars(self) == vars(other)
1300
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001301 def __contains__(self, key):
1302 return key in self.__dict__
1303
1304
1305class _ActionsContainer(object):
1306
1307 def __init__(self,
1308 description,
1309 prefix_chars,
1310 argument_default,
1311 conflict_handler):
1312 super(_ActionsContainer, self).__init__()
1313
1314 self.description = description
1315 self.argument_default = argument_default
1316 self.prefix_chars = prefix_chars
1317 self.conflict_handler = conflict_handler
1318
1319 # set up registries
1320 self._registries = {}
1321
1322 # register actions
1323 self.register('action', None, _StoreAction)
1324 self.register('action', 'store', _StoreAction)
1325 self.register('action', 'store_const', _StoreConstAction)
1326 self.register('action', 'store_true', _StoreTrueAction)
1327 self.register('action', 'store_false', _StoreFalseAction)
1328 self.register('action', 'append', _AppendAction)
1329 self.register('action', 'append_const', _AppendConstAction)
1330 self.register('action', 'count', _CountAction)
1331 self.register('action', 'help', _HelpAction)
1332 self.register('action', 'version', _VersionAction)
1333 self.register('action', 'parsers', _SubParsersAction)
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001334 self.register('action', 'extend', _ExtendAction)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001335
1336 # raise an exception if the conflict handler is invalid
1337 self._get_handler()
1338
1339 # action storage
1340 self._actions = []
1341 self._option_string_actions = {}
1342
1343 # groups
1344 self._action_groups = []
1345 self._mutually_exclusive_groups = []
1346
1347 # defaults storage
1348 self._defaults = {}
1349
1350 # determines whether an "option" looks like a negative number
1351 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1352
1353 # whether or not there are any optionals that look like negative
1354 # numbers -- uses a list so it can be shared and edited
1355 self._has_negative_number_optionals = []
1356
1357 # ====================
1358 # Registration methods
1359 # ====================
1360 def register(self, registry_name, value, object):
1361 registry = self._registries.setdefault(registry_name, {})
1362 registry[value] = object
1363
1364 def _registry_get(self, registry_name, value, default=None):
1365 return self._registries[registry_name].get(value, default)
1366
1367 # ==================================
1368 # Namespace default accessor methods
1369 # ==================================
1370 def set_defaults(self, **kwargs):
1371 self._defaults.update(kwargs)
1372
1373 # if these defaults match any existing arguments, replace
1374 # the previous default on the object with the new one
1375 for action in self._actions:
1376 if action.dest in kwargs:
1377 action.default = kwargs[action.dest]
1378
1379 def get_default(self, dest):
1380 for action in self._actions:
1381 if action.dest == dest and action.default is not None:
1382 return action.default
1383 return self._defaults.get(dest, None)
1384
1385
1386 # =======================
1387 # Adding argument actions
1388 # =======================
1389 def add_argument(self, *args, **kwargs):
1390 """
1391 add_argument(dest, ..., name=value, ...)
1392 add_argument(option_string, option_string, ..., name=value, ...)
1393 """
1394
1395 # if no positional args are supplied or only one is supplied and
1396 # it doesn't look like an option string, parse a positional
1397 # argument
1398 chars = self.prefix_chars
1399 if not args or len(args) == 1 and args[0][0] not in chars:
1400 if args and 'dest' in kwargs:
1401 raise ValueError('dest supplied twice for positional argument')
1402 kwargs = self._get_positional_kwargs(*args, **kwargs)
1403
1404 # otherwise, we're adding an optional argument
1405 else:
1406 kwargs = self._get_optional_kwargs(*args, **kwargs)
1407
1408 # if no default was supplied, use the parser-level default
1409 if 'default' not in kwargs:
1410 dest = kwargs['dest']
1411 if dest in self._defaults:
1412 kwargs['default'] = self._defaults[dest]
1413 elif self.argument_default is not None:
1414 kwargs['default'] = self.argument_default
1415
1416 # create the action object, and add it to the parser
1417 action_class = self._pop_action_class(kwargs)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001418 if not callable(action_class):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001419 raise ValueError('unknown action "%s"' % (action_class,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001420 action = action_class(**kwargs)
1421
1422 # raise an error if the action type is not callable
1423 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001424 if not callable(type_func):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001425 raise ValueError('%r is not callable' % (type_func,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001426
zygocephalus03d58312019-06-07 23:08:36 +03001427 if type_func is FileType:
1428 raise ValueError('%r is a FileType class object, instance of it'
1429 ' must be passed' % (type_func,))
1430
Steven Bethard8d9a4622011-03-26 17:33:56 +01001431 # raise an error if the metavar does not match the type
1432 if hasattr(self, "_get_formatter"):
1433 try:
1434 self._get_formatter()._format_args(action, None)
1435 except TypeError:
1436 raise ValueError("length of metavar tuple does not match nargs")
1437
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001438 return self._add_action(action)
1439
1440 def add_argument_group(self, *args, **kwargs):
1441 group = _ArgumentGroup(self, *args, **kwargs)
1442 self._action_groups.append(group)
1443 return group
1444
1445 def add_mutually_exclusive_group(self, **kwargs):
1446 group = _MutuallyExclusiveGroup(self, **kwargs)
1447 self._mutually_exclusive_groups.append(group)
1448 return group
1449
1450 def _add_action(self, action):
1451 # resolve any conflicts
1452 self._check_conflict(action)
1453
1454 # add to actions list
1455 self._actions.append(action)
1456 action.container = self
1457
1458 # index the action by any option strings it has
1459 for option_string in action.option_strings:
1460 self._option_string_actions[option_string] = action
1461
1462 # set the flag if any option strings look like negative numbers
1463 for option_string in action.option_strings:
1464 if self._negative_number_matcher.match(option_string):
1465 if not self._has_negative_number_optionals:
1466 self._has_negative_number_optionals.append(True)
1467
1468 # return the created action
1469 return action
1470
1471 def _remove_action(self, action):
1472 self._actions.remove(action)
1473
1474 def _add_container_actions(self, container):
1475 # collect groups by titles
1476 title_group_map = {}
1477 for group in self._action_groups:
1478 if group.title in title_group_map:
1479 msg = _('cannot merge actions - two groups are named %r')
1480 raise ValueError(msg % (group.title))
1481 title_group_map[group.title] = group
1482
1483 # map each action to its group
1484 group_map = {}
1485 for group in container._action_groups:
1486
1487 # if a group with the title exists, use that, otherwise
1488 # create a new group matching the container's group
1489 if group.title not in title_group_map:
1490 title_group_map[group.title] = self.add_argument_group(
1491 title=group.title,
1492 description=group.description,
1493 conflict_handler=group.conflict_handler)
1494
1495 # map the actions to their new group
1496 for action in group._group_actions:
1497 group_map[action] = title_group_map[group.title]
1498
1499 # add container's mutually exclusive groups
1500 # NOTE: if add_mutually_exclusive_group ever gains title= and
1501 # description= then this code will need to be expanded as above
1502 for group in container._mutually_exclusive_groups:
1503 mutex_group = self.add_mutually_exclusive_group(
1504 required=group.required)
1505
1506 # map the actions to their new mutex group
1507 for action in group._group_actions:
1508 group_map[action] = mutex_group
1509
1510 # add all actions to this container or their group
1511 for action in container._actions:
1512 group_map.get(action, self)._add_action(action)
1513
1514 def _get_positional_kwargs(self, dest, **kwargs):
1515 # make sure required is not specified
1516 if 'required' in kwargs:
1517 msg = _("'required' is an invalid argument for positionals")
1518 raise TypeError(msg)
1519
1520 # mark positional arguments as required if at least one is
1521 # always required
1522 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1523 kwargs['required'] = True
1524 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1525 kwargs['required'] = True
1526
1527 # return the keyword arguments with no option strings
1528 return dict(kwargs, dest=dest, option_strings=[])
1529
1530 def _get_optional_kwargs(self, *args, **kwargs):
1531 # determine short and long option strings
1532 option_strings = []
1533 long_option_strings = []
1534 for option_string in args:
1535 # error on strings that don't start with an appropriate prefix
1536 if not option_string[0] in self.prefix_chars:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001537 args = {'option': option_string,
1538 'prefix_chars': self.prefix_chars}
1539 msg = _('invalid option string %(option)r: '
1540 'must start with a character %(prefix_chars)r')
1541 raise ValueError(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001542
1543 # strings starting with two prefix characters are long options
1544 option_strings.append(option_string)
Shashank Parekhb9600b02019-06-21 08:32:22 +05301545 if len(option_string) > 1 and option_string[1] in self.prefix_chars:
1546 long_option_strings.append(option_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001547
1548 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1549 dest = kwargs.pop('dest', None)
1550 if dest is None:
1551 if long_option_strings:
1552 dest_option_string = long_option_strings[0]
1553 else:
1554 dest_option_string = option_strings[0]
1555 dest = dest_option_string.lstrip(self.prefix_chars)
1556 if not dest:
1557 msg = _('dest= is required for options like %r')
1558 raise ValueError(msg % option_string)
1559 dest = dest.replace('-', '_')
1560
1561 # return the updated keyword arguments
1562 return dict(kwargs, dest=dest, option_strings=option_strings)
1563
1564 def _pop_action_class(self, kwargs, default=None):
1565 action = kwargs.pop('action', default)
1566 return self._registry_get('action', action, action)
1567
1568 def _get_handler(self):
1569 # determine function from conflict handler string
1570 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1571 try:
1572 return getattr(self, handler_func_name)
1573 except AttributeError:
1574 msg = _('invalid conflict_resolution value: %r')
1575 raise ValueError(msg % self.conflict_handler)
1576
1577 def _check_conflict(self, action):
1578
1579 # find all options that conflict with this option
1580 confl_optionals = []
1581 for option_string in action.option_strings:
1582 if option_string in self._option_string_actions:
1583 confl_optional = self._option_string_actions[option_string]
1584 confl_optionals.append((option_string, confl_optional))
1585
1586 # resolve any conflicts
1587 if confl_optionals:
1588 conflict_handler = self._get_handler()
1589 conflict_handler(action, confl_optionals)
1590
1591 def _handle_conflict_error(self, action, conflicting_actions):
Éric Araujo12159152010-12-04 17:31:49 +00001592 message = ngettext('conflicting option string: %s',
1593 'conflicting option strings: %s',
1594 len(conflicting_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001595 conflict_string = ', '.join([option_string
1596 for option_string, action
1597 in conflicting_actions])
1598 raise ArgumentError(action, message % conflict_string)
1599
1600 def _handle_conflict_resolve(self, action, conflicting_actions):
1601
1602 # remove all conflicting options
1603 for option_string, action in conflicting_actions:
1604
1605 # remove the conflicting option
1606 action.option_strings.remove(option_string)
1607 self._option_string_actions.pop(option_string, None)
1608
1609 # if the option now has no option string, remove it from the
1610 # container holding it
1611 if not action.option_strings:
1612 action.container._remove_action(action)
1613
1614
1615class _ArgumentGroup(_ActionsContainer):
1616
1617 def __init__(self, container, title=None, description=None, **kwargs):
1618 # add any missing keyword arguments by checking the container
1619 update = kwargs.setdefault
1620 update('conflict_handler', container.conflict_handler)
1621 update('prefix_chars', container.prefix_chars)
1622 update('argument_default', container.argument_default)
1623 super_init = super(_ArgumentGroup, self).__init__
1624 super_init(description=description, **kwargs)
1625
1626 # group attributes
1627 self.title = title
1628 self._group_actions = []
1629
1630 # share most attributes with the container
1631 self._registries = container._registries
1632 self._actions = container._actions
1633 self._option_string_actions = container._option_string_actions
1634 self._defaults = container._defaults
1635 self._has_negative_number_optionals = \
1636 container._has_negative_number_optionals
Georg Brandl0f6b47a2011-01-30 12:19:35 +00001637 self._mutually_exclusive_groups = container._mutually_exclusive_groups
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001638
1639 def _add_action(self, action):
1640 action = super(_ArgumentGroup, self)._add_action(action)
1641 self._group_actions.append(action)
1642 return action
1643
1644 def _remove_action(self, action):
1645 super(_ArgumentGroup, self)._remove_action(action)
1646 self._group_actions.remove(action)
1647
1648
1649class _MutuallyExclusiveGroup(_ArgumentGroup):
1650
1651 def __init__(self, container, required=False):
1652 super(_MutuallyExclusiveGroup, self).__init__(container)
1653 self.required = required
1654 self._container = container
1655
1656 def _add_action(self, action):
1657 if action.required:
1658 msg = _('mutually exclusive arguments must be optional')
1659 raise ValueError(msg)
1660 action = self._container._add_action(action)
1661 self._group_actions.append(action)
1662 return action
1663
1664 def _remove_action(self, action):
1665 self._container._remove_action(action)
1666 self._group_actions.remove(action)
1667
1668
1669class ArgumentParser(_AttributeHolder, _ActionsContainer):
1670 """Object for parsing command line strings into Python objects.
1671
1672 Keyword Arguments:
1673 - prog -- The name of the program (default: sys.argv[0])
1674 - usage -- A usage message (default: auto-generated from arguments)
1675 - description -- A description of what the program does
1676 - epilog -- Text following the argument descriptions
1677 - parents -- Parsers whose arguments should be copied into this one
1678 - formatter_class -- HelpFormatter class for printing help messages
1679 - prefix_chars -- Characters that prefix optional arguments
1680 - fromfile_prefix_chars -- Characters that prefix files containing
1681 additional arguments
1682 - argument_default -- The default value for all arguments
1683 - conflict_handler -- String indicating how to handle conflicts
1684 - add_help -- Add a -h/-help option
Berker Peksag8089cd62015-02-14 01:39:17 +02001685 - allow_abbrev -- Allow long options to be abbreviated unambiguously
Hai Shif5456382019-09-12 05:56:05 -05001686 - exit_on_error -- Determines whether or not ArgumentParser exits with
1687 error info when an error occurs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001688 """
1689
1690 def __init__(self,
1691 prog=None,
1692 usage=None,
1693 description=None,
1694 epilog=None,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001695 parents=[],
1696 formatter_class=HelpFormatter,
1697 prefix_chars='-',
1698 fromfile_prefix_chars=None,
1699 argument_default=None,
1700 conflict_handler='error',
Berker Peksag8089cd62015-02-14 01:39:17 +02001701 add_help=True,
Hai Shif5456382019-09-12 05:56:05 -05001702 allow_abbrev=True,
1703 exit_on_error=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001704
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001705 superinit = super(ArgumentParser, self).__init__
1706 superinit(description=description,
1707 prefix_chars=prefix_chars,
1708 argument_default=argument_default,
1709 conflict_handler=conflict_handler)
1710
1711 # default setting for prog
1712 if prog is None:
1713 prog = _os.path.basename(_sys.argv[0])
1714
1715 self.prog = prog
1716 self.usage = usage
1717 self.epilog = epilog
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001718 self.formatter_class = formatter_class
1719 self.fromfile_prefix_chars = fromfile_prefix_chars
1720 self.add_help = add_help
Berker Peksag8089cd62015-02-14 01:39:17 +02001721 self.allow_abbrev = allow_abbrev
Hai Shif5456382019-09-12 05:56:05 -05001722 self.exit_on_error = exit_on_error
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001723
1724 add_group = self.add_argument_group
1725 self._positionals = add_group(_('positional arguments'))
Raymond Hettinger41b223d2020-12-23 09:40:56 -08001726 self._optionals = add_group(_('options'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001727 self._subparsers = None
1728
1729 # register types
1730 def identity(string):
1731 return string
1732 self.register('type', None, identity)
1733
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001734 # add help argument if necessary
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001735 # (using explicit default to override global argument_default)
R. David Murray88c49fe2010-08-03 17:56:09 +00001736 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001737 if self.add_help:
1738 self.add_argument(
R. David Murray88c49fe2010-08-03 17:56:09 +00001739 default_prefix+'h', default_prefix*2+'help',
1740 action='help', default=SUPPRESS,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001741 help=_('show this help message and exit'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001742
1743 # add parent arguments and defaults
1744 for parent in parents:
1745 self._add_container_actions(parent)
1746 try:
1747 defaults = parent._defaults
1748 except AttributeError:
1749 pass
1750 else:
1751 self._defaults.update(defaults)
1752
1753 # =======================
1754 # Pretty __repr__ methods
1755 # =======================
1756 def _get_kwargs(self):
1757 names = [
1758 'prog',
1759 'usage',
1760 'description',
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001761 'formatter_class',
1762 'conflict_handler',
1763 'add_help',
1764 ]
1765 return [(name, getattr(self, name)) for name in names]
1766
1767 # ==================================
1768 # Optional/Positional adding methods
1769 # ==================================
1770 def add_subparsers(self, **kwargs):
1771 if self._subparsers is not None:
1772 self.error(_('cannot have multiple subparser arguments'))
1773
1774 # add the parser class to the arguments if it's not present
1775 kwargs.setdefault('parser_class', type(self))
1776
1777 if 'title' in kwargs or 'description' in kwargs:
1778 title = _(kwargs.pop('title', 'subcommands'))
1779 description = _(kwargs.pop('description', None))
1780 self._subparsers = self.add_argument_group(title, description)
1781 else:
1782 self._subparsers = self._positionals
1783
1784 # prog defaults to the usage message of this parser, skipping
1785 # optional arguments and with no "usage:" prefix
1786 if kwargs.get('prog') is None:
1787 formatter = self._get_formatter()
1788 positionals = self._get_positional_actions()
1789 groups = self._mutually_exclusive_groups
1790 formatter.add_usage(self.usage, positionals, groups, '')
1791 kwargs['prog'] = formatter.format_help().strip()
1792
1793 # create the parsers action and add it to the positionals list
1794 parsers_class = self._pop_action_class(kwargs, 'parsers')
1795 action = parsers_class(option_strings=[], **kwargs)
1796 self._subparsers._add_action(action)
1797
1798 # return the created parsers action
1799 return action
1800
1801 def _add_action(self, action):
1802 if action.option_strings:
1803 self._optionals._add_action(action)
1804 else:
1805 self._positionals._add_action(action)
1806 return action
1807
1808 def _get_optional_actions(self):
1809 return [action
1810 for action in self._actions
1811 if action.option_strings]
1812
1813 def _get_positional_actions(self):
1814 return [action
1815 for action in self._actions
1816 if not action.option_strings]
1817
1818 # =====================================
1819 # Command line argument parsing methods
1820 # =====================================
1821 def parse_args(self, args=None, namespace=None):
1822 args, argv = self.parse_known_args(args, namespace)
1823 if argv:
1824 msg = _('unrecognized arguments: %s')
1825 self.error(msg % ' '.join(argv))
1826 return args
1827
1828 def parse_known_args(self, args=None, namespace=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001829 if args is None:
R David Murrayb5228282012-09-08 12:08:01 -04001830 # args default to the system args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001831 args = _sys.argv[1:]
R David Murrayb5228282012-09-08 12:08:01 -04001832 else:
1833 # make sure that args are mutable
1834 args = list(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001835
1836 # default Namespace built from parser defaults
1837 if namespace is None:
1838 namespace = Namespace()
1839
1840 # add any action defaults that aren't present
1841 for action in self._actions:
1842 if action.dest is not SUPPRESS:
1843 if not hasattr(namespace, action.dest):
1844 if action.default is not SUPPRESS:
R David Murray6fb8fb12012-08-31 22:45:20 -04001845 setattr(namespace, action.dest, action.default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001846
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001847 # parse the arguments and exit if there are any errors
Hai Shif5456382019-09-12 05:56:05 -05001848 if self.exit_on_error:
1849 try:
1850 namespace, args = self._parse_known_args(args, namespace)
1851 except ArgumentError:
1852 err = _sys.exc_info()[1]
1853 self.error(str(err))
1854 else:
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001855 namespace, args = self._parse_known_args(args, namespace)
Hai Shif5456382019-09-12 05:56:05 -05001856
Miss Islington (bot)6e4101a2021-09-17 23:47:16 -07001857 # add any parser defaults that aren't present
1858 for dest in self._defaults:
1859 if not hasattr(namespace, dest):
1860 setattr(namespace, dest, self._defaults[dest])
1861
Hai Shif5456382019-09-12 05:56:05 -05001862 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1863 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1864 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1865 return namespace, args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001866
1867 def _parse_known_args(self, arg_strings, namespace):
1868 # replace arg strings that are file references
1869 if self.fromfile_prefix_chars is not None:
1870 arg_strings = self._read_args_from_files(arg_strings)
1871
1872 # map all mutually exclusive arguments to the other arguments
1873 # they can't occur with
1874 action_conflicts = {}
1875 for mutex_group in self._mutually_exclusive_groups:
1876 group_actions = mutex_group._group_actions
1877 for i, mutex_action in enumerate(mutex_group._group_actions):
1878 conflicts = action_conflicts.setdefault(mutex_action, [])
1879 conflicts.extend(group_actions[:i])
1880 conflicts.extend(group_actions[i + 1:])
1881
1882 # find all option indices, and determine the arg_string_pattern
1883 # which has an 'O' if there is an option at an index,
1884 # an 'A' if there is an argument, or a '-' if there is a '--'
1885 option_string_indices = {}
1886 arg_string_pattern_parts = []
1887 arg_strings_iter = iter(arg_strings)
1888 for i, arg_string in enumerate(arg_strings_iter):
1889
1890 # all args after -- are non-options
1891 if arg_string == '--':
1892 arg_string_pattern_parts.append('-')
1893 for arg_string in arg_strings_iter:
1894 arg_string_pattern_parts.append('A')
1895
1896 # otherwise, add the arg to the arg strings
1897 # and note the index if it was an option
1898 else:
1899 option_tuple = self._parse_optional(arg_string)
1900 if option_tuple is None:
1901 pattern = 'A'
1902 else:
1903 option_string_indices[i] = option_tuple
1904 pattern = 'O'
1905 arg_string_pattern_parts.append(pattern)
1906
1907 # join the pieces together to form the pattern
1908 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1909
1910 # converts arg strings to the appropriate and then takes the action
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00001911 seen_actions = set()
1912 seen_non_default_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001913
1914 def take_action(action, argument_strings, option_string=None):
1915 seen_actions.add(action)
1916 argument_values = self._get_values(action, argument_strings)
1917
1918 # error if this argument is not allowed with other previously
1919 # seen arguments, assuming that actions that use the default
1920 # value don't really count as "present"
1921 if argument_values is not action.default:
1922 seen_non_default_actions.add(action)
1923 for conflict_action in action_conflicts.get(action, []):
1924 if conflict_action in seen_non_default_actions:
1925 msg = _('not allowed with argument %s')
1926 action_name = _get_action_name(conflict_action)
1927 raise ArgumentError(action, msg % action_name)
1928
1929 # take the action if we didn't receive a SUPPRESS value
1930 # (e.g. from a default)
1931 if argument_values is not SUPPRESS:
1932 action(self, namespace, argument_values, option_string)
1933
1934 # function to convert arg_strings into an optional action
1935 def consume_optional(start_index):
1936
1937 # get the optional identified at this index
1938 option_tuple = option_string_indices[start_index]
1939 action, option_string, explicit_arg = option_tuple
1940
1941 # identify additional optionals in the same arg string
1942 # (e.g. -xyz is the same as -x -y -z if no args are required)
1943 match_argument = self._match_argument
1944 action_tuples = []
1945 while True:
1946
1947 # if we found no optional action, skip it
1948 if action is None:
1949 extras.append(arg_strings[start_index])
1950 return start_index + 1
1951
1952 # if there is an explicit argument, try to match the
1953 # optional's string arguments to only this
1954 if explicit_arg is not None:
1955 arg_count = match_argument(action, 'A')
1956
1957 # if the action is a single-dash option and takes no
1958 # arguments, try to parse more single-dash options out
1959 # of the tail of the option string
1960 chars = self.prefix_chars
1961 if arg_count == 0 and option_string[1] not in chars:
1962 action_tuples.append((action, [], option_string))
Steven Bethard1ca45a52010-11-01 15:57:36 +00001963 char = option_string[0]
1964 option_string = char + explicit_arg[0]
1965 new_explicit_arg = explicit_arg[1:] or None
1966 optionals_map = self._option_string_actions
1967 if option_string in optionals_map:
1968 action = optionals_map[option_string]
1969 explicit_arg = new_explicit_arg
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001970 else:
1971 msg = _('ignored explicit argument %r')
1972 raise ArgumentError(action, msg % explicit_arg)
1973
1974 # if the action expect exactly one argument, we've
1975 # successfully matched the option; exit the loop
1976 elif arg_count == 1:
1977 stop = start_index + 1
1978 args = [explicit_arg]
1979 action_tuples.append((action, args, option_string))
1980 break
1981
1982 # error if a double-dash option did not use the
1983 # explicit argument
1984 else:
1985 msg = _('ignored explicit argument %r')
1986 raise ArgumentError(action, msg % explicit_arg)
1987
1988 # if there is no explicit argument, try to match the
1989 # optional's string arguments with the following strings
1990 # if successful, exit the loop
1991 else:
1992 start = start_index + 1
1993 selected_patterns = arg_strings_pattern[start:]
1994 arg_count = match_argument(action, selected_patterns)
1995 stop = start + arg_count
1996 args = arg_strings[start:stop]
1997 action_tuples.append((action, args, option_string))
1998 break
1999
2000 # add the Optional to the list and return the index at which
2001 # the Optional's string args stopped
2002 assert action_tuples
2003 for action, args, option_string in action_tuples:
2004 take_action(action, args, option_string)
2005 return stop
2006
2007 # the list of Positionals left to be parsed; this is modified
2008 # by consume_positionals()
2009 positionals = self._get_positional_actions()
2010
2011 # function to convert arg_strings into positional actions
2012 def consume_positionals(start_index):
2013 # match as many Positionals as possible
2014 match_partial = self._match_arguments_partial
2015 selected_pattern = arg_strings_pattern[start_index:]
2016 arg_counts = match_partial(positionals, selected_pattern)
2017
2018 # slice off the appropriate arg strings for each Positional
2019 # and add the Positional and its args to the list
2020 for action, arg_count in zip(positionals, arg_counts):
2021 args = arg_strings[start_index: start_index + arg_count]
2022 start_index += arg_count
2023 take_action(action, args)
2024
2025 # slice off the Positionals that we just parsed and return the
2026 # index at which the Positionals' string args stopped
2027 positionals[:] = positionals[len(arg_counts):]
2028 return start_index
2029
2030 # consume Positionals and Optionals alternately, until we have
2031 # passed the last option string
2032 extras = []
2033 start_index = 0
2034 if option_string_indices:
2035 max_option_string_index = max(option_string_indices)
2036 else:
2037 max_option_string_index = -1
2038 while start_index <= max_option_string_index:
2039
2040 # consume any Positionals preceding the next option
2041 next_option_string_index = min([
2042 index
2043 for index in option_string_indices
2044 if index >= start_index])
2045 if start_index != next_option_string_index:
2046 positionals_end_index = consume_positionals(start_index)
2047
2048 # only try to parse the next optional if we didn't consume
2049 # the option string during the positionals parsing
2050 if positionals_end_index > start_index:
2051 start_index = positionals_end_index
2052 continue
2053 else:
2054 start_index = positionals_end_index
2055
2056 # if we consumed all the positionals we could and we're not
2057 # at the index of an option string, there were extra arguments
2058 if start_index not in option_string_indices:
2059 strings = arg_strings[start_index:next_option_string_index]
2060 extras.extend(strings)
2061 start_index = next_option_string_index
2062
2063 # consume the next optional and any arguments for it
2064 start_index = consume_optional(start_index)
2065
2066 # consume any positionals following the last Optional
2067 stop_index = consume_positionals(start_index)
2068
2069 # if we didn't consume all the argument strings, there were extras
2070 extras.extend(arg_strings[stop_index:])
2071
R David Murray64b0ef12012-08-31 23:09:34 -04002072 # make sure all required actions were present and also convert
2073 # action defaults which were not given as arguments
2074 required_actions = []
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002075 for action in self._actions:
R David Murray6fb8fb12012-08-31 22:45:20 -04002076 if action not in seen_actions:
2077 if action.required:
R David Murray64b0ef12012-08-31 23:09:34 -04002078 required_actions.append(_get_action_name(action))
R David Murray6fb8fb12012-08-31 22:45:20 -04002079 else:
2080 # Convert action default now instead of doing it before
2081 # parsing arguments to avoid calling convert functions
2082 # twice (which may fail) if the argument was given, but
2083 # only if it was defined already in the namespace
2084 if (action.default is not None and
Barry Warsawd89774e2012-09-12 15:31:38 -04002085 isinstance(action.default, str) and
R David Murray64b0ef12012-08-31 23:09:34 -04002086 hasattr(namespace, action.dest) and
2087 action.default is getattr(namespace, action.dest)):
R David Murray6fb8fb12012-08-31 22:45:20 -04002088 setattr(namespace, action.dest,
2089 self._get_value(action, action.default))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002090
R David Murrayf97c59a2011-06-09 12:34:07 -04002091 if required_actions:
2092 self.error(_('the following arguments are required: %s') %
2093 ', '.join(required_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002094
2095 # make sure all required groups had one option present
2096 for group in self._mutually_exclusive_groups:
2097 if group.required:
2098 for action in group._group_actions:
2099 if action in seen_non_default_actions:
2100 break
2101
2102 # if no actions were used, report the error
2103 else:
2104 names = [_get_action_name(action)
2105 for action in group._group_actions
2106 if action.help is not SUPPRESS]
2107 msg = _('one of the arguments %s is required')
2108 self.error(msg % ' '.join(names))
2109
2110 # return the updated namespace and the extra arguments
2111 return namespace, extras
2112
2113 def _read_args_from_files(self, arg_strings):
2114 # expand arguments referencing files
2115 new_arg_strings = []
2116 for arg_string in arg_strings:
2117
2118 # for regular arguments, just add them back into the list
R David Murrayb94082a2012-07-21 22:20:11 -04002119 if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002120 new_arg_strings.append(arg_string)
2121
2122 # replace arguments referencing files with the file content
2123 else:
2124 try:
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01002125 with open(arg_string[1:]) as args_file:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002126 arg_strings = []
2127 for arg_line in args_file.read().splitlines():
2128 for arg in self.convert_arg_line_to_args(arg_line):
2129 arg_strings.append(arg)
2130 arg_strings = self._read_args_from_files(arg_strings)
2131 new_arg_strings.extend(arg_strings)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002132 except OSError:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002133 err = _sys.exc_info()[1]
2134 self.error(str(err))
2135
2136 # return the modified argument list
2137 return new_arg_strings
2138
2139 def convert_arg_line_to_args(self, arg_line):
2140 return [arg_line]
2141
2142 def _match_argument(self, action, arg_strings_pattern):
2143 # match the pattern for this action to the arg strings
2144 nargs_pattern = self._get_nargs_pattern(action)
2145 match = _re.match(nargs_pattern, arg_strings_pattern)
2146
2147 # raise an exception if we weren't able to find a match
2148 if match is None:
2149 nargs_errors = {
2150 None: _('expected one argument'),
2151 OPTIONAL: _('expected at most one argument'),
2152 ONE_OR_MORE: _('expected at least one argument'),
2153 }
Federico Bondbe5c79e2019-11-20 10:29:29 -03002154 msg = nargs_errors.get(action.nargs)
2155 if msg is None:
2156 msg = ngettext('expected %s argument',
Éric Araujo12159152010-12-04 17:31:49 +00002157 'expected %s arguments',
2158 action.nargs) % action.nargs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002159 raise ArgumentError(action, msg)
2160
2161 # return the number of arguments matched
2162 return len(match.group(1))
2163
2164 def _match_arguments_partial(self, actions, arg_strings_pattern):
2165 # progressively shorten the actions list by slicing off the
2166 # final actions until we find a match
2167 result = []
2168 for i in range(len(actions), 0, -1):
2169 actions_slice = actions[:i]
2170 pattern = ''.join([self._get_nargs_pattern(action)
2171 for action in actions_slice])
2172 match = _re.match(pattern, arg_strings_pattern)
2173 if match is not None:
2174 result.extend([len(string) for string in match.groups()])
2175 break
2176
2177 # return the list of arg string counts
2178 return result
2179
2180 def _parse_optional(self, arg_string):
2181 # if it's an empty string, it was meant to be a positional
2182 if not arg_string:
2183 return None
2184
2185 # if it doesn't start with a prefix, it was meant to be positional
2186 if not arg_string[0] in self.prefix_chars:
2187 return None
2188
2189 # if the option string is present in the parser, return the action
2190 if arg_string in self._option_string_actions:
2191 action = self._option_string_actions[arg_string]
2192 return action, arg_string, None
2193
2194 # if it's just a single character, it was meant to be positional
2195 if len(arg_string) == 1:
2196 return None
2197
2198 # if the option string before the "=" is present, return the action
2199 if '=' in arg_string:
2200 option_string, explicit_arg = arg_string.split('=', 1)
2201 if option_string in self._option_string_actions:
2202 action = self._option_string_actions[option_string]
2203 return action, option_string, explicit_arg
2204
Kyle Meyer8edfc472020-02-18 04:48:57 -05002205 # search through all possible prefixes of the option string
2206 # and all actions in the parser for possible interpretations
2207 option_tuples = self._get_option_tuples(arg_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002208
Kyle Meyer8edfc472020-02-18 04:48:57 -05002209 # if multiple actions match, the option string was ambiguous
2210 if len(option_tuples) > 1:
2211 options = ', '.join([option_string
2212 for action, option_string, explicit_arg in option_tuples])
2213 args = {'option': arg_string, 'matches': options}
2214 msg = _('ambiguous option: %(option)s could match %(matches)s')
2215 self.error(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002216
Kyle Meyer8edfc472020-02-18 04:48:57 -05002217 # if exactly one action matched, this segmentation is good,
2218 # so return the parsed action
2219 elif len(option_tuples) == 1:
2220 option_tuple, = option_tuples
2221 return option_tuple
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002222
2223 # if it was not found as an option, but it looks like a negative
2224 # number, it was meant to be positional
2225 # unless there are negative-number-like options
2226 if self._negative_number_matcher.match(arg_string):
2227 if not self._has_negative_number_optionals:
2228 return None
2229
2230 # if it contains a space, it was meant to be a positional
2231 if ' ' in arg_string:
2232 return None
2233
2234 # it was meant to be an optional but there is no such option
2235 # in this parser (though it might be a valid option in a subparser)
2236 return None, arg_string, None
2237
2238 def _get_option_tuples(self, option_string):
2239 result = []
2240
2241 # option strings starting with two prefix characters are only
2242 # split at the '='
2243 chars = self.prefix_chars
2244 if option_string[0] in chars and option_string[1] in chars:
Kyle Meyer8edfc472020-02-18 04:48:57 -05002245 if self.allow_abbrev:
2246 if '=' in option_string:
2247 option_prefix, explicit_arg = option_string.split('=', 1)
2248 else:
2249 option_prefix = option_string
2250 explicit_arg = None
2251 for option_string in self._option_string_actions:
2252 if option_string.startswith(option_prefix):
2253 action = self._option_string_actions[option_string]
2254 tup = action, option_string, explicit_arg
2255 result.append(tup)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002256
2257 # single character options can be concatenated with their arguments
2258 # but multiple character options always have to have their argument
2259 # separate
2260 elif option_string[0] in chars and option_string[1] not in chars:
2261 option_prefix = option_string
2262 explicit_arg = None
2263 short_option_prefix = option_string[:2]
2264 short_explicit_arg = option_string[2:]
2265
2266 for option_string in self._option_string_actions:
2267 if option_string == short_option_prefix:
2268 action = self._option_string_actions[option_string]
2269 tup = action, option_string, short_explicit_arg
2270 result.append(tup)
2271 elif option_string.startswith(option_prefix):
2272 action = self._option_string_actions[option_string]
2273 tup = action, option_string, explicit_arg
2274 result.append(tup)
2275
2276 # shouldn't ever get here
2277 else:
2278 self.error(_('unexpected option string: %s') % option_string)
2279
2280 # return the collected option tuples
2281 return result
2282
2283 def _get_nargs_pattern(self, action):
2284 # in all examples below, we have to allow for '--' args
2285 # which are represented as '-' in the pattern
2286 nargs = action.nargs
2287
2288 # the default (None) is assumed to be a single argument
2289 if nargs is None:
2290 nargs_pattern = '(-*A-*)'
2291
2292 # allow zero or one arguments
2293 elif nargs == OPTIONAL:
2294 nargs_pattern = '(-*A?-*)'
2295
2296 # allow zero or more arguments
2297 elif nargs == ZERO_OR_MORE:
2298 nargs_pattern = '(-*[A-]*)'
2299
2300 # allow one or more arguments
2301 elif nargs == ONE_OR_MORE:
2302 nargs_pattern = '(-*A[A-]*)'
2303
2304 # allow any number of options or arguments
2305 elif nargs == REMAINDER:
2306 nargs_pattern = '([-AO]*)'
2307
2308 # allow one argument followed by any number of options or arguments
2309 elif nargs == PARSER:
2310 nargs_pattern = '(-*A[-AO]*)'
2311
R. David Murray0f6b9d22017-09-06 20:25:40 -04002312 # suppress action, like nargs=0
2313 elif nargs == SUPPRESS:
2314 nargs_pattern = '(-*-*)'
2315
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002316 # all others should be integers
2317 else:
2318 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2319
2320 # if this is an optional action, -- is not allowed
2321 if action.option_strings:
2322 nargs_pattern = nargs_pattern.replace('-*', '')
2323 nargs_pattern = nargs_pattern.replace('-', '')
2324
2325 # return the pattern
2326 return nargs_pattern
2327
2328 # ========================
R. David Murray0f6b9d22017-09-06 20:25:40 -04002329 # Alt command line argument parsing, allowing free intermix
2330 # ========================
2331
2332 def parse_intermixed_args(self, args=None, namespace=None):
2333 args, argv = self.parse_known_intermixed_args(args, namespace)
2334 if argv:
2335 msg = _('unrecognized arguments: %s')
2336 self.error(msg % ' '.join(argv))
2337 return args
2338
2339 def parse_known_intermixed_args(self, args=None, namespace=None):
2340 # returns a namespace and list of extras
2341 #
2342 # positional can be freely intermixed with optionals. optionals are
2343 # first parsed with all positional arguments deactivated. The 'extras'
2344 # are then parsed. If the parser definition is incompatible with the
2345 # intermixed assumptions (e.g. use of REMAINDER, subparsers) a
2346 # TypeError is raised.
2347 #
2348 # positionals are 'deactivated' by setting nargs and default to
2349 # SUPPRESS. This blocks the addition of that positional to the
2350 # namespace
2351
2352 positionals = self._get_positional_actions()
2353 a = [action for action in positionals
2354 if action.nargs in [PARSER, REMAINDER]]
2355 if a:
2356 raise TypeError('parse_intermixed_args: positional arg'
2357 ' with nargs=%s'%a[0].nargs)
2358
2359 if [action.dest for group in self._mutually_exclusive_groups
2360 for action in group._group_actions if action in positionals]:
2361 raise TypeError('parse_intermixed_args: positional in'
2362 ' mutuallyExclusiveGroup')
2363
2364 try:
2365 save_usage = self.usage
2366 try:
2367 if self.usage is None:
2368 # capture the full usage for use in error messages
2369 self.usage = self.format_usage()[7:]
2370 for action in positionals:
2371 # deactivate positionals
2372 action.save_nargs = action.nargs
2373 # action.nargs = 0
2374 action.nargs = SUPPRESS
2375 action.save_default = action.default
2376 action.default = SUPPRESS
2377 namespace, remaining_args = self.parse_known_args(args,
2378 namespace)
2379 for action in positionals:
2380 # remove the empty positional values from namespace
2381 if (hasattr(namespace, action.dest)
2382 and getattr(namespace, action.dest)==[]):
2383 from warnings import warn
2384 warn('Do not expect %s in %s' % (action.dest, namespace))
2385 delattr(namespace, action.dest)
2386 finally:
2387 # restore nargs and usage before exiting
2388 for action in positionals:
2389 action.nargs = action.save_nargs
2390 action.default = action.save_default
2391 optionals = self._get_optional_actions()
2392 try:
2393 # parse positionals. optionals aren't normally required, but
2394 # they could be, so make sure they aren't.
2395 for action in optionals:
2396 action.save_required = action.required
2397 action.required = False
2398 for group in self._mutually_exclusive_groups:
2399 group.save_required = group.required
2400 group.required = False
2401 namespace, extras = self.parse_known_args(remaining_args,
2402 namespace)
2403 finally:
2404 # restore parser values before exiting
2405 for action in optionals:
2406 action.required = action.save_required
2407 for group in self._mutually_exclusive_groups:
2408 group.required = group.save_required
2409 finally:
2410 self.usage = save_usage
2411 return namespace, extras
2412
2413 # ========================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002414 # Value conversion methods
2415 # ========================
2416 def _get_values(self, action, arg_strings):
R David Murray00528e82012-07-21 22:48:35 -04002417 # for everything but PARSER, REMAINDER args, strip out first '--'
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002418 if action.nargs not in [PARSER, REMAINDER]:
R David Murray00528e82012-07-21 22:48:35 -04002419 try:
2420 arg_strings.remove('--')
2421 except ValueError:
2422 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002423
2424 # optional argument produces a default when not present
2425 if not arg_strings and action.nargs == OPTIONAL:
2426 if action.option_strings:
2427 value = action.const
2428 else:
2429 value = action.default
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00002430 if isinstance(value, str):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002431 value = self._get_value(action, value)
2432 self._check_value(action, value)
2433
2434 # when nargs='*' on a positional, if there were no command-line
2435 # args, use the default if it is anything other than None
2436 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2437 not action.option_strings):
2438 if action.default is not None:
2439 value = action.default
2440 else:
2441 value = arg_strings
2442 self._check_value(action, value)
2443
2444 # single argument or optional argument produces a single value
2445 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2446 arg_string, = arg_strings
2447 value = self._get_value(action, arg_string)
2448 self._check_value(action, value)
2449
2450 # REMAINDER arguments convert all values, checking none
2451 elif action.nargs == REMAINDER:
2452 value = [self._get_value(action, v) for v in arg_strings]
2453
2454 # PARSER arguments convert all values, but check only the first
2455 elif action.nargs == PARSER:
2456 value = [self._get_value(action, v) for v in arg_strings]
2457 self._check_value(action, value[0])
2458
R. David Murray0f6b9d22017-09-06 20:25:40 -04002459 # SUPPRESS argument does not put anything in the namespace
2460 elif action.nargs == SUPPRESS:
2461 value = SUPPRESS
2462
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002463 # all other types of nargs produce a list
2464 else:
2465 value = [self._get_value(action, v) for v in arg_strings]
2466 for v in value:
2467 self._check_value(action, v)
2468
2469 # return the converted value
2470 return value
2471
2472 def _get_value(self, action, arg_string):
2473 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02002474 if not callable(type_func):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002475 msg = _('%r is not callable')
2476 raise ArgumentError(action, msg % type_func)
2477
2478 # convert the value to the appropriate type
2479 try:
2480 result = type_func(arg_string)
2481
2482 # ArgumentTypeErrors indicate errors
2483 except ArgumentTypeError:
2484 name = getattr(action.type, '__name__', repr(action.type))
2485 msg = str(_sys.exc_info()[1])
2486 raise ArgumentError(action, msg)
2487
2488 # TypeErrors or ValueErrors also indicate errors
2489 except (TypeError, ValueError):
2490 name = getattr(action.type, '__name__', repr(action.type))
Éric Araujobb48a8b2010-12-03 19:41:00 +00002491 args = {'type': name, 'value': arg_string}
2492 msg = _('invalid %(type)s value: %(value)r')
2493 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002494
2495 # return the converted value
2496 return result
2497
2498 def _check_value(self, action, value):
2499 # converted value must be one of the choices (if specified)
Vinay Sajip9ae50502016-08-23 08:43:16 +01002500 if action.choices is not None and value not in action.choices:
2501 args = {'value': value,
2502 'choices': ', '.join(map(repr, action.choices))}
2503 msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2504 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002505
2506 # =======================
2507 # Help-formatting methods
2508 # =======================
2509 def format_usage(self):
2510 formatter = self._get_formatter()
2511 formatter.add_usage(self.usage, self._actions,
2512 self._mutually_exclusive_groups)
2513 return formatter.format_help()
2514
2515 def format_help(self):
2516 formatter = self._get_formatter()
2517
2518 # usage
2519 formatter.add_usage(self.usage, self._actions,
2520 self._mutually_exclusive_groups)
2521
2522 # description
2523 formatter.add_text(self.description)
2524
2525 # positionals, optionals and user-defined groups
2526 for action_group in self._action_groups:
2527 formatter.start_section(action_group.title)
2528 formatter.add_text(action_group.description)
2529 formatter.add_arguments(action_group._group_actions)
2530 formatter.end_section()
2531
2532 # epilog
2533 formatter.add_text(self.epilog)
2534
2535 # determine help from format above
2536 return formatter.format_help()
2537
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002538 def _get_formatter(self):
2539 return self.formatter_class(prog=self.prog)
2540
2541 # =====================
2542 # Help-printing methods
2543 # =====================
2544 def print_usage(self, file=None):
2545 if file is None:
2546 file = _sys.stdout
2547 self._print_message(self.format_usage(), file)
2548
2549 def print_help(self, file=None):
2550 if file is None:
2551 file = _sys.stdout
2552 self._print_message(self.format_help(), file)
2553
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002554 def _print_message(self, message, file=None):
2555 if message:
2556 if file is None:
2557 file = _sys.stderr
2558 file.write(message)
2559
2560 # ===============
2561 # Exiting methods
2562 # ===============
2563 def exit(self, status=0, message=None):
2564 if message:
2565 self._print_message(message, _sys.stderr)
2566 _sys.exit(status)
2567
2568 def error(self, message):
2569 """error(message: string)
2570
2571 Prints a usage message incorporating the message to stderr and
2572 exits.
2573
2574 If you override this in a subclass, it should not return -- it
2575 should either exit or raise an exception.
2576 """
2577 self.print_usage(_sys.stderr)
Éric Araujobb48a8b2010-12-03 19:41:00 +00002578 args = {'prog': self.prog, 'message': message}
2579 self.exit(2, _('%(prog)s: error: %(message)s\n') % args)