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