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