blob: bc2ba132eddc82671bc728f2b96607943a0f146e [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 = []
121 for arg in self._get_args():
122 arg_strings.append(repr(arg))
123 for name, value in self._get_kwargs():
124 arg_strings.append('%s=%r' % (name, value))
125 return '%s(%s)' % (type_name, ', '.join(arg_strings))
126
127 def _get_kwargs(self):
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000128 return sorted(self.__dict__.items())
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000129
130 def _get_args(self):
131 return []
132
133
134def _ensure_value(namespace, name, value):
135 if getattr(namespace, name, None) is None:
136 setattr(namespace, name, value)
137 return getattr(namespace, name)
138
139
140# ===============
141# Formatting Help
142# ===============
143
144class HelpFormatter(object):
145 """Formatter for generating usage messages and argument help strings.
146
147 Only the name of this class is considered a public API. All the methods
148 provided by the class are considered an implementation detail.
149 """
150
151 def __init__(self,
152 prog,
153 indent_increment=2,
154 max_help_position=24,
155 width=None):
156
157 # default setting for width
158 if width is None:
159 try:
160 width = int(_os.environ['COLUMNS'])
161 except (KeyError, ValueError):
162 width = 80
163 width -= 2
164
165 self._prog = prog
166 self._indent_increment = indent_increment
167 self._max_help_position = max_help_position
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200168 self._max_help_position = min(max_help_position,
169 max(width - 20, indent_increment * 2))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000170 self._width = width
171
172 self._current_indent = 0
173 self._level = 0
174 self._action_max_length = 0
175
176 self._root_section = self._Section(self, None)
177 self._current_section = self._root_section
178
179 self._whitespace_matcher = _re.compile(r'\s+')
180 self._long_break_matcher = _re.compile(r'\n\n\n+')
181
182 # ===============================
183 # Section and indentation methods
184 # ===============================
185 def _indent(self):
186 self._current_indent += self._indent_increment
187 self._level += 1
188
189 def _dedent(self):
190 self._current_indent -= self._indent_increment
191 assert self._current_indent >= 0, 'Indent decreased below 0.'
192 self._level -= 1
193
194 class _Section(object):
195
196 def __init__(self, formatter, parent, heading=None):
197 self.formatter = formatter
198 self.parent = parent
199 self.heading = heading
200 self.items = []
201
202 def format_help(self):
203 # format the indented section
204 if self.parent is not None:
205 self.formatter._indent()
206 join = self.formatter._join_parts
207 for func, args in self.items:
208 func(*args)
209 item_help = join([func(*args) for func, args in self.items])
210 if self.parent is not None:
211 self.formatter._dedent()
212
213 # return nothing if the section was empty
214 if not item_help:
215 return ''
216
217 # add the heading if the section was non-empty
218 if self.heading is not SUPPRESS and self.heading is not None:
219 current_indent = self.formatter._current_indent
220 heading = '%*s%s:\n' % (current_indent, '', self.heading)
221 else:
222 heading = ''
223
224 # join the section-initial newline, the heading and the help
225 return join(['\n', heading, item_help, '\n'])
226
227 def _add_item(self, func, args):
228 self._current_section.items.append((func, args))
229
230 # ========================
231 # Message building methods
232 # ========================
233 def start_section(self, heading):
234 self._indent()
235 section = self._Section(self, self._current_section, heading)
236 self._add_item(section.format_help, [])
237 self._current_section = section
238
239 def end_section(self):
240 self._current_section = self._current_section.parent
241 self._dedent()
242
243 def add_text(self, text):
244 if text is not SUPPRESS and text is not None:
245 self._add_item(self._format_text, [text])
246
247 def add_usage(self, usage, actions, groups, prefix=None):
248 if usage is not SUPPRESS:
249 args = usage, actions, groups, prefix
250 self._add_item(self._format_usage, args)
251
252 def add_argument(self, action):
253 if action.help is not SUPPRESS:
254
255 # find all invocations
256 get_invocation = self._format_action_invocation
257 invocations = [get_invocation(action)]
258 for subaction in self._iter_indented_subactions(action):
259 invocations.append(get_invocation(subaction))
260
261 # update the maximum item length
262 invocation_length = max([len(s) for s in invocations])
263 action_length = invocation_length + self._current_indent
264 self._action_max_length = max(self._action_max_length,
265 action_length)
266
267 # add the item to the list
268 self._add_item(self._format_action, [action])
269
270 def add_arguments(self, actions):
271 for action in actions:
272 self.add_argument(action)
273
274 # =======================
275 # Help-formatting methods
276 # =======================
277 def format_help(self):
278 help = self._root_section.format_help()
279 if help:
280 help = self._long_break_matcher.sub('\n\n', help)
281 help = help.strip('\n') + '\n'
282 return help
283
284 def _join_parts(self, part_strings):
285 return ''.join([part
286 for part in part_strings
287 if part and part is not SUPPRESS])
288
289 def _format_usage(self, usage, actions, groups, prefix):
290 if prefix is None:
291 prefix = _('usage: ')
292
293 # if usage is specified, use that
294 if usage is not None:
295 usage = usage % dict(prog=self._prog)
296
297 # if no optionals or positionals are available, usage is just prog
298 elif usage is None and not actions:
299 usage = '%(prog)s' % dict(prog=self._prog)
300
301 # if optionals and positionals are available, calculate usage
302 elif usage is None:
303 prog = '%(prog)s' % dict(prog=self._prog)
304
305 # split optionals from positionals
306 optionals = []
307 positionals = []
308 for action in actions:
309 if action.option_strings:
310 optionals.append(action)
311 else:
312 positionals.append(action)
313
314 # build full usage string
315 format = self._format_actions_usage
316 action_usage = format(optionals + positionals, groups)
317 usage = ' '.join([s for s in [prog, action_usage] if s])
318
319 # wrap the usage parts if it's too long
320 text_width = self._width - self._current_indent
321 if len(prefix) + len(usage) > text_width:
322
323 # break usage into wrappable parts
324 part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
325 opt_usage = format(optionals, groups)
326 pos_usage = format(positionals, groups)
327 opt_parts = _re.findall(part_regexp, opt_usage)
328 pos_parts = _re.findall(part_regexp, pos_usage)
329 assert ' '.join(opt_parts) == opt_usage
330 assert ' '.join(pos_parts) == pos_usage
331
332 # helper for wrapping lines
333 def get_lines(parts, indent, prefix=None):
334 lines = []
335 line = []
336 if prefix is not None:
337 line_len = len(prefix) - 1
338 else:
339 line_len = len(indent) - 1
340 for part in parts:
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200341 if line_len + 1 + len(part) > text_width and line:
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000342 lines.append(indent + ' '.join(line))
343 line = []
344 line_len = len(indent) - 1
345 line.append(part)
346 line_len += len(part) + 1
347 if line:
348 lines.append(indent + ' '.join(line))
349 if prefix is not None:
350 lines[0] = lines[0][len(indent):]
351 return lines
352
353 # if prog is short, follow it with optionals or positionals
354 if len(prefix) + len(prog) <= 0.75 * text_width:
355 indent = ' ' * (len(prefix) + len(prog) + 1)
356 if opt_parts:
357 lines = get_lines([prog] + opt_parts, indent, prefix)
358 lines.extend(get_lines(pos_parts, indent))
359 elif pos_parts:
360 lines = get_lines([prog] + pos_parts, indent, prefix)
361 else:
362 lines = [prog]
363
364 # if prog is long, put it on its own line
365 else:
366 indent = ' ' * len(prefix)
367 parts = opt_parts + pos_parts
368 lines = get_lines(parts, indent)
369 if len(lines) > 1:
370 lines = []
371 lines.extend(get_lines(opt_parts, indent))
372 lines.extend(get_lines(pos_parts, indent))
373 lines = [prog] + lines
374
375 # join lines into usage
376 usage = '\n'.join(lines)
377
378 # prefix with 'usage:'
379 return '%s%s\n\n' % (prefix, usage)
380
381 def _format_actions_usage(self, actions, groups):
382 # find group indices and identify actions in groups
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000383 group_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000384 inserts = {}
385 for group in groups:
386 try:
387 start = actions.index(group._group_actions[0])
388 except ValueError:
389 continue
390 else:
391 end = start + len(group._group_actions)
392 if actions[start:end] == group._group_actions:
393 for action in group._group_actions:
394 group_actions.add(action)
395 if not group.required:
Steven Bethard49998ee2010-11-01 16:29:26 +0000396 if start in inserts:
397 inserts[start] += ' ['
398 else:
399 inserts[start] = '['
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000400 inserts[end] = ']'
401 else:
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 for i in range(start + 1, end):
408 inserts[i] = '|'
409
410 # collect all actions format strings
411 parts = []
412 for i, action in enumerate(actions):
413
414 # suppressed arguments are marked with None
415 # remove | separators for suppressed arguments
416 if action.help is SUPPRESS:
417 parts.append(None)
418 if inserts.get(i) == '|':
419 inserts.pop(i)
420 elif inserts.get(i + 1) == '|':
421 inserts.pop(i + 1)
422
423 # produce all arg strings
424 elif not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100425 default = self._get_default_metavar_for_positional(action)
426 part = self._format_args(action, default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000427
428 # if it's in a group, strip the outer []
429 if action in group_actions:
430 if part[0] == '[' and part[-1] == ']':
431 part = part[1:-1]
432
433 # add the action string to the list
434 parts.append(part)
435
436 # produce the first way to invoke the option in brackets
437 else:
438 option_string = action.option_strings[0]
439
440 # if the Optional doesn't take a value, format is:
441 # -s or --long
442 if action.nargs == 0:
443 part = '%s' % option_string
444
445 # if the Optional takes a value, format is:
446 # -s ARGS or --long ARGS
447 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100448 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000449 args_string = self._format_args(action, default)
450 part = '%s %s' % (option_string, args_string)
451
452 # make it look optional if it's not required or in a group
453 if not action.required and action not in group_actions:
454 part = '[%s]' % part
455
456 # add the action string to the list
457 parts.append(part)
458
459 # insert things at the necessary indices
Benjamin Peterson16f2fd02010-03-02 23:09:38 +0000460 for i in sorted(inserts, reverse=True):
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000461 parts[i:i] = [inserts[i]]
462
463 # join all the action items with spaces
464 text = ' '.join([item for item in parts if item is not None])
465
466 # clean up separators for mutually exclusive groups
467 open = r'[\[(]'
468 close = r'[\])]'
469 text = _re.sub(r'(%s) ' % open, r'\1', text)
470 text = _re.sub(r' (%s)' % close, r'\1', text)
471 text = _re.sub(r'%s *%s' % (open, close), r'', text)
472 text = _re.sub(r'\(([^|]*)\)', r'\1', text)
473 text = text.strip()
474
475 # return the text
476 return text
477
478 def _format_text(self, text):
479 if '%(prog)' in text:
480 text = text % dict(prog=self._prog)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200481 text_width = max(self._width - self._current_indent, 11)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000482 indent = ' ' * self._current_indent
483 return self._fill_text(text, text_width, indent) + '\n\n'
484
485 def _format_action(self, action):
486 # determine the required width and the entry label
487 help_position = min(self._action_max_length + 2,
488 self._max_help_position)
Serhiy Storchakaf4511122014-01-09 23:14:27 +0200489 help_width = max(self._width - help_position, 11)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000490 action_width = help_position - self._current_indent - 2
491 action_header = self._format_action_invocation(action)
492
493 # ho nelp; start on same line and add a final newline
494 if not action.help:
495 tup = self._current_indent, '', action_header
496 action_header = '%*s%s\n' % tup
497
498 # short action name; start on the same line and pad two spaces
499 elif len(action_header) <= action_width:
500 tup = self._current_indent, '', action_width, action_header
501 action_header = '%*s%-*s ' % tup
502 indent_first = 0
503
504 # long action name; start on the next line
505 else:
506 tup = self._current_indent, '', action_header
507 action_header = '%*s%s\n' % tup
508 indent_first = help_position
509
510 # collect the pieces of the action help
511 parts = [action_header]
512
513 # if there was help for the action, add lines of help text
514 if action.help:
515 help_text = self._expand_help(action)
516 help_lines = self._split_lines(help_text, help_width)
517 parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
518 for line in help_lines[1:]:
519 parts.append('%*s%s\n' % (help_position, '', line))
520
521 # or add a newline if the description doesn't end with one
522 elif not action_header.endswith('\n'):
523 parts.append('\n')
524
525 # if there are any sub-actions, add their help as well
526 for subaction in self._iter_indented_subactions(action):
527 parts.append(self._format_action(subaction))
528
529 # return a single string
530 return self._join_parts(parts)
531
532 def _format_action_invocation(self, action):
533 if not action.option_strings:
Steven Bethard0331e902011-03-26 14:48:04 +0100534 default = self._get_default_metavar_for_positional(action)
535 metavar, = self._metavar_formatter(action, default)(1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000536 return metavar
537
538 else:
539 parts = []
540
541 # if the Optional doesn't take a value, format is:
542 # -s, --long
543 if action.nargs == 0:
544 parts.extend(action.option_strings)
545
546 # if the Optional takes a value, format is:
547 # -s ARGS, --long ARGS
548 else:
Steven Bethard0331e902011-03-26 14:48:04 +0100549 default = self._get_default_metavar_for_optional(action)
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000550 args_string = self._format_args(action, default)
551 for option_string in action.option_strings:
552 parts.append('%s %s' % (option_string, args_string))
553
554 return ', '.join(parts)
555
556 def _metavar_formatter(self, action, default_metavar):
557 if action.metavar is not None:
558 result = action.metavar
559 elif action.choices is not None:
560 choice_strs = [str(choice) for choice in action.choices]
561 result = '{%s}' % ','.join(choice_strs)
562 else:
563 result = default_metavar
564
565 def format(tuple_size):
566 if isinstance(result, tuple):
567 return result
568 else:
569 return (result, ) * tuple_size
570 return format
571
572 def _format_args(self, action, default_metavar):
573 get_metavar = self._metavar_formatter(action, default_metavar)
574 if action.nargs is None:
575 result = '%s' % get_metavar(1)
576 elif action.nargs == OPTIONAL:
577 result = '[%s]' % get_metavar(1)
578 elif action.nargs == ZERO_OR_MORE:
579 result = '[%s [%s ...]]' % get_metavar(2)
580 elif action.nargs == ONE_OR_MORE:
581 result = '%s [%s ...]' % get_metavar(2)
582 elif action.nargs == REMAINDER:
583 result = '...'
584 elif action.nargs == PARSER:
585 result = '%s ...' % get_metavar(1)
586 else:
587 formats = ['%s' for _ in range(action.nargs)]
588 result = ' '.join(formats) % get_metavar(action.nargs)
589 return result
590
591 def _expand_help(self, action):
592 params = dict(vars(action), prog=self._prog)
593 for name in list(params):
594 if params[name] is SUPPRESS:
595 del params[name]
596 for name in list(params):
597 if hasattr(params[name], '__name__'):
598 params[name] = params[name].__name__
599 if params.get('choices') is not None:
600 choices_str = ', '.join([str(c) for c in params['choices']])
601 params['choices'] = choices_str
602 return self._get_help_string(action) % params
603
604 def _iter_indented_subactions(self, action):
605 try:
606 get_subactions = action._get_subactions
607 except AttributeError:
608 pass
609 else:
610 self._indent()
611 for subaction in get_subactions():
612 yield subaction
613 self._dedent()
614
615 def _split_lines(self, text, width):
616 text = self._whitespace_matcher.sub(' ', text).strip()
617 return _textwrap.wrap(text, width)
618
619 def _fill_text(self, text, width, indent):
620 text = self._whitespace_matcher.sub(' ', text).strip()
621 return _textwrap.fill(text, width, initial_indent=indent,
622 subsequent_indent=indent)
623
624 def _get_help_string(self, action):
625 return action.help
626
Steven Bethard0331e902011-03-26 14:48:04 +0100627 def _get_default_metavar_for_optional(self, action):
628 return action.dest.upper()
629
630 def _get_default_metavar_for_positional(self, action):
631 return action.dest
632
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000633
634class RawDescriptionHelpFormatter(HelpFormatter):
635 """Help message formatter which retains any formatting in descriptions.
636
637 Only the name of this class is considered a public API. All the methods
638 provided by the class are considered an implementation detail.
639 """
640
641 def _fill_text(self, text, width, indent):
Ezio Melottid8b509b2011-09-28 17:37:55 +0300642 return ''.join(indent + line for line in text.splitlines(keepends=True))
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000643
644
645class RawTextHelpFormatter(RawDescriptionHelpFormatter):
646 """Help message formatter which retains formatting of all help text.
647
648 Only the name of this class is considered a public API. All the methods
649 provided by the class are considered an implementation detail.
650 """
651
652 def _split_lines(self, text, width):
653 return text.splitlines()
654
655
656class ArgumentDefaultsHelpFormatter(HelpFormatter):
657 """Help message formatter which adds default values to argument help.
658
659 Only the name of this class is considered a public API. All the methods
660 provided by the class are considered an implementation detail.
661 """
662
663 def _get_help_string(self, action):
664 help = action.help
665 if '%(default)' not in action.help:
666 if action.default is not SUPPRESS:
667 defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
668 if action.option_strings or action.nargs in defaulting_nargs:
669 help += ' (default: %(default)s)'
670 return help
671
672
Steven Bethard0331e902011-03-26 14:48:04 +0100673class MetavarTypeHelpFormatter(HelpFormatter):
674 """Help message formatter which uses the argument 'type' as the default
675 metavar value (instead of the argument 'dest')
676
677 Only the name of this class is considered a public API. All the methods
678 provided by the class are considered an implementation detail.
679 """
680
681 def _get_default_metavar_for_optional(self, action):
682 return action.type.__name__
683
684 def _get_default_metavar_for_positional(self, action):
685 return action.type.__name__
686
687
688
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000689# =====================
690# Options and Arguments
691# =====================
692
693def _get_action_name(argument):
694 if argument is None:
695 return None
696 elif argument.option_strings:
697 return '/'.join(argument.option_strings)
698 elif argument.metavar not in (None, SUPPRESS):
699 return argument.metavar
700 elif argument.dest not in (None, SUPPRESS):
701 return argument.dest
702 else:
703 return None
704
705
706class ArgumentError(Exception):
707 """An error from creating or using an argument (optional or positional).
708
709 The string value of this exception is the message, augmented with
710 information about the argument that caused it.
711 """
712
713 def __init__(self, argument, message):
714 self.argument_name = _get_action_name(argument)
715 self.message = message
716
717 def __str__(self):
718 if self.argument_name is None:
719 format = '%(message)s'
720 else:
721 format = 'argument %(argument_name)s: %(message)s'
722 return format % dict(message=self.message,
723 argument_name=self.argument_name)
724
725
726class ArgumentTypeError(Exception):
727 """An error from trying to convert a command line string to a type."""
728 pass
729
730
731# ==============
732# Action classes
733# ==============
734
735class Action(_AttributeHolder):
736 """Information about how to convert command line strings to Python objects.
737
738 Action objects are used by an ArgumentParser to represent the information
739 needed to parse a single argument from one or more strings from the
740 command line. The keyword arguments to the Action constructor are also
741 all attributes of Action instances.
742
743 Keyword Arguments:
744
745 - option_strings -- A list of command-line option strings which
746 should be associated with this action.
747
748 - dest -- The name of the attribute to hold the created object(s)
749
750 - nargs -- The number of command-line arguments that should be
751 consumed. By default, one argument will be consumed and a single
752 value will be produced. Other values include:
753 - N (an integer) consumes N arguments (and produces a list)
754 - '?' consumes zero or one arguments
755 - '*' consumes zero or more arguments (and produces a list)
756 - '+' consumes one or more arguments (and produces a list)
757 Note that the difference between the default and nargs=1 is that
758 with the default, a single value will be produced, while with
759 nargs=1, a list containing a single value will be produced.
760
761 - const -- The value to be produced if the option is specified and the
762 option uses an action that takes no values.
763
764 - default -- The value to be produced if the option is not specified.
765
R David Murray15cd9a02012-07-21 17:04:25 -0400766 - type -- A callable that accepts a single string argument, and
767 returns the converted value. The standard Python types str, int,
768 float, and complex are useful examples of such callables. If None,
769 str is used.
Benjamin Peterson698a18a2010-03-02 22:34:37 +0000770
771 - choices -- A container of values that should be allowed. If not None,
772 after a command-line argument has been converted to the appropriate
773 type, an exception will be raised if it is not a member of this
774 collection.
775
776 - required -- True if the action must always be specified at the
777 command line. This is only meaningful for optional command-line
778 arguments.
779
780 - help -- The help string describing the argument.
781
782 - metavar -- The name to be used for the option's argument with the
783 help string. If None, the 'dest' value will be used as the name.
784 """
785
786 def __init__(self,
787 option_strings,
788 dest,
789 nargs=None,
790 const=None,
791 default=None,
792 type=None,
793 choices=None,
794 required=False,
795 help=None,
796 metavar=None):
797 self.option_strings = option_strings
798 self.dest = dest
799 self.nargs = nargs
800 self.const = const
801 self.default = default
802 self.type = type
803 self.choices = choices
804 self.required = required
805 self.help = help
806 self.metavar = metavar
807
808 def _get_kwargs(self):
809 names = [
810 'option_strings',
811 'dest',
812 'nargs',
813 'const',
814 'default',
815 'type',
816 'choices',
817 'help',
818 'metavar',
819 ]
820 return [(name, getattr(self, name)) for name in names]
821
822 def __call__(self, parser, namespace, values, option_string=None):
823 raise NotImplementedError(_('.__call__() not defined'))
824
825
826class _StoreAction(Action):
827
828 def __init__(self,
829 option_strings,
830 dest,
831 nargs=None,
832 const=None,
833 default=None,
834 type=None,
835 choices=None,
836 required=False,
837 help=None,
838 metavar=None):
839 if nargs == 0:
840 raise ValueError('nargs for store actions must be > 0; if you '
841 'have nothing to store, actions such as store '
842 'true or store const may be more appropriate')
843 if const is not None and nargs != OPTIONAL:
844 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
845 super(_StoreAction, self).__init__(
846 option_strings=option_strings,
847 dest=dest,
848 nargs=nargs,
849 const=const,
850 default=default,
851 type=type,
852 choices=choices,
853 required=required,
854 help=help,
855 metavar=metavar)
856
857 def __call__(self, parser, namespace, values, option_string=None):
858 setattr(namespace, self.dest, values)
859
860
861class _StoreConstAction(Action):
862
863 def __init__(self,
864 option_strings,
865 dest,
866 const,
867 default=None,
868 required=False,
869 help=None,
870 metavar=None):
871 super(_StoreConstAction, self).__init__(
872 option_strings=option_strings,
873 dest=dest,
874 nargs=0,
875 const=const,
876 default=default,
877 required=required,
878 help=help)
879
880 def __call__(self, parser, namespace, values, option_string=None):
881 setattr(namespace, self.dest, self.const)
882
883
884class _StoreTrueAction(_StoreConstAction):
885
886 def __init__(self,
887 option_strings,
888 dest,
889 default=False,
890 required=False,
891 help=None):
892 super(_StoreTrueAction, self).__init__(
893 option_strings=option_strings,
894 dest=dest,
895 const=True,
896 default=default,
897 required=required,
898 help=help)
899
900
901class _StoreFalseAction(_StoreConstAction):
902
903 def __init__(self,
904 option_strings,
905 dest,
906 default=True,
907 required=False,
908 help=None):
909 super(_StoreFalseAction, self).__init__(
910 option_strings=option_strings,
911 dest=dest,
912 const=False,
913 default=default,
914 required=required,
915 help=help)
916
917
918class _AppendAction(Action):
919
920 def __init__(self,
921 option_strings,
922 dest,
923 nargs=None,
924 const=None,
925 default=None,
926 type=None,
927 choices=None,
928 required=False,
929 help=None,
930 metavar=None):
931 if nargs == 0:
932 raise ValueError('nargs for append actions must be > 0; if arg '
933 'strings are not supplying the value to append, '
934 'the append const action may be more appropriate')
935 if const is not None and nargs != OPTIONAL:
936 raise ValueError('nargs must be %r to supply const' % OPTIONAL)
937 super(_AppendAction, self).__init__(
938 option_strings=option_strings,
939 dest=dest,
940 nargs=nargs,
941 const=const,
942 default=default,
943 type=type,
944 choices=choices,
945 required=required,
946 help=help,
947 metavar=metavar)
948
949 def __call__(self, parser, namespace, values, option_string=None):
950 items = _copy.copy(_ensure_value(namespace, self.dest, []))
951 items.append(values)
952 setattr(namespace, self.dest, items)
953
954
955class _AppendConstAction(Action):
956
957 def __init__(self,
958 option_strings,
959 dest,
960 const,
961 default=None,
962 required=False,
963 help=None,
964 metavar=None):
965 super(_AppendConstAction, self).__init__(
966 option_strings=option_strings,
967 dest=dest,
968 nargs=0,
969 const=const,
970 default=default,
971 required=required,
972 help=help,
973 metavar=metavar)
974
975 def __call__(self, parser, namespace, values, option_string=None):
976 items = _copy.copy(_ensure_value(namespace, self.dest, []))
977 items.append(self.const)
978 setattr(namespace, self.dest, items)
979
980
981class _CountAction(Action):
982
983 def __init__(self,
984 option_strings,
985 dest,
986 default=None,
987 required=False,
988 help=None):
989 super(_CountAction, self).__init__(
990 option_strings=option_strings,
991 dest=dest,
992 nargs=0,
993 default=default,
994 required=required,
995 help=help)
996
997 def __call__(self, parser, namespace, values, option_string=None):
998 new_count = _ensure_value(namespace, self.dest, 0) + 1
999 setattr(namespace, self.dest, new_count)
1000
1001
1002class _HelpAction(Action):
1003
1004 def __init__(self,
1005 option_strings,
1006 dest=SUPPRESS,
1007 default=SUPPRESS,
1008 help=None):
1009 super(_HelpAction, self).__init__(
1010 option_strings=option_strings,
1011 dest=dest,
1012 default=default,
1013 nargs=0,
1014 help=help)
1015
1016 def __call__(self, parser, namespace, values, option_string=None):
1017 parser.print_help()
1018 parser.exit()
1019
1020
1021class _VersionAction(Action):
1022
1023 def __init__(self,
1024 option_strings,
1025 version=None,
1026 dest=SUPPRESS,
1027 default=SUPPRESS,
Steven Bethard50fe5932010-05-24 03:47:38 +00001028 help="show program's version number and exit"):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001029 super(_VersionAction, self).__init__(
1030 option_strings=option_strings,
1031 dest=dest,
1032 default=default,
1033 nargs=0,
1034 help=help)
1035 self.version = version
1036
1037 def __call__(self, parser, namespace, values, option_string=None):
1038 version = self.version
1039 if version is None:
1040 version = parser.version
1041 formatter = parser._get_formatter()
1042 formatter.add_text(version)
1043 parser.exit(message=formatter.format_help())
1044
1045
1046class _SubParsersAction(Action):
1047
1048 class _ChoicesPseudoAction(Action):
1049
Steven Bethardfd311a72010-12-18 11:19:23 +00001050 def __init__(self, name, aliases, help):
1051 metavar = dest = name
1052 if aliases:
1053 metavar += ' (%s)' % ', '.join(aliases)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001054 sup = super(_SubParsersAction._ChoicesPseudoAction, self)
Steven Bethardfd311a72010-12-18 11:19:23 +00001055 sup.__init__(option_strings=[], dest=dest, help=help,
1056 metavar=metavar)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001057
1058 def __init__(self,
1059 option_strings,
1060 prog,
1061 parser_class,
1062 dest=SUPPRESS,
1063 help=None,
1064 metavar=None):
1065
1066 self._prog_prefix = prog
1067 self._parser_class = parser_class
Steven Bethard8a6a1982011-03-27 13:53:53 +02001068 self._name_parser_map = _collections.OrderedDict()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001069 self._choices_actions = []
1070
1071 super(_SubParsersAction, self).__init__(
1072 option_strings=option_strings,
1073 dest=dest,
1074 nargs=PARSER,
1075 choices=self._name_parser_map,
1076 help=help,
1077 metavar=metavar)
1078
1079 def add_parser(self, name, **kwargs):
1080 # set prog from the existing prefix
1081 if kwargs.get('prog') is None:
1082 kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1083
Steven Bethardfd311a72010-12-18 11:19:23 +00001084 aliases = kwargs.pop('aliases', ())
1085
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001086 # create a pseudo-action to hold the choice help
1087 if 'help' in kwargs:
1088 help = kwargs.pop('help')
Steven Bethardfd311a72010-12-18 11:19:23 +00001089 choice_action = self._ChoicesPseudoAction(name, aliases, help)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001090 self._choices_actions.append(choice_action)
1091
1092 # create the parser and add it to the map
1093 parser = self._parser_class(**kwargs)
1094 self._name_parser_map[name] = parser
Steven Bethardfd311a72010-12-18 11:19:23 +00001095
1096 # make parser available under aliases also
1097 for alias in aliases:
1098 self._name_parser_map[alias] = parser
1099
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001100 return parser
1101
1102 def _get_subactions(self):
1103 return self._choices_actions
1104
1105 def __call__(self, parser, namespace, values, option_string=None):
1106 parser_name = values[0]
1107 arg_strings = values[1:]
1108
1109 # set the parser name if requested
1110 if self.dest is not SUPPRESS:
1111 setattr(namespace, self.dest, parser_name)
1112
1113 # select the parser
1114 try:
1115 parser = self._name_parser_map[parser_name]
1116 except KeyError:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001117 args = {'parser_name': parser_name,
1118 'choices': ', '.join(self._name_parser_map)}
1119 msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001120 raise ArgumentError(self, msg)
1121
1122 # parse all the remaining options into the namespace
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001123 # store any unrecognized options on the object, so that the top
1124 # level parser can decide what to do with them
1125 namespace, arg_strings = parser.parse_known_args(arg_strings, namespace)
1126 if arg_strings:
1127 vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1128 getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001129
1130
1131# ==============
1132# Type classes
1133# ==============
1134
1135class FileType(object):
1136 """Factory for creating file object types
1137
1138 Instances of FileType are typically passed as type= arguments to the
1139 ArgumentParser add_argument() method.
1140
1141 Keyword Arguments:
1142 - mode -- A string indicating how the file is to be opened. Accepts the
1143 same values as the builtin open() function.
1144 - bufsize -- The file's desired buffer size. Accepts the same values as
1145 the builtin open() function.
1146 """
1147
Steven Bethardb0270112011-01-24 21:02:50 +00001148 def __init__(self, mode='r', bufsize=-1):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001149 self._mode = mode
1150 self._bufsize = bufsize
1151
1152 def __call__(self, string):
1153 # the special argument "-" means sys.std{in,out}
1154 if string == '-':
1155 if 'r' in self._mode:
1156 return _sys.stdin
1157 elif 'w' in self._mode:
1158 return _sys.stdout
1159 else:
Éric Araujoa9c7a8f2010-12-03 19:19:17 +00001160 msg = _('argument "-" with mode %r') % self._mode
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001161 raise ValueError(msg)
1162
1163 # all other arguments are used as file names
Steven Bethardb0270112011-01-24 21:02:50 +00001164 try:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001165 return open(string, self._mode, self._bufsize)
Steven Bethardb0270112011-01-24 21:02:50 +00001166 except IOError as e:
1167 message = _("can't open '%s': %s")
1168 raise ArgumentTypeError(message % (string, e))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001169
1170 def __repr__(self):
Steven Bethardb0270112011-01-24 21:02:50 +00001171 args = self._mode, self._bufsize
1172 args_str = ', '.join(repr(arg) for arg in args if arg != -1)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001173 return '%s(%s)' % (type(self).__name__, args_str)
1174
1175# ===========================
1176# Optional and Positional Parsing
1177# ===========================
1178
1179class Namespace(_AttributeHolder):
1180 """Simple object for storing attributes.
1181
1182 Implements equality by attribute names and values, and provides a simple
1183 string representation.
1184 """
1185
1186 def __init__(self, **kwargs):
1187 for name in kwargs:
1188 setattr(self, name, kwargs[name])
1189
1190 def __eq__(self, other):
1191 return vars(self) == vars(other)
1192
1193 def __ne__(self, other):
1194 return not (self == other)
1195
1196 def __contains__(self, key):
1197 return key in self.__dict__
1198
1199
1200class _ActionsContainer(object):
1201
1202 def __init__(self,
1203 description,
1204 prefix_chars,
1205 argument_default,
1206 conflict_handler):
1207 super(_ActionsContainer, self).__init__()
1208
1209 self.description = description
1210 self.argument_default = argument_default
1211 self.prefix_chars = prefix_chars
1212 self.conflict_handler = conflict_handler
1213
1214 # set up registries
1215 self._registries = {}
1216
1217 # register actions
1218 self.register('action', None, _StoreAction)
1219 self.register('action', 'store', _StoreAction)
1220 self.register('action', 'store_const', _StoreConstAction)
1221 self.register('action', 'store_true', _StoreTrueAction)
1222 self.register('action', 'store_false', _StoreFalseAction)
1223 self.register('action', 'append', _AppendAction)
1224 self.register('action', 'append_const', _AppendConstAction)
1225 self.register('action', 'count', _CountAction)
1226 self.register('action', 'help', _HelpAction)
1227 self.register('action', 'version', _VersionAction)
1228 self.register('action', 'parsers', _SubParsersAction)
1229
1230 # raise an exception if the conflict handler is invalid
1231 self._get_handler()
1232
1233 # action storage
1234 self._actions = []
1235 self._option_string_actions = {}
1236
1237 # groups
1238 self._action_groups = []
1239 self._mutually_exclusive_groups = []
1240
1241 # defaults storage
1242 self._defaults = {}
1243
1244 # determines whether an "option" looks like a negative number
1245 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1246
1247 # whether or not there are any optionals that look like negative
1248 # numbers -- uses a list so it can be shared and edited
1249 self._has_negative_number_optionals = []
1250
1251 # ====================
1252 # Registration methods
1253 # ====================
1254 def register(self, registry_name, value, object):
1255 registry = self._registries.setdefault(registry_name, {})
1256 registry[value] = object
1257
1258 def _registry_get(self, registry_name, value, default=None):
1259 return self._registries[registry_name].get(value, default)
1260
1261 # ==================================
1262 # Namespace default accessor methods
1263 # ==================================
1264 def set_defaults(self, **kwargs):
1265 self._defaults.update(kwargs)
1266
1267 # if these defaults match any existing arguments, replace
1268 # the previous default on the object with the new one
1269 for action in self._actions:
1270 if action.dest in kwargs:
1271 action.default = kwargs[action.dest]
1272
1273 def get_default(self, dest):
1274 for action in self._actions:
1275 if action.dest == dest and action.default is not None:
1276 return action.default
1277 return self._defaults.get(dest, None)
1278
1279
1280 # =======================
1281 # Adding argument actions
1282 # =======================
1283 def add_argument(self, *args, **kwargs):
1284 """
1285 add_argument(dest, ..., name=value, ...)
1286 add_argument(option_string, option_string, ..., name=value, ...)
1287 """
1288
1289 # if no positional args are supplied or only one is supplied and
1290 # it doesn't look like an option string, parse a positional
1291 # argument
1292 chars = self.prefix_chars
1293 if not args or len(args) == 1 and args[0][0] not in chars:
1294 if args and 'dest' in kwargs:
1295 raise ValueError('dest supplied twice for positional argument')
1296 kwargs = self._get_positional_kwargs(*args, **kwargs)
1297
1298 # otherwise, we're adding an optional argument
1299 else:
1300 kwargs = self._get_optional_kwargs(*args, **kwargs)
1301
1302 # if no default was supplied, use the parser-level default
1303 if 'default' not in kwargs:
1304 dest = kwargs['dest']
1305 if dest in self._defaults:
1306 kwargs['default'] = self._defaults[dest]
1307 elif self.argument_default is not None:
1308 kwargs['default'] = self.argument_default
1309
1310 # create the action object, and add it to the parser
1311 action_class = self._pop_action_class(kwargs)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001312 if not callable(action_class):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001313 raise ValueError('unknown action "%s"' % (action_class,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001314 action = action_class(**kwargs)
1315
1316 # raise an error if the action type is not callable
1317 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02001318 if not callable(type_func):
Steven Bethard7cb20a82011-04-04 01:53:02 +02001319 raise ValueError('%r is not callable' % (type_func,))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001320
Steven Bethard8d9a4622011-03-26 17:33:56 +01001321 # raise an error if the metavar does not match the type
1322 if hasattr(self, "_get_formatter"):
1323 try:
1324 self._get_formatter()._format_args(action, None)
1325 except TypeError:
1326 raise ValueError("length of metavar tuple does not match nargs")
1327
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001328 return self._add_action(action)
1329
1330 def add_argument_group(self, *args, **kwargs):
1331 group = _ArgumentGroup(self, *args, **kwargs)
1332 self._action_groups.append(group)
1333 return group
1334
1335 def add_mutually_exclusive_group(self, **kwargs):
1336 group = _MutuallyExclusiveGroup(self, **kwargs)
1337 self._mutually_exclusive_groups.append(group)
1338 return group
1339
1340 def _add_action(self, action):
1341 # resolve any conflicts
1342 self._check_conflict(action)
1343
1344 # add to actions list
1345 self._actions.append(action)
1346 action.container = self
1347
1348 # index the action by any option strings it has
1349 for option_string in action.option_strings:
1350 self._option_string_actions[option_string] = action
1351
1352 # set the flag if any option strings look like negative numbers
1353 for option_string in action.option_strings:
1354 if self._negative_number_matcher.match(option_string):
1355 if not self._has_negative_number_optionals:
1356 self._has_negative_number_optionals.append(True)
1357
1358 # return the created action
1359 return action
1360
1361 def _remove_action(self, action):
1362 self._actions.remove(action)
1363
1364 def _add_container_actions(self, container):
1365 # collect groups by titles
1366 title_group_map = {}
1367 for group in self._action_groups:
1368 if group.title in title_group_map:
1369 msg = _('cannot merge actions - two groups are named %r')
1370 raise ValueError(msg % (group.title))
1371 title_group_map[group.title] = group
1372
1373 # map each action to its group
1374 group_map = {}
1375 for group in container._action_groups:
1376
1377 # if a group with the title exists, use that, otherwise
1378 # create a new group matching the container's group
1379 if group.title not in title_group_map:
1380 title_group_map[group.title] = self.add_argument_group(
1381 title=group.title,
1382 description=group.description,
1383 conflict_handler=group.conflict_handler)
1384
1385 # map the actions to their new group
1386 for action in group._group_actions:
1387 group_map[action] = title_group_map[group.title]
1388
1389 # add container's mutually exclusive groups
1390 # NOTE: if add_mutually_exclusive_group ever gains title= and
1391 # description= then this code will need to be expanded as above
1392 for group in container._mutually_exclusive_groups:
1393 mutex_group = self.add_mutually_exclusive_group(
1394 required=group.required)
1395
1396 # map the actions to their new mutex group
1397 for action in group._group_actions:
1398 group_map[action] = mutex_group
1399
1400 # add all actions to this container or their group
1401 for action in container._actions:
1402 group_map.get(action, self)._add_action(action)
1403
1404 def _get_positional_kwargs(self, dest, **kwargs):
1405 # make sure required is not specified
1406 if 'required' in kwargs:
1407 msg = _("'required' is an invalid argument for positionals")
1408 raise TypeError(msg)
1409
1410 # mark positional arguments as required if at least one is
1411 # always required
1412 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1413 kwargs['required'] = True
1414 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1415 kwargs['required'] = True
1416
1417 # return the keyword arguments with no option strings
1418 return dict(kwargs, dest=dest, option_strings=[])
1419
1420 def _get_optional_kwargs(self, *args, **kwargs):
1421 # determine short and long option strings
1422 option_strings = []
1423 long_option_strings = []
1424 for option_string in args:
1425 # error on strings that don't start with an appropriate prefix
1426 if not option_string[0] in self.prefix_chars:
Éric Araujobb48a8b2010-12-03 19:41:00 +00001427 args = {'option': option_string,
1428 'prefix_chars': self.prefix_chars}
1429 msg = _('invalid option string %(option)r: '
1430 'must start with a character %(prefix_chars)r')
1431 raise ValueError(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001432
1433 # strings starting with two prefix characters are long options
1434 option_strings.append(option_string)
1435 if option_string[0] in self.prefix_chars:
1436 if len(option_string) > 1:
1437 if option_string[1] in self.prefix_chars:
1438 long_option_strings.append(option_string)
1439
1440 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1441 dest = kwargs.pop('dest', None)
1442 if dest is None:
1443 if long_option_strings:
1444 dest_option_string = long_option_strings[0]
1445 else:
1446 dest_option_string = option_strings[0]
1447 dest = dest_option_string.lstrip(self.prefix_chars)
1448 if not dest:
1449 msg = _('dest= is required for options like %r')
1450 raise ValueError(msg % option_string)
1451 dest = dest.replace('-', '_')
1452
1453 # return the updated keyword arguments
1454 return dict(kwargs, dest=dest, option_strings=option_strings)
1455
1456 def _pop_action_class(self, kwargs, default=None):
1457 action = kwargs.pop('action', default)
1458 return self._registry_get('action', action, action)
1459
1460 def _get_handler(self):
1461 # determine function from conflict handler string
1462 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1463 try:
1464 return getattr(self, handler_func_name)
1465 except AttributeError:
1466 msg = _('invalid conflict_resolution value: %r')
1467 raise ValueError(msg % self.conflict_handler)
1468
1469 def _check_conflict(self, action):
1470
1471 # find all options that conflict with this option
1472 confl_optionals = []
1473 for option_string in action.option_strings:
1474 if option_string in self._option_string_actions:
1475 confl_optional = self._option_string_actions[option_string]
1476 confl_optionals.append((option_string, confl_optional))
1477
1478 # resolve any conflicts
1479 if confl_optionals:
1480 conflict_handler = self._get_handler()
1481 conflict_handler(action, confl_optionals)
1482
1483 def _handle_conflict_error(self, action, conflicting_actions):
Éric Araujo12159152010-12-04 17:31:49 +00001484 message = ngettext('conflicting option string: %s',
1485 'conflicting option strings: %s',
1486 len(conflicting_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001487 conflict_string = ', '.join([option_string
1488 for option_string, action
1489 in conflicting_actions])
1490 raise ArgumentError(action, message % conflict_string)
1491
1492 def _handle_conflict_resolve(self, action, conflicting_actions):
1493
1494 # remove all conflicting options
1495 for option_string, action in conflicting_actions:
1496
1497 # remove the conflicting option
1498 action.option_strings.remove(option_string)
1499 self._option_string_actions.pop(option_string, None)
1500
1501 # if the option now has no option string, remove it from the
1502 # container holding it
1503 if not action.option_strings:
1504 action.container._remove_action(action)
1505
1506
1507class _ArgumentGroup(_ActionsContainer):
1508
1509 def __init__(self, container, title=None, description=None, **kwargs):
1510 # add any missing keyword arguments by checking the container
1511 update = kwargs.setdefault
1512 update('conflict_handler', container.conflict_handler)
1513 update('prefix_chars', container.prefix_chars)
1514 update('argument_default', container.argument_default)
1515 super_init = super(_ArgumentGroup, self).__init__
1516 super_init(description=description, **kwargs)
1517
1518 # group attributes
1519 self.title = title
1520 self._group_actions = []
1521
1522 # share most attributes with the container
1523 self._registries = container._registries
1524 self._actions = container._actions
1525 self._option_string_actions = container._option_string_actions
1526 self._defaults = container._defaults
1527 self._has_negative_number_optionals = \
1528 container._has_negative_number_optionals
Georg Brandl0f6b47a2011-01-30 12:19:35 +00001529 self._mutually_exclusive_groups = container._mutually_exclusive_groups
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001530
1531 def _add_action(self, action):
1532 action = super(_ArgumentGroup, self)._add_action(action)
1533 self._group_actions.append(action)
1534 return action
1535
1536 def _remove_action(self, action):
1537 super(_ArgumentGroup, self)._remove_action(action)
1538 self._group_actions.remove(action)
1539
1540
1541class _MutuallyExclusiveGroup(_ArgumentGroup):
1542
1543 def __init__(self, container, required=False):
1544 super(_MutuallyExclusiveGroup, self).__init__(container)
1545 self.required = required
1546 self._container = container
1547
1548 def _add_action(self, action):
1549 if action.required:
1550 msg = _('mutually exclusive arguments must be optional')
1551 raise ValueError(msg)
1552 action = self._container._add_action(action)
1553 self._group_actions.append(action)
1554 return action
1555
1556 def _remove_action(self, action):
1557 self._container._remove_action(action)
1558 self._group_actions.remove(action)
1559
1560
1561class ArgumentParser(_AttributeHolder, _ActionsContainer):
1562 """Object for parsing command line strings into Python objects.
1563
1564 Keyword Arguments:
1565 - prog -- The name of the program (default: sys.argv[0])
1566 - usage -- A usage message (default: auto-generated from arguments)
1567 - description -- A description of what the program does
1568 - epilog -- Text following the argument descriptions
1569 - parents -- Parsers whose arguments should be copied into this one
1570 - formatter_class -- HelpFormatter class for printing help messages
1571 - prefix_chars -- Characters that prefix optional arguments
1572 - fromfile_prefix_chars -- Characters that prefix files containing
1573 additional arguments
1574 - argument_default -- The default value for all arguments
1575 - conflict_handler -- String indicating how to handle conflicts
1576 - add_help -- Add a -h/-help option
1577 """
1578
1579 def __init__(self,
1580 prog=None,
1581 usage=None,
1582 description=None,
1583 epilog=None,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001584 parents=[],
1585 formatter_class=HelpFormatter,
1586 prefix_chars='-',
1587 fromfile_prefix_chars=None,
1588 argument_default=None,
1589 conflict_handler='error',
1590 add_help=True):
1591
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001592 superinit = super(ArgumentParser, self).__init__
1593 superinit(description=description,
1594 prefix_chars=prefix_chars,
1595 argument_default=argument_default,
1596 conflict_handler=conflict_handler)
1597
1598 # default setting for prog
1599 if prog is None:
1600 prog = _os.path.basename(_sys.argv[0])
1601
1602 self.prog = prog
1603 self.usage = usage
1604 self.epilog = epilog
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001605 self.formatter_class = formatter_class
1606 self.fromfile_prefix_chars = fromfile_prefix_chars
1607 self.add_help = add_help
1608
1609 add_group = self.add_argument_group
1610 self._positionals = add_group(_('positional arguments'))
1611 self._optionals = add_group(_('optional arguments'))
1612 self._subparsers = None
1613
1614 # register types
1615 def identity(string):
1616 return string
1617 self.register('type', None, identity)
1618
Florent Xiclunaaf1adbe2012-07-07 17:02:22 +02001619 # add help argument if necessary
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001620 # (using explicit default to override global argument_default)
R. David Murray88c49fe2010-08-03 17:56:09 +00001621 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001622 if self.add_help:
1623 self.add_argument(
R. David Murray88c49fe2010-08-03 17:56:09 +00001624 default_prefix+'h', default_prefix*2+'help',
1625 action='help', default=SUPPRESS,
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001626 help=_('show this help message and exit'))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001627
1628 # add parent arguments and defaults
1629 for parent in parents:
1630 self._add_container_actions(parent)
1631 try:
1632 defaults = parent._defaults
1633 except AttributeError:
1634 pass
1635 else:
1636 self._defaults.update(defaults)
1637
1638 # =======================
1639 # Pretty __repr__ methods
1640 # =======================
1641 def _get_kwargs(self):
1642 names = [
1643 'prog',
1644 'usage',
1645 'description',
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001646 'formatter_class',
1647 'conflict_handler',
1648 'add_help',
1649 ]
1650 return [(name, getattr(self, name)) for name in names]
1651
1652 # ==================================
1653 # Optional/Positional adding methods
1654 # ==================================
1655 def add_subparsers(self, **kwargs):
1656 if self._subparsers is not None:
1657 self.error(_('cannot have multiple subparser arguments'))
1658
1659 # add the parser class to the arguments if it's not present
1660 kwargs.setdefault('parser_class', type(self))
1661
1662 if 'title' in kwargs or 'description' in kwargs:
1663 title = _(kwargs.pop('title', 'subcommands'))
1664 description = _(kwargs.pop('description', None))
1665 self._subparsers = self.add_argument_group(title, description)
1666 else:
1667 self._subparsers = self._positionals
1668
1669 # prog defaults to the usage message of this parser, skipping
1670 # optional arguments and with no "usage:" prefix
1671 if kwargs.get('prog') is None:
1672 formatter = self._get_formatter()
1673 positionals = self._get_positional_actions()
1674 groups = self._mutually_exclusive_groups
1675 formatter.add_usage(self.usage, positionals, groups, '')
1676 kwargs['prog'] = formatter.format_help().strip()
1677
1678 # create the parsers action and add it to the positionals list
1679 parsers_class = self._pop_action_class(kwargs, 'parsers')
1680 action = parsers_class(option_strings=[], **kwargs)
1681 self._subparsers._add_action(action)
1682
1683 # return the created parsers action
1684 return action
1685
1686 def _add_action(self, action):
1687 if action.option_strings:
1688 self._optionals._add_action(action)
1689 else:
1690 self._positionals._add_action(action)
1691 return action
1692
1693 def _get_optional_actions(self):
1694 return [action
1695 for action in self._actions
1696 if action.option_strings]
1697
1698 def _get_positional_actions(self):
1699 return [action
1700 for action in self._actions
1701 if not action.option_strings]
1702
1703 # =====================================
1704 # Command line argument parsing methods
1705 # =====================================
1706 def parse_args(self, args=None, namespace=None):
1707 args, argv = self.parse_known_args(args, namespace)
1708 if argv:
1709 msg = _('unrecognized arguments: %s')
1710 self.error(msg % ' '.join(argv))
1711 return args
1712
1713 def parse_known_args(self, args=None, namespace=None):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001714 if args is None:
R David Murrayb5228282012-09-08 12:08:01 -04001715 # args default to the system args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001716 args = _sys.argv[1:]
R David Murrayb5228282012-09-08 12:08:01 -04001717 else:
1718 # make sure that args are mutable
1719 args = list(args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001720
1721 # default Namespace built from parser defaults
1722 if namespace is None:
1723 namespace = Namespace()
1724
1725 # add any action defaults that aren't present
1726 for action in self._actions:
1727 if action.dest is not SUPPRESS:
1728 if not hasattr(namespace, action.dest):
1729 if action.default is not SUPPRESS:
R David Murray6fb8fb12012-08-31 22:45:20 -04001730 setattr(namespace, action.dest, action.default)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001731
1732 # add any parser defaults that aren't present
1733 for dest in self._defaults:
1734 if not hasattr(namespace, dest):
1735 setattr(namespace, dest, self._defaults[dest])
1736
1737 # parse the arguments and exit if there are any errors
1738 try:
Steven Bethardfca2e8a2010-11-02 12:47:22 +00001739 namespace, args = self._parse_known_args(args, namespace)
1740 if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1741 args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1742 delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1743 return namespace, args
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001744 except ArgumentError:
1745 err = _sys.exc_info()[1]
1746 self.error(str(err))
1747
1748 def _parse_known_args(self, arg_strings, namespace):
1749 # replace arg strings that are file references
1750 if self.fromfile_prefix_chars is not None:
1751 arg_strings = self._read_args_from_files(arg_strings)
1752
1753 # map all mutually exclusive arguments to the other arguments
1754 # they can't occur with
1755 action_conflicts = {}
1756 for mutex_group in self._mutually_exclusive_groups:
1757 group_actions = mutex_group._group_actions
1758 for i, mutex_action in enumerate(mutex_group._group_actions):
1759 conflicts = action_conflicts.setdefault(mutex_action, [])
1760 conflicts.extend(group_actions[:i])
1761 conflicts.extend(group_actions[i + 1:])
1762
1763 # find all option indices, and determine the arg_string_pattern
1764 # which has an 'O' if there is an option at an index,
1765 # an 'A' if there is an argument, or a '-' if there is a '--'
1766 option_string_indices = {}
1767 arg_string_pattern_parts = []
1768 arg_strings_iter = iter(arg_strings)
1769 for i, arg_string in enumerate(arg_strings_iter):
1770
1771 # all args after -- are non-options
1772 if arg_string == '--':
1773 arg_string_pattern_parts.append('-')
1774 for arg_string in arg_strings_iter:
1775 arg_string_pattern_parts.append('A')
1776
1777 # otherwise, add the arg to the arg strings
1778 # and note the index if it was an option
1779 else:
1780 option_tuple = self._parse_optional(arg_string)
1781 if option_tuple is None:
1782 pattern = 'A'
1783 else:
1784 option_string_indices[i] = option_tuple
1785 pattern = 'O'
1786 arg_string_pattern_parts.append(pattern)
1787
1788 # join the pieces together to form the pattern
1789 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1790
1791 # converts arg strings to the appropriate and then takes the action
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00001792 seen_actions = set()
1793 seen_non_default_actions = set()
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001794
1795 def take_action(action, argument_strings, option_string=None):
1796 seen_actions.add(action)
1797 argument_values = self._get_values(action, argument_strings)
1798
1799 # error if this argument is not allowed with other previously
1800 # seen arguments, assuming that actions that use the default
1801 # value don't really count as "present"
1802 if argument_values is not action.default:
1803 seen_non_default_actions.add(action)
1804 for conflict_action in action_conflicts.get(action, []):
1805 if conflict_action in seen_non_default_actions:
1806 msg = _('not allowed with argument %s')
1807 action_name = _get_action_name(conflict_action)
1808 raise ArgumentError(action, msg % action_name)
1809
1810 # take the action if we didn't receive a SUPPRESS value
1811 # (e.g. from a default)
1812 if argument_values is not SUPPRESS:
1813 action(self, namespace, argument_values, option_string)
1814
1815 # function to convert arg_strings into an optional action
1816 def consume_optional(start_index):
1817
1818 # get the optional identified at this index
1819 option_tuple = option_string_indices[start_index]
1820 action, option_string, explicit_arg = option_tuple
1821
1822 # identify additional optionals in the same arg string
1823 # (e.g. -xyz is the same as -x -y -z if no args are required)
1824 match_argument = self._match_argument
1825 action_tuples = []
1826 while True:
1827
1828 # if we found no optional action, skip it
1829 if action is None:
1830 extras.append(arg_strings[start_index])
1831 return start_index + 1
1832
1833 # if there is an explicit argument, try to match the
1834 # optional's string arguments to only this
1835 if explicit_arg is not None:
1836 arg_count = match_argument(action, 'A')
1837
1838 # if the action is a single-dash option and takes no
1839 # arguments, try to parse more single-dash options out
1840 # of the tail of the option string
1841 chars = self.prefix_chars
1842 if arg_count == 0 and option_string[1] not in chars:
1843 action_tuples.append((action, [], option_string))
Steven Bethard1ca45a52010-11-01 15:57:36 +00001844 char = option_string[0]
1845 option_string = char + explicit_arg[0]
1846 new_explicit_arg = explicit_arg[1:] or None
1847 optionals_map = self._option_string_actions
1848 if option_string in optionals_map:
1849 action = optionals_map[option_string]
1850 explicit_arg = new_explicit_arg
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001851 else:
1852 msg = _('ignored explicit argument %r')
1853 raise ArgumentError(action, msg % explicit_arg)
1854
1855 # if the action expect exactly one argument, we've
1856 # successfully matched the option; exit the loop
1857 elif arg_count == 1:
1858 stop = start_index + 1
1859 args = [explicit_arg]
1860 action_tuples.append((action, args, option_string))
1861 break
1862
1863 # error if a double-dash option did not use the
1864 # explicit argument
1865 else:
1866 msg = _('ignored explicit argument %r')
1867 raise ArgumentError(action, msg % explicit_arg)
1868
1869 # if there is no explicit argument, try to match the
1870 # optional's string arguments with the following strings
1871 # if successful, exit the loop
1872 else:
1873 start = start_index + 1
1874 selected_patterns = arg_strings_pattern[start:]
1875 arg_count = match_argument(action, selected_patterns)
1876 stop = start + arg_count
1877 args = arg_strings[start:stop]
1878 action_tuples.append((action, args, option_string))
1879 break
1880
1881 # add the Optional to the list and return the index at which
1882 # the Optional's string args stopped
1883 assert action_tuples
1884 for action, args, option_string in action_tuples:
1885 take_action(action, args, option_string)
1886 return stop
1887
1888 # the list of Positionals left to be parsed; this is modified
1889 # by consume_positionals()
1890 positionals = self._get_positional_actions()
1891
1892 # function to convert arg_strings into positional actions
1893 def consume_positionals(start_index):
1894 # match as many Positionals as possible
1895 match_partial = self._match_arguments_partial
1896 selected_pattern = arg_strings_pattern[start_index:]
1897 arg_counts = match_partial(positionals, selected_pattern)
1898
1899 # slice off the appropriate arg strings for each Positional
1900 # and add the Positional and its args to the list
1901 for action, arg_count in zip(positionals, arg_counts):
1902 args = arg_strings[start_index: start_index + arg_count]
1903 start_index += arg_count
1904 take_action(action, args)
1905
1906 # slice off the Positionals that we just parsed and return the
1907 # index at which the Positionals' string args stopped
1908 positionals[:] = positionals[len(arg_counts):]
1909 return start_index
1910
1911 # consume Positionals and Optionals alternately, until we have
1912 # passed the last option string
1913 extras = []
1914 start_index = 0
1915 if option_string_indices:
1916 max_option_string_index = max(option_string_indices)
1917 else:
1918 max_option_string_index = -1
1919 while start_index <= max_option_string_index:
1920
1921 # consume any Positionals preceding the next option
1922 next_option_string_index = min([
1923 index
1924 for index in option_string_indices
1925 if index >= start_index])
1926 if start_index != next_option_string_index:
1927 positionals_end_index = consume_positionals(start_index)
1928
1929 # only try to parse the next optional if we didn't consume
1930 # the option string during the positionals parsing
1931 if positionals_end_index > start_index:
1932 start_index = positionals_end_index
1933 continue
1934 else:
1935 start_index = positionals_end_index
1936
1937 # if we consumed all the positionals we could and we're not
1938 # at the index of an option string, there were extra arguments
1939 if start_index not in option_string_indices:
1940 strings = arg_strings[start_index:next_option_string_index]
1941 extras.extend(strings)
1942 start_index = next_option_string_index
1943
1944 # consume the next optional and any arguments for it
1945 start_index = consume_optional(start_index)
1946
1947 # consume any positionals following the last Optional
1948 stop_index = consume_positionals(start_index)
1949
1950 # if we didn't consume all the argument strings, there were extras
1951 extras.extend(arg_strings[stop_index:])
1952
R David Murray64b0ef12012-08-31 23:09:34 -04001953 # make sure all required actions were present and also convert
1954 # action defaults which were not given as arguments
1955 required_actions = []
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001956 for action in self._actions:
R David Murray6fb8fb12012-08-31 22:45:20 -04001957 if action not in seen_actions:
1958 if action.required:
R David Murray64b0ef12012-08-31 23:09:34 -04001959 required_actions.append(_get_action_name(action))
R David Murray6fb8fb12012-08-31 22:45:20 -04001960 else:
1961 # Convert action default now instead of doing it before
1962 # parsing arguments to avoid calling convert functions
1963 # twice (which may fail) if the argument was given, but
1964 # only if it was defined already in the namespace
1965 if (action.default is not None and
Barry Warsawd89774e2012-09-12 15:31:38 -04001966 isinstance(action.default, str) and
R David Murray64b0ef12012-08-31 23:09:34 -04001967 hasattr(namespace, action.dest) and
1968 action.default is getattr(namespace, action.dest)):
R David Murray6fb8fb12012-08-31 22:45:20 -04001969 setattr(namespace, action.dest,
1970 self._get_value(action, action.default))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001971
R David Murrayf97c59a2011-06-09 12:34:07 -04001972 if required_actions:
1973 self.error(_('the following arguments are required: %s') %
1974 ', '.join(required_actions))
Benjamin Peterson698a18a2010-03-02 22:34:37 +00001975
1976 # make sure all required groups had one option present
1977 for group in self._mutually_exclusive_groups:
1978 if group.required:
1979 for action in group._group_actions:
1980 if action in seen_non_default_actions:
1981 break
1982
1983 # if no actions were used, report the error
1984 else:
1985 names = [_get_action_name(action)
1986 for action in group._group_actions
1987 if action.help is not SUPPRESS]
1988 msg = _('one of the arguments %s is required')
1989 self.error(msg % ' '.join(names))
1990
1991 # return the updated namespace and the extra arguments
1992 return namespace, extras
1993
1994 def _read_args_from_files(self, arg_strings):
1995 # expand arguments referencing files
1996 new_arg_strings = []
1997 for arg_string in arg_strings:
1998
1999 # for regular arguments, just add them back into the list
R David Murrayb94082a2012-07-21 22:20:11 -04002000 if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002001 new_arg_strings.append(arg_string)
2002
2003 # replace arguments referencing files with the file content
2004 else:
2005 try:
2006 args_file = open(arg_string[1:])
2007 try:
2008 arg_strings = []
2009 for arg_line in args_file.read().splitlines():
2010 for arg in self.convert_arg_line_to_args(arg_line):
2011 arg_strings.append(arg)
2012 arg_strings = self._read_args_from_files(arg_strings)
2013 new_arg_strings.extend(arg_strings)
2014 finally:
2015 args_file.close()
2016 except IOError:
2017 err = _sys.exc_info()[1]
2018 self.error(str(err))
2019
2020 # return the modified argument list
2021 return new_arg_strings
2022
2023 def convert_arg_line_to_args(self, arg_line):
2024 return [arg_line]
2025
2026 def _match_argument(self, action, arg_strings_pattern):
2027 # match the pattern for this action to the arg strings
2028 nargs_pattern = self._get_nargs_pattern(action)
2029 match = _re.match(nargs_pattern, arg_strings_pattern)
2030
2031 # raise an exception if we weren't able to find a match
2032 if match is None:
2033 nargs_errors = {
2034 None: _('expected one argument'),
2035 OPTIONAL: _('expected at most one argument'),
2036 ONE_OR_MORE: _('expected at least one argument'),
2037 }
Éric Araujo12159152010-12-04 17:31:49 +00002038 default = ngettext('expected %s argument',
2039 'expected %s arguments',
2040 action.nargs) % action.nargs
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002041 msg = nargs_errors.get(action.nargs, default)
2042 raise ArgumentError(action, msg)
2043
2044 # return the number of arguments matched
2045 return len(match.group(1))
2046
2047 def _match_arguments_partial(self, actions, arg_strings_pattern):
2048 # progressively shorten the actions list by slicing off the
2049 # final actions until we find a match
2050 result = []
2051 for i in range(len(actions), 0, -1):
2052 actions_slice = actions[:i]
2053 pattern = ''.join([self._get_nargs_pattern(action)
2054 for action in actions_slice])
2055 match = _re.match(pattern, arg_strings_pattern)
2056 if match is not None:
2057 result.extend([len(string) for string in match.groups()])
2058 break
2059
2060 # return the list of arg string counts
2061 return result
2062
2063 def _parse_optional(self, arg_string):
2064 # if it's an empty string, it was meant to be a positional
2065 if not arg_string:
2066 return None
2067
2068 # if it doesn't start with a prefix, it was meant to be positional
2069 if not arg_string[0] in self.prefix_chars:
2070 return None
2071
2072 # if the option string is present in the parser, return the action
2073 if arg_string in self._option_string_actions:
2074 action = self._option_string_actions[arg_string]
2075 return action, arg_string, None
2076
2077 # if it's just a single character, it was meant to be positional
2078 if len(arg_string) == 1:
2079 return None
2080
2081 # if the option string before the "=" is present, return the action
2082 if '=' in arg_string:
2083 option_string, explicit_arg = arg_string.split('=', 1)
2084 if option_string in self._option_string_actions:
2085 action = self._option_string_actions[option_string]
2086 return action, option_string, explicit_arg
2087
2088 # search through all possible prefixes of the option string
2089 # and all actions in the parser for possible interpretations
2090 option_tuples = self._get_option_tuples(arg_string)
2091
2092 # if multiple actions match, the option string was ambiguous
2093 if len(option_tuples) > 1:
2094 options = ', '.join([option_string
2095 for action, option_string, explicit_arg in option_tuples])
Éric Araujobb48a8b2010-12-03 19:41:00 +00002096 args = {'option': arg_string, 'matches': options}
2097 msg = _('ambiguous option: %(option)s could match %(matches)s')
2098 self.error(msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002099
2100 # if exactly one action matched, this segmentation is good,
2101 # so return the parsed action
2102 elif len(option_tuples) == 1:
2103 option_tuple, = option_tuples
2104 return option_tuple
2105
2106 # if it was not found as an option, but it looks like a negative
2107 # number, it was meant to be positional
2108 # unless there are negative-number-like options
2109 if self._negative_number_matcher.match(arg_string):
2110 if not self._has_negative_number_optionals:
2111 return None
2112
2113 # if it contains a space, it was meant to be a positional
2114 if ' ' in arg_string:
2115 return None
2116
2117 # it was meant to be an optional but there is no such option
2118 # in this parser (though it might be a valid option in a subparser)
2119 return None, arg_string, None
2120
2121 def _get_option_tuples(self, option_string):
2122 result = []
2123
2124 # option strings starting with two prefix characters are only
2125 # split at the '='
2126 chars = self.prefix_chars
2127 if option_string[0] in chars and option_string[1] in chars:
2128 if '=' in option_string:
2129 option_prefix, explicit_arg = option_string.split('=', 1)
2130 else:
2131 option_prefix = option_string
2132 explicit_arg = None
2133 for option_string in self._option_string_actions:
2134 if option_string.startswith(option_prefix):
2135 action = self._option_string_actions[option_string]
2136 tup = action, option_string, explicit_arg
2137 result.append(tup)
2138
2139 # single character options can be concatenated with their arguments
2140 # but multiple character options always have to have their argument
2141 # separate
2142 elif option_string[0] in chars and option_string[1] not in chars:
2143 option_prefix = option_string
2144 explicit_arg = None
2145 short_option_prefix = option_string[:2]
2146 short_explicit_arg = option_string[2:]
2147
2148 for option_string in self._option_string_actions:
2149 if option_string == short_option_prefix:
2150 action = self._option_string_actions[option_string]
2151 tup = action, option_string, short_explicit_arg
2152 result.append(tup)
2153 elif option_string.startswith(option_prefix):
2154 action = self._option_string_actions[option_string]
2155 tup = action, option_string, explicit_arg
2156 result.append(tup)
2157
2158 # shouldn't ever get here
2159 else:
2160 self.error(_('unexpected option string: %s') % option_string)
2161
2162 # return the collected option tuples
2163 return result
2164
2165 def _get_nargs_pattern(self, action):
2166 # in all examples below, we have to allow for '--' args
2167 # which are represented as '-' in the pattern
2168 nargs = action.nargs
2169
2170 # the default (None) is assumed to be a single argument
2171 if nargs is None:
2172 nargs_pattern = '(-*A-*)'
2173
2174 # allow zero or one arguments
2175 elif nargs == OPTIONAL:
2176 nargs_pattern = '(-*A?-*)'
2177
2178 # allow zero or more arguments
2179 elif nargs == ZERO_OR_MORE:
2180 nargs_pattern = '(-*[A-]*)'
2181
2182 # allow one or more arguments
2183 elif nargs == ONE_OR_MORE:
2184 nargs_pattern = '(-*A[A-]*)'
2185
2186 # allow any number of options or arguments
2187 elif nargs == REMAINDER:
2188 nargs_pattern = '([-AO]*)'
2189
2190 # allow one argument followed by any number of options or arguments
2191 elif nargs == PARSER:
2192 nargs_pattern = '(-*A[-AO]*)'
2193
2194 # all others should be integers
2195 else:
2196 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2197
2198 # if this is an optional action, -- is not allowed
2199 if action.option_strings:
2200 nargs_pattern = nargs_pattern.replace('-*', '')
2201 nargs_pattern = nargs_pattern.replace('-', '')
2202
2203 # return the pattern
2204 return nargs_pattern
2205
2206 # ========================
2207 # Value conversion methods
2208 # ========================
2209 def _get_values(self, action, arg_strings):
R David Murray00528e82012-07-21 22:48:35 -04002210 # for everything but PARSER, REMAINDER args, strip out first '--'
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002211 if action.nargs not in [PARSER, REMAINDER]:
R David Murray00528e82012-07-21 22:48:35 -04002212 try:
2213 arg_strings.remove('--')
2214 except ValueError:
2215 pass
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002216
2217 # optional argument produces a default when not present
2218 if not arg_strings and action.nargs == OPTIONAL:
2219 if action.option_strings:
2220 value = action.const
2221 else:
2222 value = action.default
Benjamin Peterson16f2fd02010-03-02 23:09:38 +00002223 if isinstance(value, str):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002224 value = self._get_value(action, value)
2225 self._check_value(action, value)
2226
2227 # when nargs='*' on a positional, if there were no command-line
2228 # args, use the default if it is anything other than None
2229 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2230 not action.option_strings):
2231 if action.default is not None:
2232 value = action.default
2233 else:
2234 value = arg_strings
2235 self._check_value(action, value)
2236
2237 # single argument or optional argument produces a single value
2238 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2239 arg_string, = arg_strings
2240 value = self._get_value(action, arg_string)
2241 self._check_value(action, value)
2242
2243 # REMAINDER arguments convert all values, checking none
2244 elif action.nargs == REMAINDER:
2245 value = [self._get_value(action, v) for v in arg_strings]
2246
2247 # PARSER arguments convert all values, but check only the first
2248 elif action.nargs == PARSER:
2249 value = [self._get_value(action, v) for v in arg_strings]
2250 self._check_value(action, value[0])
2251
2252 # all other types of nargs produce a list
2253 else:
2254 value = [self._get_value(action, v) for v in arg_strings]
2255 for v in value:
2256 self._check_value(action, v)
2257
2258 # return the converted value
2259 return value
2260
2261 def _get_value(self, action, arg_string):
2262 type_func = self._registry_get('type', action.type, action.type)
Florent Xicluna5d1155c2011-10-28 14:45:05 +02002263 if not callable(type_func):
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002264 msg = _('%r is not callable')
2265 raise ArgumentError(action, msg % type_func)
2266
2267 # convert the value to the appropriate type
2268 try:
2269 result = type_func(arg_string)
2270
2271 # ArgumentTypeErrors indicate errors
2272 except ArgumentTypeError:
2273 name = getattr(action.type, '__name__', repr(action.type))
2274 msg = str(_sys.exc_info()[1])
2275 raise ArgumentError(action, msg)
2276
2277 # TypeErrors or ValueErrors also indicate errors
2278 except (TypeError, ValueError):
2279 name = getattr(action.type, '__name__', repr(action.type))
Éric Araujobb48a8b2010-12-03 19:41:00 +00002280 args = {'type': name, 'value': arg_string}
2281 msg = _('invalid %(type)s value: %(value)r')
2282 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002283
2284 # return the converted value
2285 return result
2286
2287 def _check_value(self, action, value):
2288 # converted value must be one of the choices (if specified)
2289 if action.choices is not None and value not in action.choices:
Éric Araujobb48a8b2010-12-03 19:41:00 +00002290 args = {'value': value,
2291 'choices': ', '.join(map(repr, action.choices))}
2292 msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2293 raise ArgumentError(action, msg % args)
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002294
2295 # =======================
2296 # Help-formatting methods
2297 # =======================
2298 def format_usage(self):
2299 formatter = self._get_formatter()
2300 formatter.add_usage(self.usage, self._actions,
2301 self._mutually_exclusive_groups)
2302 return formatter.format_help()
2303
2304 def format_help(self):
2305 formatter = self._get_formatter()
2306
2307 # usage
2308 formatter.add_usage(self.usage, self._actions,
2309 self._mutually_exclusive_groups)
2310
2311 # description
2312 formatter.add_text(self.description)
2313
2314 # positionals, optionals and user-defined groups
2315 for action_group in self._action_groups:
2316 formatter.start_section(action_group.title)
2317 formatter.add_text(action_group.description)
2318 formatter.add_arguments(action_group._group_actions)
2319 formatter.end_section()
2320
2321 # epilog
2322 formatter.add_text(self.epilog)
2323
2324 # determine help from format above
2325 return formatter.format_help()
2326
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002327 def _get_formatter(self):
2328 return self.formatter_class(prog=self.prog)
2329
2330 # =====================
2331 # Help-printing methods
2332 # =====================
2333 def print_usage(self, file=None):
2334 if file is None:
2335 file = _sys.stdout
2336 self._print_message(self.format_usage(), file)
2337
2338 def print_help(self, file=None):
2339 if file is None:
2340 file = _sys.stdout
2341 self._print_message(self.format_help(), file)
2342
Benjamin Peterson698a18a2010-03-02 22:34:37 +00002343 def _print_message(self, message, file=None):
2344 if message:
2345 if file is None:
2346 file = _sys.stderr
2347 file.write(message)
2348
2349 # ===============
2350 # Exiting methods
2351 # ===============
2352 def exit(self, status=0, message=None):
2353 if message:
2354 self._print_message(message, _sys.stderr)
2355 _sys.exit(status)
2356
2357 def error(self, message):
2358 """error(message: string)
2359
2360 Prints a usage message incorporating the message to stderr and
2361 exits.
2362
2363 If you override this in a subclass, it should not return -- it
2364 should either exit or raise an exception.
2365 """
2366 self.print_usage(_sys.stderr)
Éric Araujobb48a8b2010-12-03 19:41:00 +00002367 args = {'prog': self.prog, 'message': message}
2368 self.exit(2, _('%(prog)s: error: %(message)s\n') % args)