blob: 13af7ac2392174a628edcfefb60eb634ebc66fdb [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
Berker Peksag74102c92018-07-25 18:23:44 +030090import shutil as _shutil
Benjamin Peterson698a18a2010-03-02 22:34:37 +000091import sys as _sys
Benjamin Peterson698a18a2010-03-02 22:34:37 +000092
Éric Araujo12159152010-12-04 17:31:49 +000093from gettext import gettext as _, ngettext
Benjamin Peterson698a18a2010-03-02 22:34:37 +000094
Benjamin Peterson698a18a2010-03-02 22:34:37 +000095SUPPRESS = '==SUPPRESS=='
96
97OPTIONAL = '?'
98ZERO_OR_MORE = '*'
99ONE_OR_MORE = '+'
100PARSER = 'A...'
101REMAINDER = '...'
Steven Bethardfca2e8a2010-11-02 12:47:22 +0000102_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000103
104# =============================
105# Utility functions and classes
106# =============================
107
108class _AttributeHolder(object):
109 """Abstract base class that provides __repr__.
110
111 The __repr__ method returns a string in the format::
112 ClassName(attr=name, attr=name, ...)
113 The attributes are determined either by a class-level attribute,
114 '_kwarg_names', or by inspecting the instance __dict__.
115 """
116
117 def __repr__(self):
118 type_name = type(self).__name__
119 arg_strings = []
Berker Peksag76b17142015-07-29 23:51:47 +0300120 star_args = {}
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000121 for arg in self._get_args():
122 arg_strings.append(repr(arg))
123 for name, value in self._get_kwargs():
Berker Peksag76b17142015-07-29 23:51:47 +0300124 if name.isidentifier():
125 arg_strings.append('%s=%r' % (name, value))
126 else:
127 star_args[name] = value
128 if star_args:
129 arg_strings.append('**%s' % repr(star_args))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000130 return '%s(%s)' % (type_name, ', '.join(arg_strings))
131
132 def _get_kwargs(self):
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000133 return sorted(self.__dict__.items())
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000134
135 def _get_args(self):
136 return []
137
138
Serhiy Storchaka81108372017-09-26 00:55:55 +0300139def _copy_items(items):
140 if items is None:
141 return []
142 # The copy module is used only in the 'append' and 'append_const'
143 # actions, and it is needed only when the default value isn't a list.
144 # Delay its import for speeding up the common case.
145 if type(items) is list:
146 return items[:]
147 import copy
148 return copy.copy(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000149
150
151# ===============
152# Formatting Help
153# ===============
154
155class HelpFormatter(object):
156 """Formatter for generating usage messages and argument help strings.
157
158 Only the name of this class is considered a public API. All the methods
159 provided by the class are considered an implementation detail.
160 """
161
162 def __init__(self,
163 prog,
164 indent_increment=2,
165 max_help_position=24,
166 width=None):
167
168 # default setting for width
169 if width is None:
Berker Peksag74102c92018-07-25 18:23:44 +0300170 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
267 invocation_length = max([len(s) for s in invocations])
268 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
529 if action.help:
530 help_text = self._expand_help(action)
531 help_lines = self._split_lines(help_text, help_width)
532 parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
533 for line in help_lines[1:]:
534 parts.append('%*s%s\n' % (help_position, '', line))
535
536 # or add a newline if the description doesn't end with one
537 elif not action_header.endswith('\n'):
538 parts.append('\n')
539
540 # if there are any sub-actions, add their help as well
541 for subaction in self._iter_indented_subactions(action):
542 parts.append(self._format_action(subaction))
543
544 # return a single string
545 return self._join_parts(parts)
546
547 def _format_action_invocation(self, action):
548 if not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100549 default = self._get_default_metavar_for_positional(action)
550 metavar, = self._metavar_formatter(action, default)(1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000551 return metavar
552
553 else:
554 parts = []
555
556 # if the Optional doesn't take a value, format is:
557 # -s, --long
558 if action.nargs == 0:
559 parts.extend(action.option_strings)
560
561 # if the Optional takes a value, format is:
562 # -s ARGS, --long ARGS
563 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100564 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000565 args_string = self._format_args(action, default)
566 for option_string in action.option_strings:
567 parts.append('%s %s' % (option_string, args_string))
568
569 return ', '.join(parts)
570
571 def _metavar_formatter(self, action, default_metavar):
572 if action.metavar is not None:
573 result = action.metavar
574 elif action.choices is not None:
575 choice_strs = [str(choice) for choice in action.choices]
576 result = '{%s}' % ','.join(choice_strs)
577 else:
578 result = default_metavar
579
580 def format(tuple_size):
581 if isinstance(result, tuple):
582 return result
583 else:
584 return (result, ) * tuple_size
585 return format
586
587 def _format_args(self, action, default_metavar):
588 get_metavar = self._metavar_formatter(action, default_metavar)
589 if action.nargs is None:
590 result = '%s' % get_metavar(1)
591 elif action.nargs == OPTIONAL:
592 result = '[%s]' % get_metavar(1)
593 elif action.nargs == ZERO_OR_MORE:
594 result = '[%s [%s ...]]' % get_metavar(2)
595 elif action.nargs == ONE_OR_MORE:
596 result = '%s [%s ...]' % get_metavar(2)
597 elif action.nargs == REMAINDER:
598 result = '...'
599 elif action.nargs == PARSER:
600 result = '%s ...' % get_metavar(1)
R. David Murray0f6b9d22017-09-06 20:25:40 -0400601 elif action.nargs == SUPPRESS:
602 result = ''
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000603 else:
tmblweed4b3e9752019-08-01 21:57:13 -0700604 try:
605 formats = ['%s' for _ in range(action.nargs)]
606 except TypeError:
607 raise ValueError("invalid nargs value") from None
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000608 result = ' '.join(formats) % get_metavar(action.nargs)
609 return result
610
611 def _expand_help(self, action):
612 params = dict(vars(action), prog=self._prog)
613 for name in list(params):
614 if params[name] is SUPPRESS:
615 del params[name]
616 for name in list(params):
617 if hasattr(params[name], '__name__'):
618 params[name] = params[name].__name__
619 if params.get('choices') is not None:
620 choices_str = ', '.join([str(c) for c in params['choices']])
621 params['choices'] = choices_str
622 return self._get_help_string(action) % params
623
624 def _iter_indented_subactions(self, action):
625 try:
626 get_subactions = action._get_subactions
627 except AttributeError:
628 pass
629 else:
630 self._indent()
Philip Jenvey4993cc02012-10-01 12:53:43 -0700631 yield from get_subactions()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000632 self._dedent()
633
634 def _split_lines(self, text, width):
635 text = self._whitespace_matcher.sub(' ', text).strip()
Serhiy Storchaka81108372017-09-26 00:55:55 +0300636 # The textwrap module is used only for formatting help.
637 # Delay its import for speeding up the common usage of argparse.
638 import textwrap
639 return textwrap.wrap(text, width)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000640
641 def _fill_text(self, text, width, indent):
642 text = self._whitespace_matcher.sub(' ', text).strip()
Serhiy Storchaka81108372017-09-26 00:55:55 +0300643 import textwrap
644 return textwrap.fill(text, width,
645 initial_indent=indent,
646 subsequent_indent=indent)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000647
648 def _get_help_string(self, action):
649 return action.help
650
Steven Bethard0331e902011-03-26 14:48:04 +0100651 def _get_default_metavar_for_optional(self, action):
652 return action.dest.upper()
653
654 def _get_default_metavar_for_positional(self, action):
655 return action.dest
656
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000657
658class RawDescriptionHelpFormatter(HelpFormatter):
659 """Help message formatter which retains any formatting in descriptions.
660
661 Only the name of this class is considered a public API. All the methods
662 provided by the class are considered an implementation detail.
663 """
664
665 def _fill_text(self, text, width, indent):
Ezio Melottid8b509b2011-09-28 17:37:55 +0300666 return ''.join(indent + line for line in text.splitlines(keepends=True))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000667
668
669class RawTextHelpFormatter(RawDescriptionHelpFormatter):
670 """Help message formatter which retains formatting of all help text.
671
672 Only the name of this class is considered a public API. All the methods
673 provided by the class are considered an implementation detail.
674 """
675
676 def _split_lines(self, text, width):
677 return text.splitlines()
678
679
680class ArgumentDefaultsHelpFormatter(HelpFormatter):
681 """Help message formatter which adds default values to argument help.
682
683 Only the name of this class is considered a public API. All the methods
684 provided by the class are considered an implementation detail.
685 """
686
687 def _get_help_string(self, action):
688 help = action.help
689 if '%(default)' not in action.help:
690 if action.default is not SUPPRESS:
691 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
692 if action.option_strings or action.nargs in defaulting_nargs:
693 help += ' (default: %(default)s)'
694 return help
695
696
Steven Bethard0331e902011-03-26 14:48:04 +0100697class MetavarTypeHelpFormatter(HelpFormatter):
698 """Help message formatter which uses the argument 'type' as the default
699 metavar value (instead of the argument 'dest')
700
701 Only the name of this class is considered a public API. All the methods
702 provided by the class are considered an implementation detail.
703 """
704
705 def _get_default_metavar_for_optional(self, action):
706 return action.type.__name__
707
708 def _get_default_metavar_for_positional(self, action):
709 return action.type.__name__
710
711
712
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000713# =====================
714# Options and Arguments
715# =====================
716
717def _get_action_name(argument):
718 if argument is None:
719 return None
720 elif argument.option_strings:
721 return '/'.join(argument.option_strings)
722 elif argument.metavar not in (None, SUPPRESS):
723 return argument.metavar
724 elif argument.dest not in (None, SUPPRESS):
725 return argument.dest
726 else:
727 return None
728
729
730class ArgumentError(Exception):
731 """An error from creating or using an argument (optional or positional).
732
733 The string value of this exception is the message, augmented with
734 information about the argument that caused it.
735 """
736
737 def __init__(self, argument, message):
738 self.argument_name = _get_action_name(argument)
739 self.message = message
740
741 def __str__(self):
742 if self.argument_name is None:
743 format = '%(message)s'
744 else:
745 format = 'argument %(argument_name)s: %(message)s'
746 return format % dict(message=self.message,
747 argument_name=self.argument_name)
748
749
750class ArgumentTypeError(Exception):
751 """An error from trying to convert a command line string to a type."""
752 pass
753
754
755# ==============
756# Action classes
757# ==============
758
759class Action(_AttributeHolder):
760 """Information about how to convert command line strings to Python objects.
761
762 Action objects are used by an ArgumentParser to represent the information
763 needed to parse a single argument from one or more strings from the
764 command line. The keyword arguments to the Action constructor are also
765 all attributes of Action instances.
766
767 Keyword Arguments:
768
769 - option_strings -- A list of command-line option strings which
770 should be associated with this action.
771
772 - dest -- The name of the attribute to hold the created object(s)
773
774 - nargs -- The number of command-line arguments that should be
775 consumed. By default, one argument will be consumed and a single
776 value will be produced. Other values include:
777 - N (an integer) consumes N arguments (and produces a list)
778 - '?' consumes zero or one arguments
779 - '*' consumes zero or more arguments (and produces a list)
780 - '+' consumes one or more arguments (and produces a list)
781 Note that the difference between the default and nargs=1 is that
782 with the default, a single value will be produced, while with
783 nargs=1, a list containing a single value will be produced.
784
785 - const -- The value to be produced if the option is specified and the
786 option uses an action that takes no values.
787
788 - default -- The value to be produced if the option is not specified.
789
R David Murray15cd9a02012-07-21 17:04:25 -0400790 - type -- A callable that accepts a single string argument, and
791 returns the converted value. The standard Python types str, int,
792 float, and complex are useful examples of such callables. If None,
793 str is used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000794
795 - choices -- A container of values that should be allowed. If not None,
796 after a command-line argument has been converted to the appropriate
797 type, an exception will be raised if it is not a member of this
798 collection.
799
800 - required -- True if the action must always be specified at the
801 command line. This is only meaningful for optional command-line
802 arguments.
803
804 - help -- The help string describing the argument.
805
806 - metavar -- The name to be used for the option's argument with the
807 help string. If None, the 'dest' value will be used as the name.
808 """
809
810 def __init__(self,
811 option_strings,
812 dest,
813 nargs=None,
814 const=None,
815 default=None,
816 type=None,
817 choices=None,
818 required=False,
819 help=None,
820 metavar=None):
821 self.option_strings = option_strings
822 self.dest = dest
823 self.nargs = nargs
824 self.const = const
825 self.default = default
826 self.type = type
827 self.choices = choices
828 self.required = required
829 self.help = help
830 self.metavar = metavar
831
832 def _get_kwargs(self):
833 names = [
834 'option_strings',
835 'dest',
836 'nargs',
837 'const',
838 'default',
839 'type',
840 'choices',
841 'help',
842 'metavar',
843 ]
844 return [(name, getattr(self, name)) for name in names]
845
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200846 def format_usage(self):
847 return self.option_strings[0]
848
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000849 def __call__(self, parser, namespace, values, option_string=None):
850 raise NotImplementedError(_('.__call__() not defined'))
851
Rémi Lapeyre6a517c62019-09-13 12:17:43 +0200852class BooleanOptionalAction(Action):
853 def __init__(self,
854 option_strings,
855 dest,
856 const=None,
857 default=None,
858 type=None,
859 choices=None,
860 required=False,
861 help=None,
862 metavar=None):
863
864 _option_strings = []
865 for option_string in option_strings:
866 _option_strings.append(option_string)
867
868 if option_string.startswith('--'):
869 option_string = '--no-' + option_string[2:]
870 _option_strings.append(option_string)
871
872 if help is not None and default is not None:
873 help += f" (default: {default})"
874
875 super().__init__(
876 option_strings=_option_strings,
877 dest=dest,
878 nargs=0,
879 default=default,
880 type=type,
881 choices=choices,
882 required=required,
883 help=help,
884 metavar=metavar)
885
886 def __call__(self, parser, namespace, values, option_string=None):
887 if option_string in self.option_strings:
888 setattr(namespace, self.dest, not option_string.startswith('--no-'))
889
890 def format_usage(self):
891 return ' | '.join(self.option_strings)
892
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000893
894class _StoreAction(Action):
895
896 def __init__(self,
897 option_strings,
898 dest,
899 nargs=None,
900 const=None,
901 default=None,
902 type=None,
903 choices=None,
904 required=False,
905 help=None,
906 metavar=None):
907 if nargs == 0:
tmblweed4b3e9752019-08-01 21:57:13 -0700908 raise ValueError('nargs for store actions must be != 0; if you '
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000909 'have nothing to store, actions such as store '
910 'true or store const may be more appropriate')
911 if const is not None and nargs != OPTIONAL:
912 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
913 super(_StoreAction, self).__init__(
914 option_strings=option_strings,
915 dest=dest,
916 nargs=nargs,
917 const=const,
918 default=default,
919 type=type,
920 choices=choices,
921 required=required,
922 help=help,
923 metavar=metavar)
924
925 def __call__(self, parser, namespace, values, option_string=None):
926 setattr(namespace, self.dest, values)
927
928
929class _StoreConstAction(Action):
930
931 def __init__(self,
932 option_strings,
933 dest,
934 const,
935 default=None,
936 required=False,
937 help=None,
938 metavar=None):
939 super(_StoreConstAction, self).__init__(
940 option_strings=option_strings,
941 dest=dest,
942 nargs=0,
943 const=const,
944 default=default,
945 required=required,
946 help=help)
947
948 def __call__(self, parser, namespace, values, option_string=None):
949 setattr(namespace, self.dest, self.const)
950
951
952class _StoreTrueAction(_StoreConstAction):
953
954 def __init__(self,
955 option_strings,
956 dest,
957 default=False,
958 required=False,
959 help=None):
960 super(_StoreTrueAction, self).__init__(
961 option_strings=option_strings,
962 dest=dest,
963 const=True,
964 default=default,
965 required=required,
966 help=help)
967
968
969class _StoreFalseAction(_StoreConstAction):
970
971 def __init__(self,
972 option_strings,
973 dest,
974 default=True,
975 required=False,
976 help=None):
977 super(_StoreFalseAction, self).__init__(
978 option_strings=option_strings,
979 dest=dest,
980 const=False,
981 default=default,
982 required=required,
983 help=help)
984
985
986class _AppendAction(Action):
987
988 def __init__(self,
989 option_strings,
990 dest,
991 nargs=None,
992 const=None,
993 default=None,
994 type=None,
995 choices=None,
996 required=False,
997 help=None,
998 metavar=None):
999 if nargs == 0:
tmblweed4b3e9752019-08-01 21:57:13 -07001000 raise ValueError('nargs for append actions must be != 0; if arg '
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001001 'strings are not supplying the value to append, '
1002 'the append const action may be more appropriate')
1003 if const is not None and nargs != OPTIONAL:
1004 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
1005 super(_AppendAction, self).__init__(
1006 option_strings=option_strings,
1007 dest=dest,
1008 nargs=nargs,
1009 const=const,
1010 default=default,
1011 type=type,
1012 choices=choices,
1013 required=required,
1014 help=help,
1015 metavar=metavar)
1016
1017 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001018 items = getattr(namespace, self.dest, None)
1019 items = _copy_items(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001020 items.append(values)
1021 setattr(namespace, self.dest, items)
1022
1023
1024class _AppendConstAction(Action):
1025
1026 def __init__(self,
1027 option_strings,
1028 dest,
1029 const,
1030 default=None,
1031 required=False,
1032 help=None,
1033 metavar=None):
1034 super(_AppendConstAction, self).__init__(
1035 option_strings=option_strings,
1036 dest=dest,
1037 nargs=0,
1038 const=const,
1039 default=default,
1040 required=required,
1041 help=help,
1042 metavar=metavar)
1043
1044 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001045 items = getattr(namespace, self.dest, None)
1046 items = _copy_items(items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001047 items.append(self.const)
1048 setattr(namespace, self.dest, items)
1049
1050
1051class _CountAction(Action):
1052
1053 def __init__(self,
1054 option_strings,
1055 dest,
1056 default=None,
1057 required=False,
1058 help=None):
1059 super(_CountAction, self).__init__(
1060 option_strings=option_strings,
1061 dest=dest,
1062 nargs=0,
1063 default=default,
1064 required=required,
1065 help=help)
1066
1067 def __call__(self, parser, namespace, values, option_string=None):
Serhiy Storchaka81108372017-09-26 00:55:55 +03001068 count = getattr(namespace, self.dest, None)
1069 if count is None:
1070 count = 0
1071 setattr(namespace, self.dest, count + 1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001072
1073
1074class _HelpAction(Action):
1075
1076 def __init__(self,
1077 option_strings,
1078 dest=SUPPRESS,
1079 default=SUPPRESS,
1080 help=None):
1081 super(_HelpAction, self).__init__(
1082 option_strings=option_strings,
1083 dest=dest,
1084 default=default,
1085 nargs=0,
1086 help=help)
1087
1088 def __call__(self, parser, namespace, values, option_string=None):
1089 parser.print_help()
1090 parser.exit()
1091
1092
1093class _VersionAction(Action):
1094
1095 def __init__(self,
1096 option_strings,
1097 version=None,
1098 dest=SUPPRESS,
1099 default=SUPPRESS,
Steven Bethard50fe5932010-05-24 03:47:38 +00001100 help="show program's version number and exit"):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001101 super(_VersionAction, self).__init__(
1102 option_strings=option_strings,
1103 dest=dest,
1104 default=default,
1105 nargs=0,
1106 help=help)
1107 self.version = version
1108
1109 def __call__(self, parser, namespace, values, option_string=None):
1110 version = self.version
1111 if version is None:
1112 version = parser.version
1113 formatter = parser._get_formatter()
1114 formatter.add_text(version)
Eli Benderskycdac5512013-09-06 06:49:15 -07001115 parser._print_message(formatter.format_help(), _sys.stdout)
1116 parser.exit()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001117
1118
1119class _SubParsersAction(Action):
1120
1121 class _ChoicesPseudoAction(Action):
1122
Steven Bethardfd311a72010-12-18 11:19:23 +00001123 def __init__(self, name, aliases, help):
1124 metavar = dest = name
1125 if aliases:
1126 metavar += ' (%s)' % ', '.join(aliases)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001127 sup = super(_SubParsersAction._ChoicesPseudoAction, self)
Steven Bethardfd311a72010-12-18 11:19:23 +00001128 sup.__init__(option_strings=[], dest=dest, help=help,
1129 metavar=metavar)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001130
1131 def __init__(self,
1132 option_strings,
1133 prog,
1134 parser_class,
1135 dest=SUPPRESS,
Ned Deily8ebf5ce2018-05-23 21:55:15 -04001136 required=False,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001137 help=None,
1138 metavar=None):
1139
1140 self._prog_prefix = prog
1141 self._parser_class = parser_class
Raymond Hettinger05565ed2018-01-11 22:20:33 -08001142 self._name_parser_map = {}
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001143 self._choices_actions = []
1144
1145 super(_SubParsersAction, self).__init__(
1146 option_strings=option_strings,
1147 dest=dest,
1148 nargs=PARSER,
1149 choices=self._name_parser_map,
Anthony Sottileaaf6fc02017-09-20 14:35:27 -07001150 required=required,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001151 help=help,
1152 metavar=metavar)
1153
1154 def add_parser(self, name, **kwargs):
1155 # set prog from the existing prefix
1156 if kwargs.get('prog') is None:
1157 kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1158
Steven Bethardfd311a72010-12-18 11:19:23 +00001159 aliases = kwargs.pop('aliases', ())
1160
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001161 # create a pseudo-action to hold the choice help
1162 if 'help' in kwargs:
1163 help = kwargs.pop('help')
Steven Bethardfd311a72010-12-18 11:19:23 +00001164 choice_action = self._ChoicesPseudoAction(name, aliases, help)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001165 self._choices_actions.append(choice_action)
1166
1167 # create the parser and add it to the map
1168 parser = self._parser_class(**kwargs)
1169 self._name_parser_map[name] = parser
Steven Bethardfd311a72010-12-18 11:19:23 +00001170
1171 # make parser available under aliases also
1172 for alias in aliases:
1173 self._name_parser_map[alias] = parser
1174
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001175 return parser
1176
1177 def _get_subactions(self):
1178 return self._choices_actions
1179
1180 def __call__(self, parser, namespace, values, option_string=None):
1181 parser_name = values[0]
1182 arg_strings = values[1:]
1183
1184 # set the parser name if requested
1185 if self.dest is not SUPPRESS:
1186 setattr(namespace, self.dest, parser_name)
1187
1188 # select the parser
1189 try:
1190 parser = self._name_parser_map[parser_name]
1191 except KeyError:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001192 args = {'parser_name': parser_name,
1193 'choices': ', '.join(self._name_parser_map)}
1194 msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001195 raise ArgumentError(self, msg)
1196
1197 # parse all the remaining options into the namespace
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001198 # store any unrecognized options on the object, so that the top
1199 # level parser can decide what to do with them
R David Murray7570cbd2014-10-17 19:55:11 -04001200
1201 # In case this subparser defines new defaults, we parse them
1202 # in a new namespace object and then update the original
1203 # namespace for the relevant parts.
1204 subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
1205 for key, value in vars(subnamespace).items():
1206 setattr(namespace, key, value)
1207
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001208 if arg_strings:
1209 vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1210 getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001211
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001212class _ExtendAction(_AppendAction):
1213 def __call__(self, parser, namespace, values, option_string=None):
1214 items = getattr(namespace, self.dest, None)
1215 items = _copy_items(items)
1216 items.extend(values)
1217 setattr(namespace, self.dest, items)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001218
1219# ==============
1220# Type classes
1221# ==============
1222
1223class FileType(object):
1224 """Factory for creating file object types
1225
1226 Instances of FileType are typically passed as type= arguments to the
1227 ArgumentParser add_argument() method.
1228
1229 Keyword Arguments:
1230 - mode -- A string indicating how the file is to be opened. Accepts the
1231 same values as the builtin open() function.
1232 - bufsize -- The file's desired buffer size. Accepts the same values as
1233 the builtin open() function.
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001234 - encoding -- The file's encoding. Accepts the same values as the
Terry Jan Reedy8e7586b2013-03-11 18:38:13 -04001235 builtin open() function.
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001236 - errors -- A string indicating how encoding and decoding errors are to
1237 be handled. Accepts the same value as the builtin open() function.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001238 """
1239
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001240 def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001241 self._mode = mode
1242 self._bufsize = bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001243 self._encoding = encoding
1244 self._errors = errors
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001245
1246 def __call__(self, string):
1247 # the special argument "-" means sys.std{in,out}
1248 if string == '-':
1249 if 'r' in self._mode:
1250 return _sys.stdin
1251 elif 'w' in self._mode:
1252 return _sys.stdout
1253 else:
Éric Araujoa9c7a8f2010-12-03 19:19:17 +00001254 msg = _('argument "-" with mode %r') % self._mode
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001255 raise ValueError(msg)
1256
1257 # all other arguments are used as file names
Steven Bethardb0270112011-01-24 21:02:50 +00001258 try:
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001259 return open(string, self._mode, self._bufsize, self._encoding,
1260 self._errors)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001261 except OSError as e:
Jakub Kulík42671ae2019-09-13 11:25:32 +02001262 args = {'filename': string, 'error': e}
1263 message = _("can't open '%(filename)s': %(error)s")
1264 raise ArgumentTypeError(message % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001265
1266 def __repr__(self):
Steven Bethardb0270112011-01-24 21:02:50 +00001267 args = self._mode, self._bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001268 kwargs = [('encoding', self._encoding), ('errors', self._errors)]
1269 args_str = ', '.join([repr(arg) for arg in args if arg != -1] +
1270 ['%s=%r' % (kw, arg) for kw, arg in kwargs
1271 if arg is not None])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001272 return '%s(%s)' % (type(self).__name__, args_str)
1273
1274# ===========================
1275# Optional and Positional Parsing
1276# ===========================
1277
1278class Namespace(_AttributeHolder):
1279 """Simple object for storing attributes.
1280
1281 Implements equality by attribute names and values, and provides a simple
1282 string representation.
1283 """
1284
1285 def __init__(self, **kwargs):
1286 for name in kwargs:
1287 setattr(self, name, kwargs[name])
1288
1289 def __eq__(self, other):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07001290 if not isinstance(other, Namespace):
1291 return NotImplemented
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001292 return vars(self) == vars(other)
1293
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001294 def __contains__(self, key):
1295 return key in self.__dict__
1296
1297
1298class _ActionsContainer(object):
1299
1300 def __init__(self,
1301 description,
1302 prefix_chars,
1303 argument_default,
1304 conflict_handler):
1305 super(_ActionsContainer, self).__init__()
1306
1307 self.description = description
1308 self.argument_default = argument_default
1309 self.prefix_chars = prefix_chars
1310 self.conflict_handler = conflict_handler
1311
1312 # set up registries
1313 self._registries = {}
1314
1315 # register actions
1316 self.register('action', None, _StoreAction)
1317 self.register('action', 'store', _StoreAction)
1318 self.register('action', 'store_const', _StoreConstAction)
1319 self.register('action', 'store_true', _StoreTrueAction)
1320 self.register('action', 'store_false', _StoreFalseAction)
1321 self.register('action', 'append', _AppendAction)
1322 self.register('action', 'append_const', _AppendConstAction)
1323 self.register('action', 'count', _CountAction)
1324 self.register('action', 'help', _HelpAction)
1325 self.register('action', 'version', _VersionAction)
1326 self.register('action', 'parsers', _SubParsersAction)
Batuhan Taşkayaaa32a7e2019-05-21 20:47:42 +03001327 self.register('action', 'extend', _ExtendAction)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001328
1329 # raise an exception if the conflict handler is invalid
1330 self._get_handler()
1331
1332 # action storage
1333 self._actions = []
1334 self._option_string_actions = {}
1335
1336 # groups
1337 self._action_groups = []
1338 self._mutually_exclusive_groups = []
1339
1340 # defaults storage
1341 self._defaults = {}
1342
1343 # determines whether an "option" looks like a negative number
1344 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1345
1346 # whether or not there are any optionals that look like negative
1347 # numbers -- uses a list so it can be shared and edited
1348 self._has_negative_number_optionals = []
1349
1350 # ====================
1351 # Registration methods
1352 # ====================
1353 def register(self, registry_name, value, object):
1354 registry = self._registries.setdefault(registry_name, {})
1355 registry[value] = object
1356
1357 def _registry_get(self, registry_name, value, default=None):
1358 return self._registries[registry_name].get(value, default)
1359
1360 # ==================================
1361 # Namespace default accessor methods
1362 # ==================================
1363 def set_defaults(self, **kwargs):
1364 self._defaults.update(kwargs)
1365
1366 # if these defaults match any existing arguments, replace
1367 # the previous default on the object with the new one
1368 for action in self._actions:
1369 if action.dest in kwargs:
1370 action.default = kwargs[action.dest]
1371
1372 def get_default(self, dest):
1373 for action in self._actions:
1374 if action.dest == dest and action.default is not None:
1375 return action.default
1376 return self._defaults.get(dest, None)
1377
1378
1379 # =======================
1380 # Adding argument actions
1381 # =======================
1382 def add_argument(self, *args, **kwargs):
1383 """
1384 add_argument(dest, ..., name=value, ...)
1385 add_argument(option_string, option_string, ..., name=value, ...)
1386 """
1387
1388 # if no positional args are supplied or only one is supplied and
1389 # it doesn't look like an option string, parse a positional
1390 # argument
1391 chars = self.prefix_chars
1392 if not args or len(args) == 1 and args[0][0] not in chars:
1393 if args and 'dest' in kwargs:
1394 raise ValueError('dest supplied twice for positional argument')
1395 kwargs = self._get_positional_kwargs(*args, **kwargs)
1396
1397 # otherwise, we're adding an optional argument
1398 else:
1399 kwargs = self._get_optional_kwargs(*args, **kwargs)
1400
1401 # if no default was supplied, use the parser-level default
1402 if 'default' not in kwargs:
1403 dest = kwargs['dest']
1404 if dest in self._defaults:
1405 kwargs['default'] = self._defaults[dest]
1406 elif self.argument_default is not None:
1407 kwargs['default'] = self.argument_default
1408
1409 # create the action object, and add it to the parser
1410 action_class = self._pop_action_class(kwargs)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001411 if not callable(action_class):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001412 raise ValueError('unknown action "%s"' % (action_class,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001413 action = action_class(**kwargs)
1414
1415 # raise an error if the action type is not callable
1416 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001417 if not callable(type_func):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001418 raise ValueError('%r is not callable' % (type_func,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001419
zygocephalus03d58312019-06-07 23:08:36 +03001420 if type_func is FileType:
1421 raise ValueError('%r is a FileType class object, instance of it'
1422 ' must be passed' % (type_func,))
1423
Steven Bethard8d9a4622011-03-26 17:33:56 +01001424 # raise an error if the metavar does not match the type
1425 if hasattr(self, "_get_formatter"):
1426 try:
1427 self._get_formatter()._format_args(action, None)
1428 except TypeError:
1429 raise ValueError("length of metavar tuple does not match nargs")
1430
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001431 return self._add_action(action)
1432
1433 def add_argument_group(self, *args, **kwargs):
1434 group = _ArgumentGroup(self, *args, **kwargs)
1435 self._action_groups.append(group)
1436 return group
1437
1438 def add_mutually_exclusive_group(self, **kwargs):
1439 group = _MutuallyExclusiveGroup(self, **kwargs)
1440 self._mutually_exclusive_groups.append(group)
1441 return group
1442
1443 def _add_action(self, action):
1444 # resolve any conflicts
1445 self._check_conflict(action)
1446
1447 # add to actions list
1448 self._actions.append(action)
1449 action.container = self
1450
1451 # index the action by any option strings it has
1452 for option_string in action.option_strings:
1453 self._option_string_actions[option_string] = action
1454
1455 # set the flag if any option strings look like negative numbers
1456 for option_string in action.option_strings:
1457 if self._negative_number_matcher.match(option_string):
1458 if not self._has_negative_number_optionals:
1459 self._has_negative_number_optionals.append(True)
1460
1461 # return the created action
1462 return action
1463
1464 def _remove_action(self, action):
1465 self._actions.remove(action)
1466
1467 def _add_container_actions(self, container):
1468 # collect groups by titles
1469 title_group_map = {}
1470 for group in self._action_groups:
1471 if group.title in title_group_map:
1472 msg = _('cannot merge actions - two groups are named %r')
1473 raise ValueError(msg % (group.title))
1474 title_group_map[group.title] = group
1475
1476 # map each action to its group
1477 group_map = {}
1478 for group in container._action_groups:
1479
1480 # if a group with the title exists, use that, otherwise
1481 # create a new group matching the container's group
1482 if group.title not in title_group_map:
1483 title_group_map[group.title] = self.add_argument_group(
1484 title=group.title,
1485 description=group.description,
1486 conflict_handler=group.conflict_handler)
1487
1488 # map the actions to their new group
1489 for action in group._group_actions:
1490 group_map[action] = title_group_map[group.title]
1491
1492 # add container's mutually exclusive groups
1493 # NOTE: if add_mutually_exclusive_group ever gains title= and
1494 # description= then this code will need to be expanded as above
1495 for group in container._mutually_exclusive_groups:
1496 mutex_group = self.add_mutually_exclusive_group(
1497 required=group.required)
1498
1499 # map the actions to their new mutex group
1500 for action in group._group_actions:
1501 group_map[action] = mutex_group
1502
1503 # add all actions to this container or their group
1504 for action in container._actions:
1505 group_map.get(action, self)._add_action(action)
1506
1507 def _get_positional_kwargs(self, dest, **kwargs):
1508 # make sure required is not specified
1509 if 'required' in kwargs:
1510 msg = _("'required' is an invalid argument for positionals")
1511 raise TypeError(msg)
1512
1513 # mark positional arguments as required if at least one is
1514 # always required
1515 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1516 kwargs['required'] = True
1517 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1518 kwargs['required'] = True
1519
1520 # return the keyword arguments with no option strings
1521 return dict(kwargs, dest=dest, option_strings=[])
1522
1523 def _get_optional_kwargs(self, *args, **kwargs):
1524 # determine short and long option strings
1525 option_strings = []
1526 long_option_strings = []
1527 for option_string in args:
1528 # error on strings that don't start with an appropriate prefix
1529 if not option_string[0] in self.prefix_chars:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001530 args = {'option': option_string,
1531 'prefix_chars': self.prefix_chars}
1532 msg = _('invalid option string %(option)r: '
1533 'must start with a character %(prefix_chars)r')
1534 raise ValueError(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001535
1536 # strings starting with two prefix characters are long options
1537 option_strings.append(option_string)
Shashank Parekhb9600b02019-06-21 08:32:22 +05301538 if len(option_string) > 1 and option_string[1] in self.prefix_chars:
1539 long_option_strings.append(option_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001540
1541 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1542 dest = kwargs.pop('dest', None)
1543 if dest is None:
1544 if long_option_strings:
1545 dest_option_string = long_option_strings[0]
1546 else:
1547 dest_option_string = option_strings[0]
1548 dest = dest_option_string.lstrip(self.prefix_chars)
1549 if not dest:
1550 msg = _('dest= is required for options like %r')
1551 raise ValueError(msg % option_string)
1552 dest = dest.replace('-', '_')
1553
1554 # return the updated keyword arguments
1555 return dict(kwargs, dest=dest, option_strings=option_strings)
1556
1557 def _pop_action_class(self, kwargs, default=None):
1558 action = kwargs.pop('action', default)
1559 return self._registry_get('action', action, action)
1560
1561 def _get_handler(self):
1562 # determine function from conflict handler string
1563 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1564 try:
1565 return getattr(self, handler_func_name)
1566 except AttributeError:
1567 msg = _('invalid conflict_resolution value: %r')
1568 raise ValueError(msg % self.conflict_handler)
1569
1570 def _check_conflict(self, action):
1571
1572 # find all options that conflict with this option
1573 confl_optionals = []
1574 for option_string in action.option_strings:
1575 if option_string in self._option_string_actions:
1576 confl_optional = self._option_string_actions[option_string]
1577 confl_optionals.append((option_string, confl_optional))
1578
1579 # resolve any conflicts
1580 if confl_optionals:
1581 conflict_handler = self._get_handler()
1582 conflict_handler(action, confl_optionals)
1583
1584 def _handle_conflict_error(self, action, conflicting_actions):
Éric Araujo12159152010-12-04 17:31:49 +00001585 message = ngettext('conflicting option string: %s',
1586 'conflicting option strings: %s',
1587 len(conflicting_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001588 conflict_string = ', '.join([option_string
1589 for option_string, action
1590 in conflicting_actions])
1591 raise ArgumentError(action, message % conflict_string)
1592
1593 def _handle_conflict_resolve(self, action, conflicting_actions):
1594
1595 # remove all conflicting options
1596 for option_string, action in conflicting_actions:
1597
1598 # remove the conflicting option
1599 action.option_strings.remove(option_string)
1600 self._option_string_actions.pop(option_string, None)
1601
1602 # if the option now has no option string, remove it from the
1603 # container holding it
1604 if not action.option_strings:
1605 action.container._remove_action(action)
1606
1607
1608class _ArgumentGroup(_ActionsContainer):
1609
1610 def __init__(self, container, title=None, description=None, **kwargs):
1611 # add any missing keyword arguments by checking the container
1612 update = kwargs.setdefault
1613 update('conflict_handler', container.conflict_handler)
1614 update('prefix_chars', container.prefix_chars)
1615 update('argument_default', container.argument_default)
1616 super_init = super(_ArgumentGroup, self).__init__
1617 super_init(description=description, **kwargs)
1618
1619 # group attributes
1620 self.title = title
1621 self._group_actions = []
1622
1623 # share most attributes with the container
1624 self._registries = container._registries
1625 self._actions = container._actions
1626 self._option_string_actions = container._option_string_actions
1627 self._defaults = container._defaults
1628 self._has_negative_number_optionals = \
1629 container._has_negative_number_optionals
Georg Brandl0f6b47a2011-01-30 12:19:35 +00001630 self._mutually_exclusive_groups = container._mutually_exclusive_groups
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001631
1632 def _add_action(self, action):
1633 action = super(_ArgumentGroup, self)._add_action(action)
1634 self._group_actions.append(action)
1635 return action
1636
1637 def _remove_action(self, action):
1638 super(_ArgumentGroup, self)._remove_action(action)
1639 self._group_actions.remove(action)
1640
1641
1642class _MutuallyExclusiveGroup(_ArgumentGroup):
1643
1644 def __init__(self, container, required=False):
1645 super(_MutuallyExclusiveGroup, self).__init__(container)
1646 self.required = required
1647 self._container = container
1648
1649 def _add_action(self, action):
1650 if action.required:
1651 msg = _('mutually exclusive arguments must be optional')
1652 raise ValueError(msg)
1653 action = self._container._add_action(action)
1654 self._group_actions.append(action)
1655 return action
1656
1657 def _remove_action(self, action):
1658 self._container._remove_action(action)
1659 self._group_actions.remove(action)
1660
1661
1662class ArgumentParser(_AttributeHolder, _ActionsContainer):
1663 """Object for parsing command line strings into Python objects.
1664
1665 Keyword Arguments:
1666 - prog -- The name of the program (default: sys.argv[0])
1667 - usage -- A usage message (default: auto-generated from arguments)
1668 - description -- A description of what the program does
1669 - epilog -- Text following the argument descriptions
1670 - parents -- Parsers whose arguments should be copied into this one
1671 - formatter_class -- HelpFormatter class for printing help messages
1672 - prefix_chars -- Characters that prefix optional arguments
1673 - fromfile_prefix_chars -- Characters that prefix files containing
1674 additional arguments
1675 - argument_default -- The default value for all arguments
1676 - conflict_handler -- String indicating how to handle conflicts
1677 - add_help -- Add a -h/-help option
Berker Peksag8089cd62015-02-14 01:39:17 +02001678 - allow_abbrev -- Allow long options to be abbreviated unambiguously
Hai Shif5456382019-09-12 05:56:05 -05001679 - exit_on_error -- Determines whether or not ArgumentParser exits with
1680 error info when an error occurs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001681 """
1682
1683 def __init__(self,
1684 prog=None,
1685 usage=None,
1686 description=None,
1687 epilog=None,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001688 parents=[],
1689 formatter_class=HelpFormatter,
1690 prefix_chars='-',
1691 fromfile_prefix_chars=None,
1692 argument_default=None,
1693 conflict_handler='error',
Berker Peksag8089cd62015-02-14 01:39:17 +02001694 add_help=True,
Hai Shif5456382019-09-12 05:56:05 -05001695 allow_abbrev=True,
1696 exit_on_error=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001697
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001698 superinit = super(ArgumentParser, self).__init__
1699 superinit(description=description,
1700 prefix_chars=prefix_chars,
1701 argument_default=argument_default,
1702 conflict_handler=conflict_handler)
1703
1704 # default setting for prog
1705 if prog is None:
1706 prog = _os.path.basename(_sys.argv[0])
1707
1708 self.prog = prog
1709 self.usage = usage
1710 self.epilog = epilog
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001711 self.formatter_class = formatter_class
1712 self.fromfile_prefix_chars = fromfile_prefix_chars
1713 self.add_help = add_help
Berker Peksag8089cd62015-02-14 01:39:17 +02001714 self.allow_abbrev = allow_abbrev
Hai Shif5456382019-09-12 05:56:05 -05001715 self.exit_on_error = exit_on_error
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001716
1717 add_group = self.add_argument_group
1718 self._positionals = add_group(_('positional arguments'))
1719 self._optionals = add_group(_('optional arguments'))
1720 self._subparsers = None
1721
1722 # register types
1723 def identity(string):
1724 return string
1725 self.register('type', None, identity)
1726
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001727 # add help argument if necessary
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001728 # (using explicit default to override global argument_default)
R. David Murray88c49fe2010-08-03 17:56:09 +00001729 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001730 if self.add_help:
1731 self.add_argument(
R. David Murray88c49fe2010-08-03 17:56:09 +00001732 default_prefix+'h', default_prefix*2+'help',
1733 action='help', default=SUPPRESS,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001734 help=_('show this help message and exit'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001735
1736 # add parent arguments and defaults
1737 for parent in parents:
1738 self._add_container_actions(parent)
1739 try:
1740 defaults = parent._defaults
1741 except AttributeError:
1742 pass
1743 else:
1744 self._defaults.update(defaults)
1745
1746 # =======================
1747 # Pretty __repr__ methods
1748 # =======================
1749 def _get_kwargs(self):
1750 names = [
1751 'prog',
1752 'usage',
1753 'description',
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001754 'formatter_class',
1755 'conflict_handler',
1756 'add_help',
1757 ]
1758 return [(name, getattr(self, name)) for name in names]
1759
1760 # ==================================
1761 # Optional/Positional adding methods
1762 # ==================================
1763 def add_subparsers(self, **kwargs):
1764 if self._subparsers is not None:
1765 self.error(_('cannot have multiple subparser arguments'))
1766
1767 # add the parser class to the arguments if it's not present
1768 kwargs.setdefault('parser_class', type(self))
1769
1770 if 'title' in kwargs or 'description' in kwargs:
1771 title = _(kwargs.pop('title', 'subcommands'))
1772 description = _(kwargs.pop('description', None))
1773 self._subparsers = self.add_argument_group(title, description)
1774 else:
1775 self._subparsers = self._positionals
1776
1777 # prog defaults to the usage message of this parser, skipping
1778 # optional arguments and with no "usage:" prefix
1779 if kwargs.get('prog') is None:
1780 formatter = self._get_formatter()
1781 positionals = self._get_positional_actions()
1782 groups = self._mutually_exclusive_groups
1783 formatter.add_usage(self.usage, positionals, groups, '')
1784 kwargs['prog'] = formatter.format_help().strip()
1785
1786 # create the parsers action and add it to the positionals list
1787 parsers_class = self._pop_action_class(kwargs, 'parsers')
1788 action = parsers_class(option_strings=[], **kwargs)
1789 self._subparsers._add_action(action)
1790
1791 # return the created parsers action
1792 return action
1793
1794 def _add_action(self, action):
1795 if action.option_strings:
1796 self._optionals._add_action(action)
1797 else:
1798 self._positionals._add_action(action)
1799 return action
1800
1801 def _get_optional_actions(self):
1802 return [action
1803 for action in self._actions
1804 if action.option_strings]
1805
1806 def _get_positional_actions(self):
1807 return [action
1808 for action in self._actions
1809 if not action.option_strings]
1810
1811 # =====================================
1812 # Command line argument parsing methods
1813 # =====================================
1814 def parse_args(self, args=None, namespace=None):
1815 args, argv = self.parse_known_args(args, namespace)
1816 if argv:
1817 msg = _('unrecognized arguments: %s')
1818 self.error(msg % ' '.join(argv))
1819 return args
1820
1821 def parse_known_args(self, args=None, namespace=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001822 if args is None:
R David Murrayb5228282012-09-08 12:08:01 -04001823 # args default to the system args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001824 args = _sys.argv[1:]
R David Murrayb5228282012-09-08 12:08:01 -04001825 else:
1826 # make sure that args are mutable
1827 args = list(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001828
1829 # default Namespace built from parser defaults
1830 if namespace is None:
1831 namespace = Namespace()
1832
1833 # add any action defaults that aren't present
1834 for action in self._actions:
1835 if action.dest is not SUPPRESS:
1836 if not hasattr(namespace, action.dest):
1837 if action.default is not SUPPRESS:
R David Murray6fb8fb12012-08-31 22:45:20 -04001838 setattr(namespace, action.dest, action.default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001839
1840 # add any parser defaults that aren't present
1841 for dest in self._defaults:
1842 if not hasattr(namespace, dest):
1843 setattr(namespace, dest, self._defaults[dest])
1844
1845 # parse the arguments and exit if there are any errors
Hai Shif5456382019-09-12 05:56:05 -05001846 if self.exit_on_error:
1847 try:
1848 namespace, args = self._parse_known_args(args, namespace)
1849 except ArgumentError:
1850 err = _sys.exc_info()[1]
1851 self.error(str(err))
1852 else:
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001853 namespace, args = self._parse_known_args(args, namespace)
Hai Shif5456382019-09-12 05:56:05 -05001854
1855 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1856 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1857 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1858 return namespace, args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001859
1860 def _parse_known_args(self, arg_strings, namespace):
1861 # replace arg strings that are file references
1862 if self.fromfile_prefix_chars is not None:
1863 arg_strings = self._read_args_from_files(arg_strings)
1864
1865 # map all mutually exclusive arguments to the other arguments
1866 # they can't occur with
1867 action_conflicts = {}
1868 for mutex_group in self._mutually_exclusive_groups:
1869 group_actions = mutex_group._group_actions
1870 for i, mutex_action in enumerate(mutex_group._group_actions):
1871 conflicts = action_conflicts.setdefault(mutex_action, [])
1872 conflicts.extend(group_actions[:i])
1873 conflicts.extend(group_actions[i + 1:])
1874
1875 # find all option indices, and determine the arg_string_pattern
1876 # which has an 'O' if there is an option at an index,
1877 # an 'A' if there is an argument, or a '-' if there is a '--'
1878 option_string_indices = {}
1879 arg_string_pattern_parts = []
1880 arg_strings_iter = iter(arg_strings)
1881 for i, arg_string in enumerate(arg_strings_iter):
1882
1883 # all args after -- are non-options
1884 if arg_string == '--':
1885 arg_string_pattern_parts.append('-')
1886 for arg_string in arg_strings_iter:
1887 arg_string_pattern_parts.append('A')
1888
1889 # otherwise, add the arg to the arg strings
1890 # and note the index if it was an option
1891 else:
1892 option_tuple = self._parse_optional(arg_string)
1893 if option_tuple is None:
1894 pattern = 'A'
1895 else:
1896 option_string_indices[i] = option_tuple
1897 pattern = 'O'
1898 arg_string_pattern_parts.append(pattern)
1899
1900 # join the pieces together to form the pattern
1901 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1902
1903 # converts arg strings to the appropriate and then takes the action
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00001904 seen_actions = set()
1905 seen_non_default_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001906
1907 def take_action(action, argument_strings, option_string=None):
1908 seen_actions.add(action)
1909 argument_values = self._get_values(action, argument_strings)
1910
1911 # error if this argument is not allowed with other previously
1912 # seen arguments, assuming that actions that use the default
1913 # value don't really count as "present"
1914 if argument_values is not action.default:
1915 seen_non_default_actions.add(action)
1916 for conflict_action in action_conflicts.get(action, []):
1917 if conflict_action in seen_non_default_actions:
1918 msg = _('not allowed with argument %s')
1919 action_name = _get_action_name(conflict_action)
1920 raise ArgumentError(action, msg % action_name)
1921
1922 # take the action if we didn't receive a SUPPRESS value
1923 # (e.g. from a default)
1924 if argument_values is not SUPPRESS:
1925 action(self, namespace, argument_values, option_string)
1926
1927 # function to convert arg_strings into an optional action
1928 def consume_optional(start_index):
1929
1930 # get the optional identified at this index
1931 option_tuple = option_string_indices[start_index]
1932 action, option_string, explicit_arg = option_tuple
1933
1934 # identify additional optionals in the same arg string
1935 # (e.g. -xyz is the same as -x -y -z if no args are required)
1936 match_argument = self._match_argument
1937 action_tuples = []
1938 while True:
1939
1940 # if we found no optional action, skip it
1941 if action is None:
1942 extras.append(arg_strings[start_index])
1943 return start_index + 1
1944
1945 # if there is an explicit argument, try to match the
1946 # optional's string arguments to only this
1947 if explicit_arg is not None:
1948 arg_count = match_argument(action, 'A')
1949
1950 # if the action is a single-dash option and takes no
1951 # arguments, try to parse more single-dash options out
1952 # of the tail of the option string
1953 chars = self.prefix_chars
1954 if arg_count == 0 and option_string[1] not in chars:
1955 action_tuples.append((action, [], option_string))
Steven Bethard1ca45a52010-11-01 15:57:36 +00001956 char = option_string[0]
1957 option_string = char + explicit_arg[0]
1958 new_explicit_arg = explicit_arg[1:] or None
1959 optionals_map = self._option_string_actions
1960 if option_string in optionals_map:
1961 action = optionals_map[option_string]
1962 explicit_arg = new_explicit_arg
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001963 else:
1964 msg = _('ignored explicit argument %r')
1965 raise ArgumentError(action, msg % explicit_arg)
1966
1967 # if the action expect exactly one argument, we've
1968 # successfully matched the option; exit the loop
1969 elif arg_count == 1:
1970 stop = start_index + 1
1971 args = [explicit_arg]
1972 action_tuples.append((action, args, option_string))
1973 break
1974
1975 # error if a double-dash option did not use the
1976 # explicit argument
1977 else:
1978 msg = _('ignored explicit argument %r')
1979 raise ArgumentError(action, msg % explicit_arg)
1980
1981 # if there is no explicit argument, try to match the
1982 # optional's string arguments with the following strings
1983 # if successful, exit the loop
1984 else:
1985 start = start_index + 1
1986 selected_patterns = arg_strings_pattern[start:]
1987 arg_count = match_argument(action, selected_patterns)
1988 stop = start + arg_count
1989 args = arg_strings[start:stop]
1990 action_tuples.append((action, args, option_string))
1991 break
1992
1993 # add the Optional to the list and return the index at which
1994 # the Optional's string args stopped
1995 assert action_tuples
1996 for action, args, option_string in action_tuples:
1997 take_action(action, args, option_string)
1998 return stop
1999
2000 # the list of Positionals left to be parsed; this is modified
2001 # by consume_positionals()
2002 positionals = self._get_positional_actions()
2003
2004 # function to convert arg_strings into positional actions
2005 def consume_positionals(start_index):
2006 # match as many Positionals as possible
2007 match_partial = self._match_arguments_partial
2008 selected_pattern = arg_strings_pattern[start_index:]
2009 arg_counts = match_partial(positionals, selected_pattern)
2010
2011 # slice off the appropriate arg strings for each Positional
2012 # and add the Positional and its args to the list
2013 for action, arg_count in zip(positionals, arg_counts):
2014 args = arg_strings[start_index: start_index + arg_count]
2015 start_index += arg_count
2016 take_action(action, args)
2017
2018 # slice off the Positionals that we just parsed and return the
2019 # index at which the Positionals' string args stopped
2020 positionals[:] = positionals[len(arg_counts):]
2021 return start_index
2022
2023 # consume Positionals and Optionals alternately, until we have
2024 # passed the last option string
2025 extras = []
2026 start_index = 0
2027 if option_string_indices:
2028 max_option_string_index = max(option_string_indices)
2029 else:
2030 max_option_string_index = -1
2031 while start_index <= max_option_string_index:
2032
2033 # consume any Positionals preceding the next option
2034 next_option_string_index = min([
2035 index
2036 for index in option_string_indices
2037 if index >= start_index])
2038 if start_index != next_option_string_index:
2039 positionals_end_index = consume_positionals(start_index)
2040
2041 # only try to parse the next optional if we didn't consume
2042 # the option string during the positionals parsing
2043 if positionals_end_index > start_index:
2044 start_index = positionals_end_index
2045 continue
2046 else:
2047 start_index = positionals_end_index
2048
2049 # if we consumed all the positionals we could and we're not
2050 # at the index of an option string, there were extra arguments
2051 if start_index not in option_string_indices:
2052 strings = arg_strings[start_index:next_option_string_index]
2053 extras.extend(strings)
2054 start_index = next_option_string_index
2055
2056 # consume the next optional and any arguments for it
2057 start_index = consume_optional(start_index)
2058
2059 # consume any positionals following the last Optional
2060 stop_index = consume_positionals(start_index)
2061
2062 # if we didn't consume all the argument strings, there were extras
2063 extras.extend(arg_strings[stop_index:])
2064
R David Murray64b0ef12012-08-31 23:09:34 -04002065 # make sure all required actions were present and also convert
2066 # action defaults which were not given as arguments
2067 required_actions = []
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002068 for action in self._actions:
R David Murray6fb8fb12012-08-31 22:45:20 -04002069 if action not in seen_actions:
2070 if action.required:
R David Murray64b0ef12012-08-31 23:09:34 -04002071 required_actions.append(_get_action_name(action))
R David Murray6fb8fb12012-08-31 22:45:20 -04002072 else:
2073 # Convert action default now instead of doing it before
2074 # parsing arguments to avoid calling convert functions
2075 # twice (which may fail) if the argument was given, but
2076 # only if it was defined already in the namespace
2077 if (action.default is not None and
Barry Warsawd89774e2012-09-12 15:31:38 -04002078 isinstance(action.default, str) and
R David Murray64b0ef12012-08-31 23:09:34 -04002079 hasattr(namespace, action.dest) and
2080 action.default is getattr(namespace, action.dest)):
R David Murray6fb8fb12012-08-31 22:45:20 -04002081 setattr(namespace, action.dest,
2082 self._get_value(action, action.default))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002083
R David Murrayf97c59a2011-06-09 12:34:07 -04002084 if required_actions:
2085 self.error(_('the following arguments are required: %s') %
2086 ', '.join(required_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002087
2088 # make sure all required groups had one option present
2089 for group in self._mutually_exclusive_groups:
2090 if group.required:
2091 for action in group._group_actions:
2092 if action in seen_non_default_actions:
2093 break
2094
2095 # if no actions were used, report the error
2096 else:
2097 names = [_get_action_name(action)
2098 for action in group._group_actions
2099 if action.help is not SUPPRESS]
2100 msg = _('one of the arguments %s is required')
2101 self.error(msg % ' '.join(names))
2102
2103 # return the updated namespace and the extra arguments
2104 return namespace, extras
2105
2106 def _read_args_from_files(self, arg_strings):
2107 # expand arguments referencing files
2108 new_arg_strings = []
2109 for arg_string in arg_strings:
2110
2111 # for regular arguments, just add them back into the list
R David Murrayb94082a2012-07-21 22:20:11 -04002112 if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002113 new_arg_strings.append(arg_string)
2114
2115 # replace arguments referencing files with the file content
2116 else:
2117 try:
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01002118 with open(arg_string[1:]) as args_file:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002119 arg_strings = []
2120 for arg_line in args_file.read().splitlines():
2121 for arg in self.convert_arg_line_to_args(arg_line):
2122 arg_strings.append(arg)
2123 arg_strings = self._read_args_from_files(arg_strings)
2124 new_arg_strings.extend(arg_strings)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002125 except OSError:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002126 err = _sys.exc_info()[1]
2127 self.error(str(err))
2128
2129 # return the modified argument list
2130 return new_arg_strings
2131
2132 def convert_arg_line_to_args(self, arg_line):
2133 return [arg_line]
2134
2135 def _match_argument(self, action, arg_strings_pattern):
2136 # match the pattern for this action to the arg strings
2137 nargs_pattern = self._get_nargs_pattern(action)
2138 match = _re.match(nargs_pattern, arg_strings_pattern)
2139
2140 # raise an exception if we weren't able to find a match
2141 if match is None:
2142 nargs_errors = {
2143 None: _('expected one argument'),
2144 OPTIONAL: _('expected at most one argument'),
2145 ONE_OR_MORE: _('expected at least one argument'),
2146 }
Éric Araujo12159152010-12-04 17:31:49 +00002147 default = ngettext('expected %s argument',
2148 'expected %s arguments',
2149 action.nargs) % action.nargs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002150 msg = nargs_errors.get(action.nargs, default)
2151 raise ArgumentError(action, msg)
2152
2153 # return the number of arguments matched
2154 return len(match.group(1))
2155
2156 def _match_arguments_partial(self, actions, arg_strings_pattern):
2157 # progressively shorten the actions list by slicing off the
2158 # final actions until we find a match
2159 result = []
2160 for i in range(len(actions), 0, -1):
2161 actions_slice = actions[:i]
2162 pattern = ''.join([self._get_nargs_pattern(action)
2163 for action in actions_slice])
2164 match = _re.match(pattern, arg_strings_pattern)
2165 if match is not None:
2166 result.extend([len(string) for string in match.groups()])
2167 break
2168
2169 # return the list of arg string counts
2170 return result
2171
2172 def _parse_optional(self, arg_string):
2173 # if it's an empty string, it was meant to be a positional
2174 if not arg_string:
2175 return None
2176
2177 # if it doesn't start with a prefix, it was meant to be positional
2178 if not arg_string[0] in self.prefix_chars:
2179 return None
2180
2181 # if the option string is present in the parser, return the action
2182 if arg_string in self._option_string_actions:
2183 action = self._option_string_actions[arg_string]
2184 return action, arg_string, None
2185
2186 # if it's just a single character, it was meant to be positional
2187 if len(arg_string) == 1:
2188 return None
2189
2190 # if the option string before the "=" is present, return the action
2191 if '=' in arg_string:
2192 option_string, explicit_arg = arg_string.split('=', 1)
2193 if option_string in self._option_string_actions:
2194 action = self._option_string_actions[option_string]
2195 return action, option_string, explicit_arg
2196
Zac Hatfield-Doddsdffca9e2019-07-14 00:35:58 -05002197 if self.allow_abbrev or not arg_string.startswith('--'):
Berker Peksag8089cd62015-02-14 01:39:17 +02002198 # search through all possible prefixes of the option string
2199 # and all actions in the parser for possible interpretations
2200 option_tuples = self._get_option_tuples(arg_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002201
Berker Peksag8089cd62015-02-14 01:39:17 +02002202 # if multiple actions match, the option string was ambiguous
2203 if len(option_tuples) > 1:
2204 options = ', '.join([option_string
2205 for action, option_string, explicit_arg in option_tuples])
2206 args = {'option': arg_string, 'matches': options}
2207 msg = _('ambiguous option: %(option)s could match %(matches)s')
2208 self.error(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002209
Berker Peksag8089cd62015-02-14 01:39:17 +02002210 # if exactly one action matched, this segmentation is good,
2211 # so return the parsed action
2212 elif len(option_tuples) == 1:
2213 option_tuple, = option_tuples
2214 return option_tuple
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002215
2216 # if it was not found as an option, but it looks like a negative
2217 # number, it was meant to be positional
2218 # unless there are negative-number-like options
2219 if self._negative_number_matcher.match(arg_string):
2220 if not self._has_negative_number_optionals:
2221 return None
2222
2223 # if it contains a space, it was meant to be a positional
2224 if ' ' in arg_string:
2225 return None
2226
2227 # it was meant to be an optional but there is no such option
2228 # in this parser (though it might be a valid option in a subparser)
2229 return None, arg_string, None
2230
2231 def _get_option_tuples(self, option_string):
2232 result = []
2233
2234 # option strings starting with two prefix characters are only
2235 # split at the '='
2236 chars = self.prefix_chars
2237 if option_string[0] in chars and option_string[1] in chars:
2238 if '=' in option_string:
2239 option_prefix, explicit_arg = option_string.split('=', 1)
2240 else:
2241 option_prefix = option_string
2242 explicit_arg = None
2243 for option_string in self._option_string_actions:
2244 if option_string.startswith(option_prefix):
2245 action = self._option_string_actions[option_string]
2246 tup = action, option_string, explicit_arg
2247 result.append(tup)
2248
2249 # single character options can be concatenated with their arguments
2250 # but multiple character options always have to have their argument
2251 # separate
2252 elif option_string[0] in chars and option_string[1] not in chars:
2253 option_prefix = option_string
2254 explicit_arg = None
2255 short_option_prefix = option_string[:2]
2256 short_explicit_arg = option_string[2:]
2257
2258 for option_string in self._option_string_actions:
2259 if option_string == short_option_prefix:
2260 action = self._option_string_actions[option_string]
2261 tup = action, option_string, short_explicit_arg
2262 result.append(tup)
2263 elif option_string.startswith(option_prefix):
2264 action = self._option_string_actions[option_string]
2265 tup = action, option_string, explicit_arg
2266 result.append(tup)
2267
2268 # shouldn't ever get here
2269 else:
2270 self.error(_('unexpected option string: %s') % option_string)
2271
2272 # return the collected option tuples
2273 return result
2274
2275 def _get_nargs_pattern(self, action):
2276 # in all examples below, we have to allow for '--' args
2277 # which are represented as '-' in the pattern
2278 nargs = action.nargs
2279
2280 # the default (None) is assumed to be a single argument
2281 if nargs is None:
2282 nargs_pattern = '(-*A-*)'
2283
2284 # allow zero or one arguments
2285 elif nargs == OPTIONAL:
2286 nargs_pattern = '(-*A?-*)'
2287
2288 # allow zero or more arguments
2289 elif nargs == ZERO_OR_MORE:
2290 nargs_pattern = '(-*[A-]*)'
2291
2292 # allow one or more arguments
2293 elif nargs == ONE_OR_MORE:
2294 nargs_pattern = '(-*A[A-]*)'
2295
2296 # allow any number of options or arguments
2297 elif nargs == REMAINDER:
2298 nargs_pattern = '([-AO]*)'
2299
2300 # allow one argument followed by any number of options or arguments
2301 elif nargs == PARSER:
2302 nargs_pattern = '(-*A[-AO]*)'
2303
R. David Murray0f6b9d22017-09-06 20:25:40 -04002304 # suppress action, like nargs=0
2305 elif nargs == SUPPRESS:
2306 nargs_pattern = '(-*-*)'
2307
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002308 # all others should be integers
2309 else:
2310 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2311
2312 # if this is an optional action, -- is not allowed
2313 if action.option_strings:
2314 nargs_pattern = nargs_pattern.replace('-*', '')
2315 nargs_pattern = nargs_pattern.replace('-', '')
2316
2317 # return the pattern
2318 return nargs_pattern
2319
2320 # ========================
R. David Murray0f6b9d22017-09-06 20:25:40 -04002321 # Alt command line argument parsing, allowing free intermix
2322 # ========================
2323
2324 def parse_intermixed_args(self, args=None, namespace=None):
2325 args, argv = self.parse_known_intermixed_args(args, namespace)
2326 if argv:
2327 msg = _('unrecognized arguments: %s')
2328 self.error(msg % ' '.join(argv))
2329 return args
2330
2331 def parse_known_intermixed_args(self, args=None, namespace=None):
2332 # returns a namespace and list of extras
2333 #
2334 # positional can be freely intermixed with optionals. optionals are
2335 # first parsed with all positional arguments deactivated. The 'extras'
2336 # are then parsed. If the parser definition is incompatible with the
2337 # intermixed assumptions (e.g. use of REMAINDER, subparsers) a
2338 # TypeError is raised.
2339 #
2340 # positionals are 'deactivated' by setting nargs and default to
2341 # SUPPRESS. This blocks the addition of that positional to the
2342 # namespace
2343
2344 positionals = self._get_positional_actions()
2345 a = [action for action in positionals
2346 if action.nargs in [PARSER, REMAINDER]]
2347 if a:
2348 raise TypeError('parse_intermixed_args: positional arg'
2349 ' with nargs=%s'%a[0].nargs)
2350
2351 if [action.dest for group in self._mutually_exclusive_groups
2352 for action in group._group_actions if action in positionals]:
2353 raise TypeError('parse_intermixed_args: positional in'
2354 ' mutuallyExclusiveGroup')
2355
2356 try:
2357 save_usage = self.usage
2358 try:
2359 if self.usage is None:
2360 # capture the full usage for use in error messages
2361 self.usage = self.format_usage()[7:]
2362 for action in positionals:
2363 # deactivate positionals
2364 action.save_nargs = action.nargs
2365 # action.nargs = 0
2366 action.nargs = SUPPRESS
2367 action.save_default = action.default
2368 action.default = SUPPRESS
2369 namespace, remaining_args = self.parse_known_args(args,
2370 namespace)
2371 for action in positionals:
2372 # remove the empty positional values from namespace
2373 if (hasattr(namespace, action.dest)
2374 and getattr(namespace, action.dest)==[]):
2375 from warnings import warn
2376 warn('Do not expect %s in %s' % (action.dest, namespace))
2377 delattr(namespace, action.dest)
2378 finally:
2379 # restore nargs and usage before exiting
2380 for action in positionals:
2381 action.nargs = action.save_nargs
2382 action.default = action.save_default
2383 optionals = self._get_optional_actions()
2384 try:
2385 # parse positionals. optionals aren't normally required, but
2386 # they could be, so make sure they aren't.
2387 for action in optionals:
2388 action.save_required = action.required
2389 action.required = False
2390 for group in self._mutually_exclusive_groups:
2391 group.save_required = group.required
2392 group.required = False
2393 namespace, extras = self.parse_known_args(remaining_args,
2394 namespace)
2395 finally:
2396 # restore parser values before exiting
2397 for action in optionals:
2398 action.required = action.save_required
2399 for group in self._mutually_exclusive_groups:
2400 group.required = group.save_required
2401 finally:
2402 self.usage = save_usage
2403 return namespace, extras
2404
2405 # ========================
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002406 # Value conversion methods
2407 # ========================
2408 def _get_values(self, action, arg_strings):
R David Murray00528e82012-07-21 22:48:35 -04002409 # for everything but PARSER, REMAINDER args, strip out first '--'
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002410 if action.nargs not in [PARSER, REMAINDER]:
R David Murray00528e82012-07-21 22:48:35 -04002411 try:
2412 arg_strings.remove('--')
2413 except ValueError:
2414 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002415
2416 # optional argument produces a default when not present
2417 if not arg_strings and action.nargs == OPTIONAL:
2418 if action.option_strings:
2419 value = action.const
2420 else:
2421 value = action.default
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00002422 if isinstance(value, str):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002423 value = self._get_value(action, value)
2424 self._check_value(action, value)
2425
2426 # when nargs='*' on a positional, if there were no command-line
2427 # args, use the default if it is anything other than None
2428 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2429 not action.option_strings):
2430 if action.default is not None:
2431 value = action.default
2432 else:
2433 value = arg_strings
2434 self._check_value(action, value)
2435
2436 # single argument or optional argument produces a single value
2437 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2438 arg_string, = arg_strings
2439 value = self._get_value(action, arg_string)
2440 self._check_value(action, value)
2441
2442 # REMAINDER arguments convert all values, checking none
2443 elif action.nargs == REMAINDER:
2444 value = [self._get_value(action, v) for v in arg_strings]
2445
2446 # PARSER arguments convert all values, but check only the first
2447 elif action.nargs == PARSER:
2448 value = [self._get_value(action, v) for v in arg_strings]
2449 self._check_value(action, value[0])
2450
R. David Murray0f6b9d22017-09-06 20:25:40 -04002451 # SUPPRESS argument does not put anything in the namespace
2452 elif action.nargs == SUPPRESS:
2453 value = SUPPRESS
2454
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002455 # all other types of nargs produce a list
2456 else:
2457 value = [self._get_value(action, v) for v in arg_strings]
2458 for v in value:
2459 self._check_value(action, v)
2460
2461 # return the converted value
2462 return value
2463
2464 def _get_value(self, action, arg_string):
2465 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02002466 if not callable(type_func):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002467 msg = _('%r is not callable')
2468 raise ArgumentError(action, msg % type_func)
2469
2470 # convert the value to the appropriate type
2471 try:
2472 result = type_func(arg_string)
2473
2474 # ArgumentTypeErrors indicate errors
2475 except ArgumentTypeError:
2476 name = getattr(action.type, '__name__', repr(action.type))
2477 msg = str(_sys.exc_info()[1])
2478 raise ArgumentError(action, msg)
2479
2480 # TypeErrors or ValueErrors also indicate errors
2481 except (TypeError, ValueError):
2482 name = getattr(action.type, '__name__', repr(action.type))
Éric Araujobb48a8b2010-12-03 19:41:00 +00002483 args = {'type': name, 'value': arg_string}
2484 msg = _('invalid %(type)s value: %(value)r')
2485 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002486
2487 # return the converted value
2488 return result
2489
2490 def _check_value(self, action, value):
2491 # converted value must be one of the choices (if specified)
Vinay Sajip9ae50502016-08-23 08:43:16 +01002492 if action.choices is not None and value not in action.choices:
2493 args = {'value': value,
2494 'choices': ', '.join(map(repr, action.choices))}
2495 msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2496 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002497
2498 # =======================
2499 # Help-formatting methods
2500 # =======================
2501 def format_usage(self):
2502 formatter = self._get_formatter()
2503 formatter.add_usage(self.usage, self._actions,
2504 self._mutually_exclusive_groups)
2505 return formatter.format_help()
2506
2507 def format_help(self):
2508 formatter = self._get_formatter()
2509
2510 # usage
2511 formatter.add_usage(self.usage, self._actions,
2512 self._mutually_exclusive_groups)
2513
2514 # description
2515 formatter.add_text(self.description)
2516
2517 # positionals, optionals and user-defined groups
2518 for action_group in self._action_groups:
2519 formatter.start_section(action_group.title)
2520 formatter.add_text(action_group.description)
2521 formatter.add_arguments(action_group._group_actions)
2522 formatter.end_section()
2523
2524 # epilog
2525 formatter.add_text(self.epilog)
2526
2527 # determine help from format above
2528 return formatter.format_help()
2529
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002530 def _get_formatter(self):
2531 return self.formatter_class(prog=self.prog)
2532
2533 # =====================
2534 # Help-printing methods
2535 # =====================
2536 def print_usage(self, file=None):
2537 if file is None:
2538 file = _sys.stdout
2539 self._print_message(self.format_usage(), file)
2540
2541 def print_help(self, file=None):
2542 if file is None:
2543 file = _sys.stdout
2544 self._print_message(self.format_help(), file)
2545
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002546 def _print_message(self, message, file=None):
2547 if message:
2548 if file is None:
2549 file = _sys.stderr
2550 file.write(message)
2551
2552 # ===============
2553 # Exiting methods
2554 # ===============
2555 def exit(self, status=0, message=None):
2556 if message:
2557 self._print_message(message, _sys.stderr)
2558 _sys.exit(status)
2559
2560 def error(self, message):
2561 """error(message: string)
2562
2563 Prints a usage message incorporating the message to stderr and
2564 exits.
2565
2566 If you override this in a subclass, it should not return -- it
2567 should either exit or raise an exception.
2568 """
2569 self.print_usage(_sys.stderr)
Éric Araujobb48a8b2010-12-03 19:41:00 +00002570 args = {'prog': self.prog, 'message': message}
2571 self.exit(2, _('%(prog)s: error: %(message)s\n') % args)