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