blob: cc538415d23465586b4784cc5ecfcf63466c63bd [file] [log] [blame]
Benjamin Peterson2b37fc42010-03-24 22:10:42 +00001# Author: Steven J. Bethard <steven.bethard@gmail.com>.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002
3"""Command-line parsing library
4
5This module is an optparse-inspired command-line parsing library that:
6
7 - handles both optional and positional arguments
8 - produces highly informative usage messages
9 - supports parsers that dispatch to sub-parsers
10
11The following is a simple usage example that sums integers from the
12command-line and writes the result to a file::
13
14 parser = argparse.ArgumentParser(
15 description='sum the integers at the command line')
16 parser.add_argument(
17 'integers', metavar='int', nargs='+', type=int,
18 help='an integer to be summed')
19 parser.add_argument(
20 '--log', default=sys.stdout, type=argparse.FileType('w'),
21 help='the file where the sum should be written')
22 args = parser.parse_args()
23 args.log.write('%s' % sum(args.integers))
24 args.log.close()
25
26The module contains the following public classes:
27
28 - ArgumentParser -- The main entry point for command-line parsing. As the
29 example above shows, the add_argument() method is used to populate
30 the parser with actions for optional and positional arguments. Then
31 the parse_args() method is invoked to convert the args at the
32 command-line into an object with attributes.
33
34 - ArgumentError -- The exception raised by ArgumentParser objects when
35 there are errors with the parser's actions. Errors raised while
36 parsing the command-line are caught by ArgumentParser and emitted
37 as command-line messages.
38
39 - FileType -- A factory for defining types of files to be created. As the
40 example above shows, instances of FileType are typically passed as
41 the type= argument of add_argument() calls.
42
43 - Action -- The base class for parser actions. Typically actions are
44 selected by passing strings like 'store_true' or 'append_const' to
45 the action= argument of add_argument(). However, for greater
46 customization of ArgumentParser actions, subclasses of Action may
47 be defined and passed as the action= argument.
48
49 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
50 ArgumentDefaultsHelpFormatter -- Formatter classes which
51 may be passed as the formatter_class= argument to the
52 ArgumentParser constructor. HelpFormatter is the default,
53 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
54 not to change the formatting for help text, and
55 ArgumentDefaultsHelpFormatter adds information about argument defaults
56 to the help.
57
58All other classes in this module are considered implementation details.
59(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
60considered public as object names -- the API of the formatter objects is
61still considered an implementation detail.)
62"""
63
64__version__ = '1.1'
65__all__ = [
66 'ArgumentParser',
67 'ArgumentError',
Steven Bethard72c55382010-11-01 15:23:12 +000068 'ArgumentTypeError',
Benjamin Peterson698a18a2010-03-02 22:34:37 +000069 'FileType',
70 'HelpFormatter',
Steven Bethard72c55382010-11-01 15:23:12 +000071 'ArgumentDefaultsHelpFormatter',
Benjamin Peterson698a18a2010-03-02 22:34:37 +000072 'RawDescriptionHelpFormatter',
73 'RawTextHelpFormatter',
Steven Bethard0331e902011-03-26 14:48:04 +010074 'MetavarTypeHelpFormatter',
Steven Bethard72c55382010-11-01 15:23:12 +000075 'Namespace',
76 'Action',
77 'ONE_OR_MORE',
78 'OPTIONAL',
79 'PARSER',
80 'REMAINDER',
81 'SUPPRESS',
82 'ZERO_OR_MORE',
Benjamin Peterson698a18a2010-03-02 22:34:37 +000083]
84
85
Steven Bethard8a6a1982011-03-27 13:53:53 +020086import collections as _collections
Benjamin Peterson698a18a2010-03-02 22:34:37 +000087import copy as _copy
88import os as _os
89import re as _re
90import sys as _sys
91import textwrap as _textwrap
92
É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 +000095
Benjamin Peterson698a18a2010-03-02 22:34:37 +000096SUPPRESS = '==SUPPRESS=='
97
98OPTIONAL = '?'
99ZERO_OR_MORE = '*'
100ONE_OR_MORE = '+'
101PARSER = 'A...'
102REMAINDER = '...'
Steven Bethardfca2e8a2010-11-02 12:47:22 +0000103_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000104
105# =============================
106# Utility functions and classes
107# =============================
108
109class _AttributeHolder(object):
110 """Abstract base class that provides __repr__.
111
112 The __repr__ method returns a string in the format::
113 ClassName(attr=name, attr=name, ...)
114 The attributes are determined either by a class-level attribute,
115 '_kwarg_names', or by inspecting the instance __dict__.
116 """
117
118 def __repr__(self):
119 type_name = type(self).__name__
120 arg_strings = []
Berker Peksag76b17142015-07-29 23:51:47 +0300121 star_args = {}
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000122 for arg in self._get_args():
123 arg_strings.append(repr(arg))
124 for name, value in self._get_kwargs():
Berker Peksag76b17142015-07-29 23:51:47 +0300125 if name.isidentifier():
126 arg_strings.append('%s=%r' % (name, value))
127 else:
128 star_args[name] = value
129 if star_args:
130 arg_strings.append('**%s' % repr(star_args))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000131 return '%s(%s)' % (type_name, ', '.join(arg_strings))
132
133 def _get_kwargs(self):
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000134 return sorted(self.__dict__.items())
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000135
136 def _get_args(self):
137 return []
138
139
140def _ensure_value(namespace, name, value):
141 if getattr(namespace, name, None) is None:
142 setattr(namespace, name, value)
143 return getattr(namespace, name)
144
145
146# ===============
147# Formatting Help
148# ===============
149
150class HelpFormatter(object):
151 """Formatter for generating usage messages and argument help strings.
152
153 Only the name of this class is considered a public API. All the methods
154 provided by the class are considered an implementation detail.
155 """
156
157 def __init__(self,
158 prog,
159 indent_increment=2,
160 max_help_position=24,
161 width=None):
162
163 # default setting for width
164 if width is None:
165 try:
166 width = int(_os.environ['COLUMNS'])
167 except (KeyError, ValueError):
168 width = 80
169 width -= 2
170
171 self._prog = prog
172 self._indent_increment = indent_increment
173 self._max_help_position = max_help_position
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200174 self._max_help_position = min(max_help_position,
175 max(width - 20, indent_increment * 2))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000176 self._width = width
177
178 self._current_indent = 0
179 self._level = 0
180 self._action_max_length = 0
181
182 self._root_section = self._Section(self, None)
183 self._current_section = self._root_section
184
185 self._whitespace_matcher = _re.compile(r'\s+')
186 self._long_break_matcher = _re.compile(r'\n\n\n+')
187
188 # ===============================
189 # Section and indentation methods
190 # ===============================
191 def _indent(self):
192 self._current_indent += self._indent_increment
193 self._level += 1
194
195 def _dedent(self):
196 self._current_indent -= self._indent_increment
197 assert self._current_indent >= 0, 'Indent decreased below 0.'
198 self._level -= 1
199
200 class _Section(object):
201
202 def __init__(self, formatter, parent, heading=None):
203 self.formatter = formatter
204 self.parent = parent
205 self.heading = heading
206 self.items = []
207
208 def format_help(self):
209 # format the indented section
210 if self.parent is not None:
211 self.formatter._indent()
212 join = self.formatter._join_parts
213 for func, args in self.items:
214 func(*args)
215 item_help = join([func(*args) for func, args in self.items])
216 if self.parent is not None:
217 self.formatter._dedent()
218
219 # return nothing if the section was empty
220 if not item_help:
221 return ''
222
223 # add the heading if the section was non-empty
224 if self.heading is not SUPPRESS and self.heading is not None:
225 current_indent = self.formatter._current_indent
226 heading = '%*s%s:\n' % (current_indent, '', self.heading)
227 else:
228 heading = ''
229
230 # join the section-initial newline, the heading and the help
231 return join(['\n', heading, item_help, '\n'])
232
233 def _add_item(self, func, args):
234 self._current_section.items.append((func, args))
235
236 # ========================
237 # Message building methods
238 # ========================
239 def start_section(self, heading):
240 self._indent()
241 section = self._Section(self, self._current_section, heading)
242 self._add_item(section.format_help, [])
243 self._current_section = section
244
245 def end_section(self):
246 self._current_section = self._current_section.parent
247 self._dedent()
248
249 def add_text(self, text):
250 if text is not SUPPRESS and text is not None:
251 self._add_item(self._format_text, [text])
252
253 def add_usage(self, usage, actions, groups, prefix=None):
254 if usage is not SUPPRESS:
255 args = usage, actions, groups, prefix
256 self._add_item(self._format_usage, args)
257
258 def add_argument(self, action):
259 if action.help is not SUPPRESS:
260
261 # find all invocations
262 get_invocation = self._format_action_invocation
263 invocations = [get_invocation(action)]
264 for subaction in self._iter_indented_subactions(action):
265 invocations.append(get_invocation(subaction))
266
267 # update the maximum item length
268 invocation_length = max([len(s) for s in invocations])
269 action_length = invocation_length + self._current_indent
270 self._action_max_length = max(self._action_max_length,
271 action_length)
272
273 # add the item to the list
274 self._add_item(self._format_action, [action])
275
276 def add_arguments(self, actions):
277 for action in actions:
278 self.add_argument(action)
279
280 # =======================
281 # Help-formatting methods
282 # =======================
283 def format_help(self):
284 help = self._root_section.format_help()
285 if help:
286 help = self._long_break_matcher.sub('\n\n', help)
287 help = help.strip('\n') + '\n'
288 return help
289
290 def _join_parts(self, part_strings):
291 return ''.join([part
292 for part in part_strings
293 if part and part is not SUPPRESS])
294
295 def _format_usage(self, usage, actions, groups, prefix):
296 if prefix is None:
297 prefix = _('usage: ')
298
299 # if usage is specified, use that
300 if usage is not None:
301 usage = usage % dict(prog=self._prog)
302
303 # if no optionals or positionals are available, usage is just prog
304 elif usage is None and not actions:
305 usage = '%(prog)s' % dict(prog=self._prog)
306
307 # if optionals and positionals are available, calculate usage
308 elif usage is None:
309 prog = '%(prog)s' % dict(prog=self._prog)
310
311 # split optionals from positionals
312 optionals = []
313 positionals = []
314 for action in actions:
315 if action.option_strings:
316 optionals.append(action)
317 else:
318 positionals.append(action)
319
320 # build full usage string
321 format = self._format_actions_usage
322 action_usage = format(optionals + positionals, groups)
323 usage = ' '.join([s for s in [prog, action_usage] if s])
324
325 # wrap the usage parts if it's too long
326 text_width = self._width - self._current_indent
327 if len(prefix) + len(usage) > text_width:
328
329 # break usage into wrappable parts
330 part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
331 opt_usage = format(optionals, groups)
332 pos_usage = format(positionals, groups)
333 opt_parts = _re.findall(part_regexp, opt_usage)
334 pos_parts = _re.findall(part_regexp, pos_usage)
335 assert ' '.join(opt_parts) == opt_usage
336 assert ' '.join(pos_parts) == pos_usage
337
338 # helper for wrapping lines
339 def get_lines(parts, indent, prefix=None):
340 lines = []
341 line = []
342 if prefix is not None:
343 line_len = len(prefix) - 1
344 else:
345 line_len = len(indent) - 1
346 for part in parts:
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200347 if line_len + 1 + len(part) > text_width and line:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000348 lines.append(indent + ' '.join(line))
349 line = []
350 line_len = len(indent) - 1
351 line.append(part)
352 line_len += len(part) + 1
353 if line:
354 lines.append(indent + ' '.join(line))
355 if prefix is not None:
356 lines[0] = lines[0][len(indent):]
357 return lines
358
359 # if prog is short, follow it with optionals or positionals
360 if len(prefix) + len(prog) <= 0.75 * text_width:
361 indent = ' ' * (len(prefix) + len(prog) + 1)
362 if opt_parts:
363 lines = get_lines([prog] + opt_parts, indent, prefix)
364 lines.extend(get_lines(pos_parts, indent))
365 elif pos_parts:
366 lines = get_lines([prog] + pos_parts, indent, prefix)
367 else:
368 lines = [prog]
369
370 # if prog is long, put it on its own line
371 else:
372 indent = ' ' * len(prefix)
373 parts = opt_parts + pos_parts
374 lines = get_lines(parts, indent)
375 if len(lines) > 1:
376 lines = []
377 lines.extend(get_lines(opt_parts, indent))
378 lines.extend(get_lines(pos_parts, indent))
379 lines = [prog] + lines
380
381 # join lines into usage
382 usage = '\n'.join(lines)
383
384 # prefix with 'usage:'
385 return '%s%s\n\n' % (prefix, usage)
386
387 def _format_actions_usage(self, actions, groups):
388 # find group indices and identify actions in groups
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000389 group_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000390 inserts = {}
391 for group in groups:
392 try:
393 start = actions.index(group._group_actions[0])
394 except ValueError:
395 continue
396 else:
397 end = start + len(group._group_actions)
398 if actions[start:end] == group._group_actions:
399 for action in group._group_actions:
400 group_actions.add(action)
401 if not group.required:
Steven Bethard49998ee2010-11-01 16:29:26 +0000402 if start in inserts:
403 inserts[start] += ' ['
404 else:
405 inserts[start] = '['
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000406 inserts[end] = ']'
407 else:
Steven Bethard49998ee2010-11-01 16:29:26 +0000408 if start in inserts:
409 inserts[start] += ' ('
410 else:
411 inserts[start] = '('
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000412 inserts[end] = ')'
413 for i in range(start + 1, end):
414 inserts[i] = '|'
415
416 # collect all actions format strings
417 parts = []
418 for i, action in enumerate(actions):
419
420 # suppressed arguments are marked with None
421 # remove | separators for suppressed arguments
422 if action.help is SUPPRESS:
423 parts.append(None)
424 if inserts.get(i) == '|':
425 inserts.pop(i)
426 elif inserts.get(i + 1) == '|':
427 inserts.pop(i + 1)
428
429 # produce all arg strings
430 elif not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100431 default = self._get_default_metavar_for_positional(action)
432 part = self._format_args(action, default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000433
434 # if it's in a group, strip the outer []
435 if action in group_actions:
436 if part[0] == '[' and part[-1] == ']':
437 part = part[1:-1]
438
439 # add the action string to the list
440 parts.append(part)
441
442 # produce the first way to invoke the option in brackets
443 else:
444 option_string = action.option_strings[0]
445
446 # if the Optional doesn't take a value, format is:
447 # -s or --long
448 if action.nargs == 0:
449 part = '%s' % option_string
450
451 # if the Optional takes a value, format is:
452 # -s ARGS or --long ARGS
453 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100454 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000455 args_string = self._format_args(action, default)
456 part = '%s %s' % (option_string, args_string)
457
458 # make it look optional if it's not required or in a group
459 if not action.required and action not in group_actions:
460 part = '[%s]' % part
461
462 # add the action string to the list
463 parts.append(part)
464
465 # insert things at the necessary indices
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000466 for i in sorted(inserts, reverse=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000467 parts[i:i] = [inserts[i]]
468
469 # join all the action items with spaces
470 text = ' '.join([item for item in parts if item is not None])
471
472 # clean up separators for mutually exclusive groups
473 open = r'[\[(]'
474 close = r'[\])]'
475 text = _re.sub(r'(%s) ' % open, r'\1', text)
476 text = _re.sub(r' (%s)' % close, r'\1', text)
477 text = _re.sub(r'%s *%s' % (open, close), r'', text)
478 text = _re.sub(r'\(([^|]*)\)', r'\1', text)
479 text = text.strip()
480
481 # return the text
482 return text
483
484 def _format_text(self, text):
485 if '%(prog)' in text:
486 text = text % dict(prog=self._prog)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200487 text_width = max(self._width - self._current_indent, 11)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000488 indent = ' ' * self._current_indent
489 return self._fill_text(text, text_width, indent) + '\n\n'
490
491 def _format_action(self, action):
492 # determine the required width and the entry label
493 help_position = min(self._action_max_length + 2,
494 self._max_help_position)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200495 help_width = max(self._width - help_position, 11)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000496 action_width = help_position - self._current_indent - 2
497 action_header = self._format_action_invocation(action)
498
Georg Brandl2514f522014-10-20 08:36:02 +0200499 # no help; start on same line and add a final newline
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000500 if not action.help:
501 tup = self._current_indent, '', action_header
502 action_header = '%*s%s\n' % tup
503
504 # short action name; start on the same line and pad two spaces
505 elif len(action_header) <= action_width:
506 tup = self._current_indent, '', action_width, action_header
507 action_header = '%*s%-*s ' % tup
508 indent_first = 0
509
510 # long action name; start on the next line
511 else:
512 tup = self._current_indent, '', action_header
513 action_header = '%*s%s\n' % tup
514 indent_first = help_position
515
516 # collect the pieces of the action help
517 parts = [action_header]
518
519 # if there was help for the action, add lines of help text
520 if action.help:
521 help_text = self._expand_help(action)
522 help_lines = self._split_lines(help_text, help_width)
523 parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
524 for line in help_lines[1:]:
525 parts.append('%*s%s\n' % (help_position, '', line))
526
527 # or add a newline if the description doesn't end with one
528 elif not action_header.endswith('\n'):
529 parts.append('\n')
530
531 # if there are any sub-actions, add their help as well
532 for subaction in self._iter_indented_subactions(action):
533 parts.append(self._format_action(subaction))
534
535 # return a single string
536 return self._join_parts(parts)
537
538 def _format_action_invocation(self, action):
539 if not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100540 default = self._get_default_metavar_for_positional(action)
541 metavar, = self._metavar_formatter(action, default)(1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000542 return metavar
543
544 else:
545 parts = []
546
547 # if the Optional doesn't take a value, format is:
548 # -s, --long
549 if action.nargs == 0:
550 parts.extend(action.option_strings)
551
552 # if the Optional takes a value, format is:
553 # -s ARGS, --long ARGS
554 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100555 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000556 args_string = self._format_args(action, default)
557 for option_string in action.option_strings:
558 parts.append('%s %s' % (option_string, args_string))
559
560 return ', '.join(parts)
561
562 def _metavar_formatter(self, action, default_metavar):
563 if action.metavar is not None:
564 result = action.metavar
565 elif action.choices is not None:
566 choice_strs = [str(choice) for choice in action.choices]
567 result = '{%s}' % ','.join(choice_strs)
568 else:
569 result = default_metavar
570
571 def format(tuple_size):
572 if isinstance(result, tuple):
573 return result
574 else:
575 return (result, ) * tuple_size
576 return format
577
578 def _format_args(self, action, default_metavar):
579 get_metavar = self._metavar_formatter(action, default_metavar)
580 if action.nargs is None:
581 result = '%s' % get_metavar(1)
582 elif action.nargs == OPTIONAL:
583 result = '[%s]' % get_metavar(1)
584 elif action.nargs == ZERO_OR_MORE:
585 result = '[%s [%s ...]]' % get_metavar(2)
586 elif action.nargs == ONE_OR_MORE:
587 result = '%s [%s ...]' % get_metavar(2)
588 elif action.nargs == REMAINDER:
589 result = '...'
590 elif action.nargs == PARSER:
591 result = '%s ...' % get_metavar(1)
592 else:
593 formats = ['%s' for _ in range(action.nargs)]
594 result = ' '.join(formats) % get_metavar(action.nargs)
595 return result
596
597 def _expand_help(self, action):
598 params = dict(vars(action), prog=self._prog)
599 for name in list(params):
600 if params[name] is SUPPRESS:
601 del params[name]
602 for name in list(params):
603 if hasattr(params[name], '__name__'):
604 params[name] = params[name].__name__
605 if params.get('choices') is not None:
606 choices_str = ', '.join([str(c) for c in params['choices']])
607 params['choices'] = choices_str
608 return self._get_help_string(action) % params
609
610 def _iter_indented_subactions(self, action):
611 try:
612 get_subactions = action._get_subactions
613 except AttributeError:
614 pass
615 else:
616 self._indent()
Philip Jenvey4993cc02012-10-01 12:53:43 -0700617 yield from get_subactions()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000618 self._dedent()
619
620 def _split_lines(self, text, width):
621 text = self._whitespace_matcher.sub(' ', text).strip()
622 return _textwrap.wrap(text, width)
623
624 def _fill_text(self, text, width, indent):
625 text = self._whitespace_matcher.sub(' ', text).strip()
626 return _textwrap.fill(text, width, initial_indent=indent,
627 subsequent_indent=indent)
628
629 def _get_help_string(self, action):
630 return action.help
631
Steven Bethard0331e902011-03-26 14:48:04 +0100632 def _get_default_metavar_for_optional(self, action):
633 return action.dest.upper()
634
635 def _get_default_metavar_for_positional(self, action):
636 return action.dest
637
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000638
639class RawDescriptionHelpFormatter(HelpFormatter):
640 """Help message formatter which retains any formatting in descriptions.
641
642 Only the name of this class is considered a public API. All the methods
643 provided by the class are considered an implementation detail.
644 """
645
646 def _fill_text(self, text, width, indent):
Ezio Melottid8b509b2011-09-28 17:37:55 +0300647 return ''.join(indent + line for line in text.splitlines(keepends=True))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000648
649
650class RawTextHelpFormatter(RawDescriptionHelpFormatter):
651 """Help message formatter which retains formatting of all help text.
652
653 Only the name of this class is considered a public API. All the methods
654 provided by the class are considered an implementation detail.
655 """
656
657 def _split_lines(self, text, width):
658 return text.splitlines()
659
660
661class ArgumentDefaultsHelpFormatter(HelpFormatter):
662 """Help message formatter which adds default values to argument help.
663
664 Only the name of this class is considered a public API. All the methods
665 provided by the class are considered an implementation detail.
666 """
667
668 def _get_help_string(self, action):
669 help = action.help
670 if '%(default)' not in action.help:
671 if action.default is not SUPPRESS:
672 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
673 if action.option_strings or action.nargs in defaulting_nargs:
674 help += ' (default: %(default)s)'
675 return help
676
677
Steven Bethard0331e902011-03-26 14:48:04 +0100678class MetavarTypeHelpFormatter(HelpFormatter):
679 """Help message formatter which uses the argument 'type' as the default
680 metavar value (instead of the argument 'dest')
681
682 Only the name of this class is considered a public API. All the methods
683 provided by the class are considered an implementation detail.
684 """
685
686 def _get_default_metavar_for_optional(self, action):
687 return action.type.__name__
688
689 def _get_default_metavar_for_positional(self, action):
690 return action.type.__name__
691
692
693
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000694# =====================
695# Options and Arguments
696# =====================
697
698def _get_action_name(argument):
699 if argument is None:
700 return None
701 elif argument.option_strings:
702 return '/'.join(argument.option_strings)
703 elif argument.metavar not in (None, SUPPRESS):
704 return argument.metavar
705 elif argument.dest not in (None, SUPPRESS):
706 return argument.dest
707 else:
708 return None
709
710
711class ArgumentError(Exception):
712 """An error from creating or using an argument (optional or positional).
713
714 The string value of this exception is the message, augmented with
715 information about the argument that caused it.
716 """
717
718 def __init__(self, argument, message):
719 self.argument_name = _get_action_name(argument)
720 self.message = message
721
722 def __str__(self):
723 if self.argument_name is None:
724 format = '%(message)s'
725 else:
726 format = 'argument %(argument_name)s: %(message)s'
727 return format % dict(message=self.message,
728 argument_name=self.argument_name)
729
730
731class ArgumentTypeError(Exception):
732 """An error from trying to convert a command line string to a type."""
733 pass
734
735
736# ==============
737# Action classes
738# ==============
739
740class Action(_AttributeHolder):
741 """Information about how to convert command line strings to Python objects.
742
743 Action objects are used by an ArgumentParser to represent the information
744 needed to parse a single argument from one or more strings from the
745 command line. The keyword arguments to the Action constructor are also
746 all attributes of Action instances.
747
748 Keyword Arguments:
749
750 - option_strings -- A list of command-line option strings which
751 should be associated with this action.
752
753 - dest -- The name of the attribute to hold the created object(s)
754
755 - nargs -- The number of command-line arguments that should be
756 consumed. By default, one argument will be consumed and a single
757 value will be produced. Other values include:
758 - N (an integer) consumes N arguments (and produces a list)
759 - '?' consumes zero or one arguments
760 - '*' consumes zero or more arguments (and produces a list)
761 - '+' consumes one or more arguments (and produces a list)
762 Note that the difference between the default and nargs=1 is that
763 with the default, a single value will be produced, while with
764 nargs=1, a list containing a single value will be produced.
765
766 - const -- The value to be produced if the option is specified and the
767 option uses an action that takes no values.
768
769 - default -- The value to be produced if the option is not specified.
770
R David Murray15cd9a02012-07-21 17:04:25 -0400771 - type -- A callable that accepts a single string argument, and
772 returns the converted value. The standard Python types str, int,
773 float, and complex are useful examples of such callables. If None,
774 str is used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000775
776 - choices -- A container of values that should be allowed. If not None,
777 after a command-line argument has been converted to the appropriate
778 type, an exception will be raised if it is not a member of this
779 collection.
780
781 - required -- True if the action must always be specified at the
782 command line. This is only meaningful for optional command-line
783 arguments.
784
785 - help -- The help string describing the argument.
786
787 - metavar -- The name to be used for the option's argument with the
788 help string. If None, the 'dest' value will be used as the name.
789 """
790
791 def __init__(self,
792 option_strings,
793 dest,
794 nargs=None,
795 const=None,
796 default=None,
797 type=None,
798 choices=None,
799 required=False,
800 help=None,
801 metavar=None):
802 self.option_strings = option_strings
803 self.dest = dest
804 self.nargs = nargs
805 self.const = const
806 self.default = default
807 self.type = type
808 self.choices = choices
809 self.required = required
810 self.help = help
811 self.metavar = metavar
812
813 def _get_kwargs(self):
814 names = [
815 'option_strings',
816 'dest',
817 'nargs',
818 'const',
819 'default',
820 'type',
821 'choices',
822 'help',
823 'metavar',
824 ]
825 return [(name, getattr(self, name)) for name in names]
826
827 def __call__(self, parser, namespace, values, option_string=None):
828 raise NotImplementedError(_('.__call__() not defined'))
829
830
831class _StoreAction(Action):
832
833 def __init__(self,
834 option_strings,
835 dest,
836 nargs=None,
837 const=None,
838 default=None,
839 type=None,
840 choices=None,
841 required=False,
842 help=None,
843 metavar=None):
844 if nargs == 0:
845 raise ValueError('nargs for store actions must be > 0; if you '
846 'have nothing to store, actions such as store '
847 'true or store const may be more appropriate')
848 if const is not None and nargs != OPTIONAL:
849 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
850 super(_StoreAction, self).__init__(
851 option_strings=option_strings,
852 dest=dest,
853 nargs=nargs,
854 const=const,
855 default=default,
856 type=type,
857 choices=choices,
858 required=required,
859 help=help,
860 metavar=metavar)
861
862 def __call__(self, parser, namespace, values, option_string=None):
863 setattr(namespace, self.dest, values)
864
865
866class _StoreConstAction(Action):
867
868 def __init__(self,
869 option_strings,
870 dest,
871 const,
872 default=None,
873 required=False,
874 help=None,
875 metavar=None):
876 super(_StoreConstAction, self).__init__(
877 option_strings=option_strings,
878 dest=dest,
879 nargs=0,
880 const=const,
881 default=default,
882 required=required,
883 help=help)
884
885 def __call__(self, parser, namespace, values, option_string=None):
886 setattr(namespace, self.dest, self.const)
887
888
889class _StoreTrueAction(_StoreConstAction):
890
891 def __init__(self,
892 option_strings,
893 dest,
894 default=False,
895 required=False,
896 help=None):
897 super(_StoreTrueAction, self).__init__(
898 option_strings=option_strings,
899 dest=dest,
900 const=True,
901 default=default,
902 required=required,
903 help=help)
904
905
906class _StoreFalseAction(_StoreConstAction):
907
908 def __init__(self,
909 option_strings,
910 dest,
911 default=True,
912 required=False,
913 help=None):
914 super(_StoreFalseAction, self).__init__(
915 option_strings=option_strings,
916 dest=dest,
917 const=False,
918 default=default,
919 required=required,
920 help=help)
921
922
923class _AppendAction(Action):
924
925 def __init__(self,
926 option_strings,
927 dest,
928 nargs=None,
929 const=None,
930 default=None,
931 type=None,
932 choices=None,
933 required=False,
934 help=None,
935 metavar=None):
936 if nargs == 0:
937 raise ValueError('nargs for append actions must be > 0; if arg '
938 'strings are not supplying the value to append, '
939 'the append const action may be more appropriate')
940 if const is not None and nargs != OPTIONAL:
941 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
942 super(_AppendAction, self).__init__(
943 option_strings=option_strings,
944 dest=dest,
945 nargs=nargs,
946 const=const,
947 default=default,
948 type=type,
949 choices=choices,
950 required=required,
951 help=help,
952 metavar=metavar)
953
954 def __call__(self, parser, namespace, values, option_string=None):
955 items = _copy.copy(_ensure_value(namespace, self.dest, []))
956 items.append(values)
957 setattr(namespace, self.dest, items)
958
959
960class _AppendConstAction(Action):
961
962 def __init__(self,
963 option_strings,
964 dest,
965 const,
966 default=None,
967 required=False,
968 help=None,
969 metavar=None):
970 super(_AppendConstAction, self).__init__(
971 option_strings=option_strings,
972 dest=dest,
973 nargs=0,
974 const=const,
975 default=default,
976 required=required,
977 help=help,
978 metavar=metavar)
979
980 def __call__(self, parser, namespace, values, option_string=None):
981 items = _copy.copy(_ensure_value(namespace, self.dest, []))
982 items.append(self.const)
983 setattr(namespace, self.dest, items)
984
985
986class _CountAction(Action):
987
988 def __init__(self,
989 option_strings,
990 dest,
991 default=None,
992 required=False,
993 help=None):
994 super(_CountAction, self).__init__(
995 option_strings=option_strings,
996 dest=dest,
997 nargs=0,
998 default=default,
999 required=required,
1000 help=help)
1001
1002 def __call__(self, parser, namespace, values, option_string=None):
1003 new_count = _ensure_value(namespace, self.dest, 0) + 1
1004 setattr(namespace, self.dest, new_count)
1005
1006
1007class _HelpAction(Action):
1008
1009 def __init__(self,
1010 option_strings,
1011 dest=SUPPRESS,
1012 default=SUPPRESS,
1013 help=None):
1014 super(_HelpAction, self).__init__(
1015 option_strings=option_strings,
1016 dest=dest,
1017 default=default,
1018 nargs=0,
1019 help=help)
1020
1021 def __call__(self, parser, namespace, values, option_string=None):
1022 parser.print_help()
1023 parser.exit()
1024
1025
1026class _VersionAction(Action):
1027
1028 def __init__(self,
1029 option_strings,
1030 version=None,
1031 dest=SUPPRESS,
1032 default=SUPPRESS,
Steven Bethard50fe5932010-05-24 03:47:38 +00001033 help="show program's version number and exit"):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001034 super(_VersionAction, self).__init__(
1035 option_strings=option_strings,
1036 dest=dest,
1037 default=default,
1038 nargs=0,
1039 help=help)
1040 self.version = version
1041
1042 def __call__(self, parser, namespace, values, option_string=None):
1043 version = self.version
1044 if version is None:
1045 version = parser.version
1046 formatter = parser._get_formatter()
1047 formatter.add_text(version)
Eli Benderskycdac5512013-09-06 06:49:15 -07001048 parser._print_message(formatter.format_help(), _sys.stdout)
1049 parser.exit()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001050
1051
1052class _SubParsersAction(Action):
1053
1054 class _ChoicesPseudoAction(Action):
1055
Steven Bethardfd311a72010-12-18 11:19:23 +00001056 def __init__(self, name, aliases, help):
1057 metavar = dest = name
1058 if aliases:
1059 metavar += ' (%s)' % ', '.join(aliases)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001060 sup = super(_SubParsersAction._ChoicesPseudoAction, self)
Steven Bethardfd311a72010-12-18 11:19:23 +00001061 sup.__init__(option_strings=[], dest=dest, help=help,
1062 metavar=metavar)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001063
1064 def __init__(self,
1065 option_strings,
1066 prog,
1067 parser_class,
1068 dest=SUPPRESS,
1069 help=None,
1070 metavar=None):
1071
1072 self._prog_prefix = prog
1073 self._parser_class = parser_class
Steven Bethard8a6a1982011-03-27 13:53:53 +02001074 self._name_parser_map = _collections.OrderedDict()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001075 self._choices_actions = []
1076
1077 super(_SubParsersAction, self).__init__(
1078 option_strings=option_strings,
1079 dest=dest,
1080 nargs=PARSER,
1081 choices=self._name_parser_map,
1082 help=help,
1083 metavar=metavar)
1084
1085 def add_parser(self, name, **kwargs):
1086 # set prog from the existing prefix
1087 if kwargs.get('prog') is None:
1088 kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1089
Steven Bethardfd311a72010-12-18 11:19:23 +00001090 aliases = kwargs.pop('aliases', ())
1091
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001092 # create a pseudo-action to hold the choice help
1093 if 'help' in kwargs:
1094 help = kwargs.pop('help')
Steven Bethardfd311a72010-12-18 11:19:23 +00001095 choice_action = self._ChoicesPseudoAction(name, aliases, help)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001096 self._choices_actions.append(choice_action)
1097
1098 # create the parser and add it to the map
1099 parser = self._parser_class(**kwargs)
1100 self._name_parser_map[name] = parser
Steven Bethardfd311a72010-12-18 11:19:23 +00001101
1102 # make parser available under aliases also
1103 for alias in aliases:
1104 self._name_parser_map[alias] = parser
1105
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001106 return parser
1107
1108 def _get_subactions(self):
1109 return self._choices_actions
1110
1111 def __call__(self, parser, namespace, values, option_string=None):
1112 parser_name = values[0]
1113 arg_strings = values[1:]
1114
1115 # set the parser name if requested
1116 if self.dest is not SUPPRESS:
1117 setattr(namespace, self.dest, parser_name)
1118
1119 # select the parser
1120 try:
1121 parser = self._name_parser_map[parser_name]
1122 except KeyError:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001123 args = {'parser_name': parser_name,
1124 'choices': ', '.join(self._name_parser_map)}
1125 msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001126 raise ArgumentError(self, msg)
1127
1128 # parse all the remaining options into the namespace
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001129 # store any unrecognized options on the object, so that the top
1130 # level parser can decide what to do with them
R David Murray7570cbd2014-10-17 19:55:11 -04001131
1132 # In case this subparser defines new defaults, we parse them
1133 # in a new namespace object and then update the original
1134 # namespace for the relevant parts.
1135 subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
1136 for key, value in vars(subnamespace).items():
1137 setattr(namespace, key, value)
1138
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001139 if arg_strings:
1140 vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1141 getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001142
1143
1144# ==============
1145# Type classes
1146# ==============
1147
1148class FileType(object):
1149 """Factory for creating file object types
1150
1151 Instances of FileType are typically passed as type= arguments to the
1152 ArgumentParser add_argument() method.
1153
1154 Keyword Arguments:
1155 - mode -- A string indicating how the file is to be opened. Accepts the
1156 same values as the builtin open() function.
1157 - bufsize -- The file's desired buffer size. Accepts the same values as
1158 the builtin open() function.
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001159 - encoding -- The file's encoding. Accepts the same values as the
Terry Jan Reedy8e7586b2013-03-11 18:38:13 -04001160 builtin open() function.
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001161 - errors -- A string indicating how encoding and decoding errors are to
1162 be handled. Accepts the same value as the builtin open() function.
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001163 """
1164
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001165 def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001166 self._mode = mode
1167 self._bufsize = bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001168 self._encoding = encoding
1169 self._errors = errors
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001170
1171 def __call__(self, string):
1172 # the special argument "-" means sys.std{in,out}
1173 if string == '-':
1174 if 'r' in self._mode:
1175 return _sys.stdin
1176 elif 'w' in self._mode:
1177 return _sys.stdout
1178 else:
Éric Araujoa9c7a8f2010-12-03 19:19:17 +00001179 msg = _('argument "-" with mode %r') % self._mode
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001180 raise ValueError(msg)
1181
1182 # all other arguments are used as file names
Steven Bethardb0270112011-01-24 21:02:50 +00001183 try:
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001184 return open(string, self._mode, self._bufsize, self._encoding,
1185 self._errors)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001186 except OSError as e:
Steven Bethardb0270112011-01-24 21:02:50 +00001187 message = _("can't open '%s': %s")
1188 raise ArgumentTypeError(message % (string, e))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001189
1190 def __repr__(self):
Steven Bethardb0270112011-01-24 21:02:50 +00001191 args = self._mode, self._bufsize
Petri Lehtinen74d6c252012-12-15 22:39:32 +02001192 kwargs = [('encoding', self._encoding), ('errors', self._errors)]
1193 args_str = ', '.join([repr(arg) for arg in args if arg != -1] +
1194 ['%s=%r' % (kw, arg) for kw, arg in kwargs
1195 if arg is not None])
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001196 return '%s(%s)' % (type(self).__name__, args_str)
1197
1198# ===========================
1199# Optional and Positional Parsing
1200# ===========================
1201
1202class Namespace(_AttributeHolder):
1203 """Simple object for storing attributes.
1204
1205 Implements equality by attribute names and values, and provides a simple
1206 string representation.
1207 """
1208
1209 def __init__(self, **kwargs):
1210 for name in kwargs:
1211 setattr(self, name, kwargs[name])
1212
1213 def __eq__(self, other):
Raymond Hettingerdea46ec2014-05-26 00:43:27 -07001214 if not isinstance(other, Namespace):
1215 return NotImplemented
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001216 return vars(self) == vars(other)
1217
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001218 def __contains__(self, key):
1219 return key in self.__dict__
1220
1221
1222class _ActionsContainer(object):
1223
1224 def __init__(self,
1225 description,
1226 prefix_chars,
1227 argument_default,
1228 conflict_handler):
1229 super(_ActionsContainer, self).__init__()
1230
1231 self.description = description
1232 self.argument_default = argument_default
1233 self.prefix_chars = prefix_chars
1234 self.conflict_handler = conflict_handler
1235
1236 # set up registries
1237 self._registries = {}
1238
1239 # register actions
1240 self.register('action', None, _StoreAction)
1241 self.register('action', 'store', _StoreAction)
1242 self.register('action', 'store_const', _StoreConstAction)
1243 self.register('action', 'store_true', _StoreTrueAction)
1244 self.register('action', 'store_false', _StoreFalseAction)
1245 self.register('action', 'append', _AppendAction)
1246 self.register('action', 'append_const', _AppendConstAction)
1247 self.register('action', 'count', _CountAction)
1248 self.register('action', 'help', _HelpAction)
1249 self.register('action', 'version', _VersionAction)
1250 self.register('action', 'parsers', _SubParsersAction)
1251
1252 # raise an exception if the conflict handler is invalid
1253 self._get_handler()
1254
1255 # action storage
1256 self._actions = []
1257 self._option_string_actions = {}
1258
1259 # groups
1260 self._action_groups = []
1261 self._mutually_exclusive_groups = []
1262
1263 # defaults storage
1264 self._defaults = {}
1265
1266 # determines whether an "option" looks like a negative number
1267 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1268
1269 # whether or not there are any optionals that look like negative
1270 # numbers -- uses a list so it can be shared and edited
1271 self._has_negative_number_optionals = []
1272
1273 # ====================
1274 # Registration methods
1275 # ====================
1276 def register(self, registry_name, value, object):
1277 registry = self._registries.setdefault(registry_name, {})
1278 registry[value] = object
1279
1280 def _registry_get(self, registry_name, value, default=None):
1281 return self._registries[registry_name].get(value, default)
1282
1283 # ==================================
1284 # Namespace default accessor methods
1285 # ==================================
1286 def set_defaults(self, **kwargs):
1287 self._defaults.update(kwargs)
1288
1289 # if these defaults match any existing arguments, replace
1290 # the previous default on the object with the new one
1291 for action in self._actions:
1292 if action.dest in kwargs:
1293 action.default = kwargs[action.dest]
1294
1295 def get_default(self, dest):
1296 for action in self._actions:
1297 if action.dest == dest and action.default is not None:
1298 return action.default
1299 return self._defaults.get(dest, None)
1300
1301
1302 # =======================
1303 # Adding argument actions
1304 # =======================
1305 def add_argument(self, *args, **kwargs):
1306 """
1307 add_argument(dest, ..., name=value, ...)
1308 add_argument(option_string, option_string, ..., name=value, ...)
1309 """
1310
1311 # if no positional args are supplied or only one is supplied and
1312 # it doesn't look like an option string, parse a positional
1313 # argument
1314 chars = self.prefix_chars
1315 if not args or len(args) == 1 and args[0][0] not in chars:
1316 if args and 'dest' in kwargs:
1317 raise ValueError('dest supplied twice for positional argument')
1318 kwargs = self._get_positional_kwargs(*args, **kwargs)
1319
1320 # otherwise, we're adding an optional argument
1321 else:
1322 kwargs = self._get_optional_kwargs(*args, **kwargs)
1323
1324 # if no default was supplied, use the parser-level default
1325 if 'default' not in kwargs:
1326 dest = kwargs['dest']
1327 if dest in self._defaults:
1328 kwargs['default'] = self._defaults[dest]
1329 elif self.argument_default is not None:
1330 kwargs['default'] = self.argument_default
1331
1332 # create the action object, and add it to the parser
1333 action_class = self._pop_action_class(kwargs)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001334 if not callable(action_class):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001335 raise ValueError('unknown action "%s"' % (action_class,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001336 action = action_class(**kwargs)
1337
1338 # raise an error if the action type is not callable
1339 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001340 if not callable(type_func):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001341 raise ValueError('%r is not callable' % (type_func,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001342
Steven Bethard8d9a4622011-03-26 17:33:56 +01001343 # raise an error if the metavar does not match the type
1344 if hasattr(self, "_get_formatter"):
1345 try:
1346 self._get_formatter()._format_args(action, None)
1347 except TypeError:
1348 raise ValueError("length of metavar tuple does not match nargs")
1349
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001350 return self._add_action(action)
1351
1352 def add_argument_group(self, *args, **kwargs):
1353 group = _ArgumentGroup(self, *args, **kwargs)
1354 self._action_groups.append(group)
1355 return group
1356
1357 def add_mutually_exclusive_group(self, **kwargs):
1358 group = _MutuallyExclusiveGroup(self, **kwargs)
1359 self._mutually_exclusive_groups.append(group)
1360 return group
1361
1362 def _add_action(self, action):
1363 # resolve any conflicts
1364 self._check_conflict(action)
1365
1366 # add to actions list
1367 self._actions.append(action)
1368 action.container = self
1369
1370 # index the action by any option strings it has
1371 for option_string in action.option_strings:
1372 self._option_string_actions[option_string] = action
1373
1374 # set the flag if any option strings look like negative numbers
1375 for option_string in action.option_strings:
1376 if self._negative_number_matcher.match(option_string):
1377 if not self._has_negative_number_optionals:
1378 self._has_negative_number_optionals.append(True)
1379
1380 # return the created action
1381 return action
1382
1383 def _remove_action(self, action):
1384 self._actions.remove(action)
1385
1386 def _add_container_actions(self, container):
1387 # collect groups by titles
1388 title_group_map = {}
1389 for group in self._action_groups:
1390 if group.title in title_group_map:
1391 msg = _('cannot merge actions - two groups are named %r')
1392 raise ValueError(msg % (group.title))
1393 title_group_map[group.title] = group
1394
1395 # map each action to its group
1396 group_map = {}
1397 for group in container._action_groups:
1398
1399 # if a group with the title exists, use that, otherwise
1400 # create a new group matching the container's group
1401 if group.title not in title_group_map:
1402 title_group_map[group.title] = self.add_argument_group(
1403 title=group.title,
1404 description=group.description,
1405 conflict_handler=group.conflict_handler)
1406
1407 # map the actions to their new group
1408 for action in group._group_actions:
1409 group_map[action] = title_group_map[group.title]
1410
1411 # add container's mutually exclusive groups
1412 # NOTE: if add_mutually_exclusive_group ever gains title= and
1413 # description= then this code will need to be expanded as above
1414 for group in container._mutually_exclusive_groups:
1415 mutex_group = self.add_mutually_exclusive_group(
1416 required=group.required)
1417
1418 # map the actions to their new mutex group
1419 for action in group._group_actions:
1420 group_map[action] = mutex_group
1421
1422 # add all actions to this container or their group
1423 for action in container._actions:
1424 group_map.get(action, self)._add_action(action)
1425
1426 def _get_positional_kwargs(self, dest, **kwargs):
1427 # make sure required is not specified
1428 if 'required' in kwargs:
1429 msg = _("'required' is an invalid argument for positionals")
1430 raise TypeError(msg)
1431
1432 # mark positional arguments as required if at least one is
1433 # always required
1434 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1435 kwargs['required'] = True
1436 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1437 kwargs['required'] = True
1438
1439 # return the keyword arguments with no option strings
1440 return dict(kwargs, dest=dest, option_strings=[])
1441
1442 def _get_optional_kwargs(self, *args, **kwargs):
1443 # determine short and long option strings
1444 option_strings = []
1445 long_option_strings = []
1446 for option_string in args:
1447 # error on strings that don't start with an appropriate prefix
1448 if not option_string[0] in self.prefix_chars:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001449 args = {'option': option_string,
1450 'prefix_chars': self.prefix_chars}
1451 msg = _('invalid option string %(option)r: '
1452 'must start with a character %(prefix_chars)r')
1453 raise ValueError(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001454
1455 # strings starting with two prefix characters are long options
1456 option_strings.append(option_string)
1457 if option_string[0] in self.prefix_chars:
1458 if len(option_string) > 1:
1459 if option_string[1] in self.prefix_chars:
1460 long_option_strings.append(option_string)
1461
1462 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1463 dest = kwargs.pop('dest', None)
1464 if dest is None:
1465 if long_option_strings:
1466 dest_option_string = long_option_strings[0]
1467 else:
1468 dest_option_string = option_strings[0]
1469 dest = dest_option_string.lstrip(self.prefix_chars)
1470 if not dest:
1471 msg = _('dest= is required for options like %r')
1472 raise ValueError(msg % option_string)
1473 dest = dest.replace('-', '_')
1474
1475 # return the updated keyword arguments
1476 return dict(kwargs, dest=dest, option_strings=option_strings)
1477
1478 def _pop_action_class(self, kwargs, default=None):
1479 action = kwargs.pop('action', default)
1480 return self._registry_get('action', action, action)
1481
1482 def _get_handler(self):
1483 # determine function from conflict handler string
1484 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1485 try:
1486 return getattr(self, handler_func_name)
1487 except AttributeError:
1488 msg = _('invalid conflict_resolution value: %r')
1489 raise ValueError(msg % self.conflict_handler)
1490
1491 def _check_conflict(self, action):
1492
1493 # find all options that conflict with this option
1494 confl_optionals = []
1495 for option_string in action.option_strings:
1496 if option_string in self._option_string_actions:
1497 confl_optional = self._option_string_actions[option_string]
1498 confl_optionals.append((option_string, confl_optional))
1499
1500 # resolve any conflicts
1501 if confl_optionals:
1502 conflict_handler = self._get_handler()
1503 conflict_handler(action, confl_optionals)
1504
1505 def _handle_conflict_error(self, action, conflicting_actions):
Éric Araujo12159152010-12-04 17:31:49 +00001506 message = ngettext('conflicting option string: %s',
1507 'conflicting option strings: %s',
1508 len(conflicting_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001509 conflict_string = ', '.join([option_string
1510 for option_string, action
1511 in conflicting_actions])
1512 raise ArgumentError(action, message % conflict_string)
1513
1514 def _handle_conflict_resolve(self, action, conflicting_actions):
1515
1516 # remove all conflicting options
1517 for option_string, action in conflicting_actions:
1518
1519 # remove the conflicting option
1520 action.option_strings.remove(option_string)
1521 self._option_string_actions.pop(option_string, None)
1522
1523 # if the option now has no option string, remove it from the
1524 # container holding it
1525 if not action.option_strings:
1526 action.container._remove_action(action)
1527
1528
1529class _ArgumentGroup(_ActionsContainer):
1530
1531 def __init__(self, container, title=None, description=None, **kwargs):
1532 # add any missing keyword arguments by checking the container
1533 update = kwargs.setdefault
1534 update('conflict_handler', container.conflict_handler)
1535 update('prefix_chars', container.prefix_chars)
1536 update('argument_default', container.argument_default)
1537 super_init = super(_ArgumentGroup, self).__init__
1538 super_init(description=description, **kwargs)
1539
1540 # group attributes
1541 self.title = title
1542 self._group_actions = []
1543
1544 # share most attributes with the container
1545 self._registries = container._registries
1546 self._actions = container._actions
1547 self._option_string_actions = container._option_string_actions
1548 self._defaults = container._defaults
1549 self._has_negative_number_optionals = \
1550 container._has_negative_number_optionals
Georg Brandl0f6b47a2011-01-30 12:19:35 +00001551 self._mutually_exclusive_groups = container._mutually_exclusive_groups
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001552
1553 def _add_action(self, action):
1554 action = super(_ArgumentGroup, self)._add_action(action)
1555 self._group_actions.append(action)
1556 return action
1557
1558 def _remove_action(self, action):
1559 super(_ArgumentGroup, self)._remove_action(action)
1560 self._group_actions.remove(action)
1561
1562
1563class _MutuallyExclusiveGroup(_ArgumentGroup):
1564
1565 def __init__(self, container, required=False):
1566 super(_MutuallyExclusiveGroup, self).__init__(container)
1567 self.required = required
1568 self._container = container
1569
1570 def _add_action(self, action):
1571 if action.required:
1572 msg = _('mutually exclusive arguments must be optional')
1573 raise ValueError(msg)
1574 action = self._container._add_action(action)
1575 self._group_actions.append(action)
1576 return action
1577
1578 def _remove_action(self, action):
1579 self._container._remove_action(action)
1580 self._group_actions.remove(action)
1581
1582
1583class ArgumentParser(_AttributeHolder, _ActionsContainer):
1584 """Object for parsing command line strings into Python objects.
1585
1586 Keyword Arguments:
1587 - prog -- The name of the program (default: sys.argv[0])
1588 - usage -- A usage message (default: auto-generated from arguments)
1589 - description -- A description of what the program does
1590 - epilog -- Text following the argument descriptions
1591 - parents -- Parsers whose arguments should be copied into this one
1592 - formatter_class -- HelpFormatter class for printing help messages
1593 - prefix_chars -- Characters that prefix optional arguments
1594 - fromfile_prefix_chars -- Characters that prefix files containing
1595 additional arguments
1596 - argument_default -- The default value for all arguments
1597 - conflict_handler -- String indicating how to handle conflicts
1598 - add_help -- Add a -h/-help option
Berker Peksag8089cd62015-02-14 01:39:17 +02001599 - allow_abbrev -- Allow long options to be abbreviated unambiguously
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001600 """
1601
1602 def __init__(self,
1603 prog=None,
1604 usage=None,
1605 description=None,
1606 epilog=None,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001607 parents=[],
1608 formatter_class=HelpFormatter,
1609 prefix_chars='-',
1610 fromfile_prefix_chars=None,
1611 argument_default=None,
1612 conflict_handler='error',
Berker Peksag8089cd62015-02-14 01:39:17 +02001613 add_help=True,
1614 allow_abbrev=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001615
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001616 superinit = super(ArgumentParser, self).__init__
1617 superinit(description=description,
1618 prefix_chars=prefix_chars,
1619 argument_default=argument_default,
1620 conflict_handler=conflict_handler)
1621
1622 # default setting for prog
1623 if prog is None:
1624 prog = _os.path.basename(_sys.argv[0])
1625
1626 self.prog = prog
1627 self.usage = usage
1628 self.epilog = epilog
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001629 self.formatter_class = formatter_class
1630 self.fromfile_prefix_chars = fromfile_prefix_chars
1631 self.add_help = add_help
Berker Peksag8089cd62015-02-14 01:39:17 +02001632 self.allow_abbrev = allow_abbrev
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001633
1634 add_group = self.add_argument_group
1635 self._positionals = add_group(_('positional arguments'))
1636 self._optionals = add_group(_('optional arguments'))
1637 self._subparsers = None
1638
1639 # register types
1640 def identity(string):
1641 return string
1642 self.register('type', None, identity)
1643
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001644 # add help argument if necessary
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001645 # (using explicit default to override global argument_default)
R. David Murray88c49fe2010-08-03 17:56:09 +00001646 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001647 if self.add_help:
1648 self.add_argument(
R. David Murray88c49fe2010-08-03 17:56:09 +00001649 default_prefix+'h', default_prefix*2+'help',
1650 action='help', default=SUPPRESS,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001651 help=_('show this help message and exit'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001652
1653 # add parent arguments and defaults
1654 for parent in parents:
1655 self._add_container_actions(parent)
1656 try:
1657 defaults = parent._defaults
1658 except AttributeError:
1659 pass
1660 else:
1661 self._defaults.update(defaults)
1662
1663 # =======================
1664 # Pretty __repr__ methods
1665 # =======================
1666 def _get_kwargs(self):
1667 names = [
1668 'prog',
1669 'usage',
1670 'description',
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001671 'formatter_class',
1672 'conflict_handler',
1673 'add_help',
1674 ]
1675 return [(name, getattr(self, name)) for name in names]
1676
1677 # ==================================
1678 # Optional/Positional adding methods
1679 # ==================================
1680 def add_subparsers(self, **kwargs):
1681 if self._subparsers is not None:
1682 self.error(_('cannot have multiple subparser arguments'))
1683
1684 # add the parser class to the arguments if it's not present
1685 kwargs.setdefault('parser_class', type(self))
1686
1687 if 'title' in kwargs or 'description' in kwargs:
1688 title = _(kwargs.pop('title', 'subcommands'))
1689 description = _(kwargs.pop('description', None))
1690 self._subparsers = self.add_argument_group(title, description)
1691 else:
1692 self._subparsers = self._positionals
1693
1694 # prog defaults to the usage message of this parser, skipping
1695 # optional arguments and with no "usage:" prefix
1696 if kwargs.get('prog') is None:
1697 formatter = self._get_formatter()
1698 positionals = self._get_positional_actions()
1699 groups = self._mutually_exclusive_groups
1700 formatter.add_usage(self.usage, positionals, groups, '')
1701 kwargs['prog'] = formatter.format_help().strip()
1702
1703 # create the parsers action and add it to the positionals list
1704 parsers_class = self._pop_action_class(kwargs, 'parsers')
1705 action = parsers_class(option_strings=[], **kwargs)
1706 self._subparsers._add_action(action)
1707
1708 # return the created parsers action
1709 return action
1710
1711 def _add_action(self, action):
1712 if action.option_strings:
1713 self._optionals._add_action(action)
1714 else:
1715 self._positionals._add_action(action)
1716 return action
1717
1718 def _get_optional_actions(self):
1719 return [action
1720 for action in self._actions
1721 if action.option_strings]
1722
1723 def _get_positional_actions(self):
1724 return [action
1725 for action in self._actions
1726 if not action.option_strings]
1727
1728 # =====================================
1729 # Command line argument parsing methods
1730 # =====================================
1731 def parse_args(self, args=None, namespace=None):
1732 args, argv = self.parse_known_args(args, namespace)
1733 if argv:
1734 msg = _('unrecognized arguments: %s')
1735 self.error(msg % ' '.join(argv))
1736 return args
1737
1738 def parse_known_args(self, args=None, namespace=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001739 if args is None:
R David Murrayb5228282012-09-08 12:08:01 -04001740 # args default to the system args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001741 args = _sys.argv[1:]
R David Murrayb5228282012-09-08 12:08:01 -04001742 else:
1743 # make sure that args are mutable
1744 args = list(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001745
1746 # default Namespace built from parser defaults
1747 if namespace is None:
1748 namespace = Namespace()
1749
1750 # add any action defaults that aren't present
1751 for action in self._actions:
1752 if action.dest is not SUPPRESS:
1753 if not hasattr(namespace, action.dest):
1754 if action.default is not SUPPRESS:
R David Murray6fb8fb12012-08-31 22:45:20 -04001755 setattr(namespace, action.dest, action.default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001756
1757 # add any parser defaults that aren't present
1758 for dest in self._defaults:
1759 if not hasattr(namespace, dest):
1760 setattr(namespace, dest, self._defaults[dest])
1761
1762 # parse the arguments and exit if there are any errors
1763 try:
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001764 namespace, args = self._parse_known_args(args, namespace)
1765 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1766 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1767 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1768 return namespace, args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001769 except ArgumentError:
1770 err = _sys.exc_info()[1]
1771 self.error(str(err))
1772
1773 def _parse_known_args(self, arg_strings, namespace):
1774 # replace arg strings that are file references
1775 if self.fromfile_prefix_chars is not None:
1776 arg_strings = self._read_args_from_files(arg_strings)
1777
1778 # map all mutually exclusive arguments to the other arguments
1779 # they can't occur with
1780 action_conflicts = {}
1781 for mutex_group in self._mutually_exclusive_groups:
1782 group_actions = mutex_group._group_actions
1783 for i, mutex_action in enumerate(mutex_group._group_actions):
1784 conflicts = action_conflicts.setdefault(mutex_action, [])
1785 conflicts.extend(group_actions[:i])
1786 conflicts.extend(group_actions[i + 1:])
1787
1788 # find all option indices, and determine the arg_string_pattern
1789 # which has an 'O' if there is an option at an index,
1790 # an 'A' if there is an argument, or a '-' if there is a '--'
1791 option_string_indices = {}
1792 arg_string_pattern_parts = []
1793 arg_strings_iter = iter(arg_strings)
1794 for i, arg_string in enumerate(arg_strings_iter):
1795
1796 # all args after -- are non-options
1797 if arg_string == '--':
1798 arg_string_pattern_parts.append('-')
1799 for arg_string in arg_strings_iter:
1800 arg_string_pattern_parts.append('A')
1801
1802 # otherwise, add the arg to the arg strings
1803 # and note the index if it was an option
1804 else:
1805 option_tuple = self._parse_optional(arg_string)
1806 if option_tuple is None:
1807 pattern = 'A'
1808 else:
1809 option_string_indices[i] = option_tuple
1810 pattern = 'O'
1811 arg_string_pattern_parts.append(pattern)
1812
1813 # join the pieces together to form the pattern
1814 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1815
1816 # converts arg strings to the appropriate and then takes the action
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00001817 seen_actions = set()
1818 seen_non_default_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001819
1820 def take_action(action, argument_strings, option_string=None):
1821 seen_actions.add(action)
1822 argument_values = self._get_values(action, argument_strings)
1823
1824 # error if this argument is not allowed with other previously
1825 # seen arguments, assuming that actions that use the default
1826 # value don't really count as "present"
1827 if argument_values is not action.default:
1828 seen_non_default_actions.add(action)
1829 for conflict_action in action_conflicts.get(action, []):
1830 if conflict_action in seen_non_default_actions:
1831 msg = _('not allowed with argument %s')
1832 action_name = _get_action_name(conflict_action)
1833 raise ArgumentError(action, msg % action_name)
1834
1835 # take the action if we didn't receive a SUPPRESS value
1836 # (e.g. from a default)
1837 if argument_values is not SUPPRESS:
1838 action(self, namespace, argument_values, option_string)
1839
1840 # function to convert arg_strings into an optional action
1841 def consume_optional(start_index):
1842
1843 # get the optional identified at this index
1844 option_tuple = option_string_indices[start_index]
1845 action, option_string, explicit_arg = option_tuple
1846
1847 # identify additional optionals in the same arg string
1848 # (e.g. -xyz is the same as -x -y -z if no args are required)
1849 match_argument = self._match_argument
1850 action_tuples = []
1851 while True:
1852
1853 # if we found no optional action, skip it
1854 if action is None:
1855 extras.append(arg_strings[start_index])
1856 return start_index + 1
1857
1858 # if there is an explicit argument, try to match the
1859 # optional's string arguments to only this
1860 if explicit_arg is not None:
1861 arg_count = match_argument(action, 'A')
1862
1863 # if the action is a single-dash option and takes no
1864 # arguments, try to parse more single-dash options out
1865 # of the tail of the option string
1866 chars = self.prefix_chars
1867 if arg_count == 0 and option_string[1] not in chars:
1868 action_tuples.append((action, [], option_string))
Steven Bethard1ca45a52010-11-01 15:57:36 +00001869 char = option_string[0]
1870 option_string = char + explicit_arg[0]
1871 new_explicit_arg = explicit_arg[1:] or None
1872 optionals_map = self._option_string_actions
1873 if option_string in optionals_map:
1874 action = optionals_map[option_string]
1875 explicit_arg = new_explicit_arg
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001876 else:
1877 msg = _('ignored explicit argument %r')
1878 raise ArgumentError(action, msg % explicit_arg)
1879
1880 # if the action expect exactly one argument, we've
1881 # successfully matched the option; exit the loop
1882 elif arg_count == 1:
1883 stop = start_index + 1
1884 args = [explicit_arg]
1885 action_tuples.append((action, args, option_string))
1886 break
1887
1888 # error if a double-dash option did not use the
1889 # explicit argument
1890 else:
1891 msg = _('ignored explicit argument %r')
1892 raise ArgumentError(action, msg % explicit_arg)
1893
1894 # if there is no explicit argument, try to match the
1895 # optional's string arguments with the following strings
1896 # if successful, exit the loop
1897 else:
1898 start = start_index + 1
1899 selected_patterns = arg_strings_pattern[start:]
1900 arg_count = match_argument(action, selected_patterns)
1901 stop = start + arg_count
1902 args = arg_strings[start:stop]
1903 action_tuples.append((action, args, option_string))
1904 break
1905
1906 # add the Optional to the list and return the index at which
1907 # the Optional's string args stopped
1908 assert action_tuples
1909 for action, args, option_string in action_tuples:
1910 take_action(action, args, option_string)
1911 return stop
1912
1913 # the list of Positionals left to be parsed; this is modified
1914 # by consume_positionals()
1915 positionals = self._get_positional_actions()
1916
1917 # function to convert arg_strings into positional actions
1918 def consume_positionals(start_index):
1919 # match as many Positionals as possible
1920 match_partial = self._match_arguments_partial
1921 selected_pattern = arg_strings_pattern[start_index:]
1922 arg_counts = match_partial(positionals, selected_pattern)
1923
1924 # slice off the appropriate arg strings for each Positional
1925 # and add the Positional and its args to the list
1926 for action, arg_count in zip(positionals, arg_counts):
1927 args = arg_strings[start_index: start_index + arg_count]
1928 start_index += arg_count
1929 take_action(action, args)
1930
1931 # slice off the Positionals that we just parsed and return the
1932 # index at which the Positionals' string args stopped
1933 positionals[:] = positionals[len(arg_counts):]
1934 return start_index
1935
1936 # consume Positionals and Optionals alternately, until we have
1937 # passed the last option string
1938 extras = []
1939 start_index = 0
1940 if option_string_indices:
1941 max_option_string_index = max(option_string_indices)
1942 else:
1943 max_option_string_index = -1
1944 while start_index <= max_option_string_index:
1945
1946 # consume any Positionals preceding the next option
1947 next_option_string_index = min([
1948 index
1949 for index in option_string_indices
1950 if index >= start_index])
1951 if start_index != next_option_string_index:
1952 positionals_end_index = consume_positionals(start_index)
1953
1954 # only try to parse the next optional if we didn't consume
1955 # the option string during the positionals parsing
1956 if positionals_end_index > start_index:
1957 start_index = positionals_end_index
1958 continue
1959 else:
1960 start_index = positionals_end_index
1961
1962 # if we consumed all the positionals we could and we're not
1963 # at the index of an option string, there were extra arguments
1964 if start_index not in option_string_indices:
1965 strings = arg_strings[start_index:next_option_string_index]
1966 extras.extend(strings)
1967 start_index = next_option_string_index
1968
1969 # consume the next optional and any arguments for it
1970 start_index = consume_optional(start_index)
1971
1972 # consume any positionals following the last Optional
1973 stop_index = consume_positionals(start_index)
1974
1975 # if we didn't consume all the argument strings, there were extras
1976 extras.extend(arg_strings[stop_index:])
1977
R David Murray64b0ef12012-08-31 23:09:34 -04001978 # make sure all required actions were present and also convert
1979 # action defaults which were not given as arguments
1980 required_actions = []
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001981 for action in self._actions:
R David Murray6fb8fb12012-08-31 22:45:20 -04001982 if action not in seen_actions:
1983 if action.required:
R David Murray64b0ef12012-08-31 23:09:34 -04001984 required_actions.append(_get_action_name(action))
R David Murray6fb8fb12012-08-31 22:45:20 -04001985 else:
1986 # Convert action default now instead of doing it before
1987 # parsing arguments to avoid calling convert functions
1988 # twice (which may fail) if the argument was given, but
1989 # only if it was defined already in the namespace
1990 if (action.default is not None and
Barry Warsawd89774e2012-09-12 15:31:38 -04001991 isinstance(action.default, str) and
R David Murray64b0ef12012-08-31 23:09:34 -04001992 hasattr(namespace, action.dest) and
1993 action.default is getattr(namespace, action.dest)):
R David Murray6fb8fb12012-08-31 22:45:20 -04001994 setattr(namespace, action.dest,
1995 self._get_value(action, action.default))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001996
R David Murrayf97c59a2011-06-09 12:34:07 -04001997 if required_actions:
1998 self.error(_('the following arguments are required: %s') %
1999 ', '.join(required_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002000
2001 # make sure all required groups had one option present
2002 for group in self._mutually_exclusive_groups:
2003 if group.required:
2004 for action in group._group_actions:
2005 if action in seen_non_default_actions:
2006 break
2007
2008 # if no actions were used, report the error
2009 else:
2010 names = [_get_action_name(action)
2011 for action in group._group_actions
2012 if action.help is not SUPPRESS]
2013 msg = _('one of the arguments %s is required')
2014 self.error(msg % ' '.join(names))
2015
2016 # return the updated namespace and the extra arguments
2017 return namespace, extras
2018
2019 def _read_args_from_files(self, arg_strings):
2020 # expand arguments referencing files
2021 new_arg_strings = []
2022 for arg_string in arg_strings:
2023
2024 # for regular arguments, just add them back into the list
R David Murrayb94082a2012-07-21 22:20:11 -04002025 if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002026 new_arg_strings.append(arg_string)
2027
2028 # replace arguments referencing files with the file content
2029 else:
2030 try:
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01002031 with open(arg_string[1:]) as args_file:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002032 arg_strings = []
2033 for arg_line in args_file.read().splitlines():
2034 for arg in self.convert_arg_line_to_args(arg_line):
2035 arg_strings.append(arg)
2036 arg_strings = self._read_args_from_files(arg_strings)
2037 new_arg_strings.extend(arg_strings)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002038 except OSError:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002039 err = _sys.exc_info()[1]
2040 self.error(str(err))
2041
2042 # return the modified argument list
2043 return new_arg_strings
2044
2045 def convert_arg_line_to_args(self, arg_line):
2046 return [arg_line]
2047
2048 def _match_argument(self, action, arg_strings_pattern):
2049 # match the pattern for this action to the arg strings
2050 nargs_pattern = self._get_nargs_pattern(action)
2051 match = _re.match(nargs_pattern, arg_strings_pattern)
2052
2053 # raise an exception if we weren't able to find a match
2054 if match is None:
2055 nargs_errors = {
2056 None: _('expected one argument'),
2057 OPTIONAL: _('expected at most one argument'),
2058 ONE_OR_MORE: _('expected at least one argument'),
2059 }
Éric Araujo12159152010-12-04 17:31:49 +00002060 default = ngettext('expected %s argument',
2061 'expected %s arguments',
2062 action.nargs) % action.nargs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002063 msg = nargs_errors.get(action.nargs, default)
2064 raise ArgumentError(action, msg)
2065
2066 # return the number of arguments matched
2067 return len(match.group(1))
2068
2069 def _match_arguments_partial(self, actions, arg_strings_pattern):
2070 # progressively shorten the actions list by slicing off the
2071 # final actions until we find a match
2072 result = []
2073 for i in range(len(actions), 0, -1):
2074 actions_slice = actions[:i]
2075 pattern = ''.join([self._get_nargs_pattern(action)
2076 for action in actions_slice])
2077 match = _re.match(pattern, arg_strings_pattern)
2078 if match is not None:
2079 result.extend([len(string) for string in match.groups()])
2080 break
2081
2082 # return the list of arg string counts
2083 return result
2084
2085 def _parse_optional(self, arg_string):
2086 # if it's an empty string, it was meant to be a positional
2087 if not arg_string:
2088 return None
2089
2090 # if it doesn't start with a prefix, it was meant to be positional
2091 if not arg_string[0] in self.prefix_chars:
2092 return None
2093
2094 # if the option string is present in the parser, return the action
2095 if arg_string in self._option_string_actions:
2096 action = self._option_string_actions[arg_string]
2097 return action, arg_string, None
2098
2099 # if it's just a single character, it was meant to be positional
2100 if len(arg_string) == 1:
2101 return None
2102
2103 # if the option string before the "=" is present, return the action
2104 if '=' in arg_string:
2105 option_string, explicit_arg = arg_string.split('=', 1)
2106 if option_string in self._option_string_actions:
2107 action = self._option_string_actions[option_string]
2108 return action, option_string, explicit_arg
2109
Berker Peksag8089cd62015-02-14 01:39:17 +02002110 if self.allow_abbrev:
2111 # search through all possible prefixes of the option string
2112 # and all actions in the parser for possible interpretations
2113 option_tuples = self._get_option_tuples(arg_string)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002114
Berker Peksag8089cd62015-02-14 01:39:17 +02002115 # if multiple actions match, the option string was ambiguous
2116 if len(option_tuples) > 1:
2117 options = ', '.join([option_string
2118 for action, option_string, explicit_arg in option_tuples])
2119 args = {'option': arg_string, 'matches': options}
2120 msg = _('ambiguous option: %(option)s could match %(matches)s')
2121 self.error(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002122
Berker Peksag8089cd62015-02-14 01:39:17 +02002123 # if exactly one action matched, this segmentation is good,
2124 # so return the parsed action
2125 elif len(option_tuples) == 1:
2126 option_tuple, = option_tuples
2127 return option_tuple
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002128
2129 # if it was not found as an option, but it looks like a negative
2130 # number, it was meant to be positional
2131 # unless there are negative-number-like options
2132 if self._negative_number_matcher.match(arg_string):
2133 if not self._has_negative_number_optionals:
2134 return None
2135
2136 # if it contains a space, it was meant to be a positional
2137 if ' ' in arg_string:
2138 return None
2139
2140 # it was meant to be an optional but there is no such option
2141 # in this parser (though it might be a valid option in a subparser)
2142 return None, arg_string, None
2143
2144 def _get_option_tuples(self, option_string):
2145 result = []
2146
2147 # option strings starting with two prefix characters are only
2148 # split at the '='
2149 chars = self.prefix_chars
2150 if option_string[0] in chars and option_string[1] in chars:
2151 if '=' in option_string:
2152 option_prefix, explicit_arg = option_string.split('=', 1)
2153 else:
2154 option_prefix = option_string
2155 explicit_arg = None
2156 for option_string in self._option_string_actions:
2157 if option_string.startswith(option_prefix):
2158 action = self._option_string_actions[option_string]
2159 tup = action, option_string, explicit_arg
2160 result.append(tup)
2161
2162 # single character options can be concatenated with their arguments
2163 # but multiple character options always have to have their argument
2164 # separate
2165 elif option_string[0] in chars and option_string[1] not in chars:
2166 option_prefix = option_string
2167 explicit_arg = None
2168 short_option_prefix = option_string[:2]
2169 short_explicit_arg = option_string[2:]
2170
2171 for option_string in self._option_string_actions:
2172 if option_string == short_option_prefix:
2173 action = self._option_string_actions[option_string]
2174 tup = action, option_string, short_explicit_arg
2175 result.append(tup)
2176 elif option_string.startswith(option_prefix):
2177 action = self._option_string_actions[option_string]
2178 tup = action, option_string, explicit_arg
2179 result.append(tup)
2180
2181 # shouldn't ever get here
2182 else:
2183 self.error(_('unexpected option string: %s') % option_string)
2184
2185 # return the collected option tuples
2186 return result
2187
2188 def _get_nargs_pattern(self, action):
2189 # in all examples below, we have to allow for '--' args
2190 # which are represented as '-' in the pattern
2191 nargs = action.nargs
2192
2193 # the default (None) is assumed to be a single argument
2194 if nargs is None:
2195 nargs_pattern = '(-*A-*)'
2196
2197 # allow zero or one arguments
2198 elif nargs == OPTIONAL:
2199 nargs_pattern = '(-*A?-*)'
2200
2201 # allow zero or more arguments
2202 elif nargs == ZERO_OR_MORE:
2203 nargs_pattern = '(-*[A-]*)'
2204
2205 # allow one or more arguments
2206 elif nargs == ONE_OR_MORE:
2207 nargs_pattern = '(-*A[A-]*)'
2208
2209 # allow any number of options or arguments
2210 elif nargs == REMAINDER:
2211 nargs_pattern = '([-AO]*)'
2212
2213 # allow one argument followed by any number of options or arguments
2214 elif nargs == PARSER:
2215 nargs_pattern = '(-*A[-AO]*)'
2216
2217 # all others should be integers
2218 else:
2219 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2220
2221 # if this is an optional action, -- is not allowed
2222 if action.option_strings:
2223 nargs_pattern = nargs_pattern.replace('-*', '')
2224 nargs_pattern = nargs_pattern.replace('-', '')
2225
2226 # return the pattern
2227 return nargs_pattern
2228
2229 # ========================
2230 # Value conversion methods
2231 # ========================
2232 def _get_values(self, action, arg_strings):
R David Murray00528e82012-07-21 22:48:35 -04002233 # for everything but PARSER, REMAINDER args, strip out first '--'
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002234 if action.nargs not in [PARSER, REMAINDER]:
R David Murray00528e82012-07-21 22:48:35 -04002235 try:
2236 arg_strings.remove('--')
2237 except ValueError:
2238 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002239
2240 # optional argument produces a default when not present
2241 if not arg_strings and action.nargs == OPTIONAL:
2242 if action.option_strings:
2243 value = action.const
2244 else:
2245 value = action.default
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00002246 if isinstance(value, str):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002247 value = self._get_value(action, value)
2248 self._check_value(action, value)
2249
2250 # when nargs='*' on a positional, if there were no command-line
2251 # args, use the default if it is anything other than None
2252 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2253 not action.option_strings):
2254 if action.default is not None:
2255 value = action.default
2256 else:
2257 value = arg_strings
2258 self._check_value(action, value)
2259
2260 # single argument or optional argument produces a single value
2261 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2262 arg_string, = arg_strings
2263 value = self._get_value(action, arg_string)
2264 self._check_value(action, value)
2265
2266 # REMAINDER arguments convert all values, checking none
2267 elif action.nargs == REMAINDER:
2268 value = [self._get_value(action, v) for v in arg_strings]
2269
2270 # PARSER arguments convert all values, but check only the first
2271 elif action.nargs == PARSER:
2272 value = [self._get_value(action, v) for v in arg_strings]
2273 self._check_value(action, value[0])
2274
2275 # all other types of nargs produce a list
2276 else:
2277 value = [self._get_value(action, v) for v in arg_strings]
2278 for v in value:
2279 self._check_value(action, v)
2280
2281 # return the converted value
2282 return value
2283
2284 def _get_value(self, action, arg_string):
2285 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02002286 if not callable(type_func):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002287 msg = _('%r is not callable')
2288 raise ArgumentError(action, msg % type_func)
2289
2290 # convert the value to the appropriate type
2291 try:
2292 result = type_func(arg_string)
2293
2294 # ArgumentTypeErrors indicate errors
2295 except ArgumentTypeError:
2296 name = getattr(action.type, '__name__', repr(action.type))
2297 msg = str(_sys.exc_info()[1])
2298 raise ArgumentError(action, msg)
2299
2300 # TypeErrors or ValueErrors also indicate errors
2301 except (TypeError, ValueError):
2302 name = getattr(action.type, '__name__', repr(action.type))
Éric Araujobb48a8b2010-12-03 19:41:00 +00002303 args = {'type': name, 'value': arg_string}
2304 msg = _('invalid %(type)s value: %(value)r')
2305 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002306
2307 # return the converted value
2308 return result
2309
2310 def _check_value(self, action, value):
2311 # converted value must be one of the choices (if specified)
2312 if action.choices is not None and value not in action.choices:
Éric Araujobb48a8b2010-12-03 19:41:00 +00002313 args = {'value': value,
2314 'choices': ', '.join(map(repr, action.choices))}
2315 msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2316 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002317
2318 # =======================
2319 # Help-formatting methods
2320 # =======================
2321 def format_usage(self):
2322 formatter = self._get_formatter()
2323 formatter.add_usage(self.usage, self._actions,
2324 self._mutually_exclusive_groups)
2325 return formatter.format_help()
2326
2327 def format_help(self):
2328 formatter = self._get_formatter()
2329
2330 # usage
2331 formatter.add_usage(self.usage, self._actions,
2332 self._mutually_exclusive_groups)
2333
2334 # description
2335 formatter.add_text(self.description)
2336
2337 # positionals, optionals and user-defined groups
2338 for action_group in self._action_groups:
2339 formatter.start_section(action_group.title)
2340 formatter.add_text(action_group.description)
2341 formatter.add_arguments(action_group._group_actions)
2342 formatter.end_section()
2343
2344 # epilog
2345 formatter.add_text(self.epilog)
2346
2347 # determine help from format above
2348 return formatter.format_help()
2349
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002350 def _get_formatter(self):
2351 return self.formatter_class(prog=self.prog)
2352
2353 # =====================
2354 # Help-printing methods
2355 # =====================
2356 def print_usage(self, file=None):
2357 if file is None:
2358 file = _sys.stdout
2359 self._print_message(self.format_usage(), file)
2360
2361 def print_help(self, file=None):
2362 if file is None:
2363 file = _sys.stdout
2364 self._print_message(self.format_help(), file)
2365
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002366 def _print_message(self, message, file=None):
2367 if message:
2368 if file is None:
2369 file = _sys.stderr
2370 file.write(message)
2371
2372 # ===============
2373 # Exiting methods
2374 # ===============
2375 def exit(self, status=0, message=None):
2376 if message:
2377 self._print_message(message, _sys.stderr)
2378 _sys.exit(status)
2379
2380 def error(self, message):
2381 """error(message: string)
2382
2383 Prints a usage message incorporating the message to stderr and
2384 exits.
2385
2386 If you override this in a subclass, it should not return -- it
2387 should either exit or raise an exception.
2388 """
2389 self.print_usage(_sys.stderr)
Éric Araujobb48a8b2010-12-03 19:41:00 +00002390 args = {'prog': self.prog, 'message': message}
2391 self.exit(2, _('%(prog)s: error: %(message)s\n') % args)