blob: d5bc16c6b148915d09a2632ee7c94daa732b3433 [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:
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 Peterson0e717ad2010-03-02 23:02:02 +0000452 for i in sorted(inserts, reverse=True):
Benjamin Petersona39e9662010-03-02 22:05:59 +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 Betharddce6e1b2010-05-24 03:45:26 +0000997 help="show program's version number and exit"):
Benjamin Petersona39e9662010-03-02 22:05:59 +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
Benjamin Peterson6b31fd02010-03-07 00:29:44 +00001141 __hash__ = None
1142
Benjamin Petersona39e9662010-03-02 22:05:59 +00001143 def __eq__(self, other):
1144 return vars(self) == vars(other)
1145
1146 def __ne__(self, other):
1147 return not (self == other)
1148
1149 def __contains__(self, key):
1150 return key in self.__dict__
1151
1152
1153class _ActionsContainer(object):
1154
1155 def __init__(self,
1156 description,
1157 prefix_chars,
1158 argument_default,
1159 conflict_handler):
1160 super(_ActionsContainer, self).__init__()
1161
1162 self.description = description
1163 self.argument_default = argument_default
1164 self.prefix_chars = prefix_chars
1165 self.conflict_handler = conflict_handler
1166
1167 # set up registries
1168 self._registries = {}
1169
1170 # register actions
1171 self.register('action', None, _StoreAction)
1172 self.register('action', 'store', _StoreAction)
1173 self.register('action', 'store_const', _StoreConstAction)
1174 self.register('action', 'store_true', _StoreTrueAction)
1175 self.register('action', 'store_false', _StoreFalseAction)
1176 self.register('action', 'append', _AppendAction)
1177 self.register('action', 'append_const', _AppendConstAction)
1178 self.register('action', 'count', _CountAction)
1179 self.register('action', 'help', _HelpAction)
1180 self.register('action', 'version', _VersionAction)
1181 self.register('action', 'parsers', _SubParsersAction)
1182
1183 # raise an exception if the conflict handler is invalid
1184 self._get_handler()
1185
1186 # action storage
1187 self._actions = []
1188 self._option_string_actions = {}
1189
1190 # groups
1191 self._action_groups = []
1192 self._mutually_exclusive_groups = []
1193
1194 # defaults storage
1195 self._defaults = {}
1196
1197 # determines whether an "option" looks like a negative number
1198 self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1199
1200 # whether or not there are any optionals that look like negative
1201 # numbers -- uses a list so it can be shared and edited
1202 self._has_negative_number_optionals = []
1203
1204 # ====================
1205 # Registration methods
1206 # ====================
1207 def register(self, registry_name, value, object):
1208 registry = self._registries.setdefault(registry_name, {})
1209 registry[value] = object
1210
1211 def _registry_get(self, registry_name, value, default=None):
1212 return self._registries[registry_name].get(value, default)
1213
1214 # ==================================
1215 # Namespace default accessor methods
1216 # ==================================
1217 def set_defaults(self, **kwargs):
1218 self._defaults.update(kwargs)
1219
1220 # if these defaults match any existing arguments, replace
1221 # the previous default on the object with the new one
1222 for action in self._actions:
1223 if action.dest in kwargs:
1224 action.default = kwargs[action.dest]
1225
1226 def get_default(self, dest):
1227 for action in self._actions:
1228 if action.dest == dest and action.default is not None:
1229 return action.default
1230 return self._defaults.get(dest, None)
1231
1232
1233 # =======================
1234 # Adding argument actions
1235 # =======================
1236 def add_argument(self, *args, **kwargs):
1237 """
1238 add_argument(dest, ..., name=value, ...)
1239 add_argument(option_string, option_string, ..., name=value, ...)
1240 """
1241
1242 # if no positional args are supplied or only one is supplied and
1243 # it doesn't look like an option string, parse a positional
1244 # argument
1245 chars = self.prefix_chars
1246 if not args or len(args) == 1 and args[0][0] not in chars:
1247 if args and 'dest' in kwargs:
1248 raise ValueError('dest supplied twice for positional argument')
1249 kwargs = self._get_positional_kwargs(*args, **kwargs)
1250
1251 # otherwise, we're adding an optional argument
1252 else:
1253 kwargs = self._get_optional_kwargs(*args, **kwargs)
1254
1255 # if no default was supplied, use the parser-level default
1256 if 'default' not in kwargs:
1257 dest = kwargs['dest']
1258 if dest in self._defaults:
1259 kwargs['default'] = self._defaults[dest]
1260 elif self.argument_default is not None:
1261 kwargs['default'] = self.argument_default
1262
1263 # create the action object, and add it to the parser
1264 action_class = self._pop_action_class(kwargs)
1265 if not _callable(action_class):
1266 raise ValueError('unknown action "%s"' % action_class)
1267 action = action_class(**kwargs)
1268
1269 # raise an error if the action type is not callable
1270 type_func = self._registry_get('type', action.type, action.type)
1271 if not _callable(type_func):
1272 raise ValueError('%r is not callable' % type_func)
1273
1274 return self._add_action(action)
1275
1276 def add_argument_group(self, *args, **kwargs):
1277 group = _ArgumentGroup(self, *args, **kwargs)
1278 self._action_groups.append(group)
1279 return group
1280
1281 def add_mutually_exclusive_group(self, **kwargs):
1282 group = _MutuallyExclusiveGroup(self, **kwargs)
1283 self._mutually_exclusive_groups.append(group)
1284 return group
1285
1286 def _add_action(self, action):
1287 # resolve any conflicts
1288 self._check_conflict(action)
1289
1290 # add to actions list
1291 self._actions.append(action)
1292 action.container = self
1293
1294 # index the action by any option strings it has
1295 for option_string in action.option_strings:
1296 self._option_string_actions[option_string] = action
1297
1298 # set the flag if any option strings look like negative numbers
1299 for option_string in action.option_strings:
1300 if self._negative_number_matcher.match(option_string):
1301 if not self._has_negative_number_optionals:
1302 self._has_negative_number_optionals.append(True)
1303
1304 # return the created action
1305 return action
1306
1307 def _remove_action(self, action):
1308 self._actions.remove(action)
1309
1310 def _add_container_actions(self, container):
1311 # collect groups by titles
1312 title_group_map = {}
1313 for group in self._action_groups:
1314 if group.title in title_group_map:
1315 msg = _('cannot merge actions - two groups are named %r')
1316 raise ValueError(msg % (group.title))
1317 title_group_map[group.title] = group
1318
1319 # map each action to its group
1320 group_map = {}
1321 for group in container._action_groups:
1322
1323 # if a group with the title exists, use that, otherwise
1324 # create a new group matching the container's group
1325 if group.title not in title_group_map:
1326 title_group_map[group.title] = self.add_argument_group(
1327 title=group.title,
1328 description=group.description,
1329 conflict_handler=group.conflict_handler)
1330
1331 # map the actions to their new group
1332 for action in group._group_actions:
1333 group_map[action] = title_group_map[group.title]
1334
1335 # add container's mutually exclusive groups
1336 # NOTE: if add_mutually_exclusive_group ever gains title= and
1337 # description= then this code will need to be expanded as above
1338 for group in container._mutually_exclusive_groups:
1339 mutex_group = self.add_mutually_exclusive_group(
1340 required=group.required)
1341
1342 # map the actions to their new mutex group
1343 for action in group._group_actions:
1344 group_map[action] = mutex_group
1345
1346 # add all actions to this container or their group
1347 for action in container._actions:
1348 group_map.get(action, self)._add_action(action)
1349
1350 def _get_positional_kwargs(self, dest, **kwargs):
1351 # make sure required is not specified
1352 if 'required' in kwargs:
1353 msg = _("'required' is an invalid argument for positionals")
1354 raise TypeError(msg)
1355
1356 # mark positional arguments as required if at least one is
1357 # always required
1358 if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1359 kwargs['required'] = True
1360 if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1361 kwargs['required'] = True
1362
1363 # return the keyword arguments with no option strings
1364 return dict(kwargs, dest=dest, option_strings=[])
1365
1366 def _get_optional_kwargs(self, *args, **kwargs):
1367 # determine short and long option strings
1368 option_strings = []
1369 long_option_strings = []
1370 for option_string in args:
1371 # error on strings that don't start with an appropriate prefix
1372 if not option_string[0] in self.prefix_chars:
1373 msg = _('invalid option string %r: '
1374 'must start with a character %r')
1375 tup = option_string, self.prefix_chars
1376 raise ValueError(msg % tup)
1377
1378 # strings starting with two prefix characters are long options
1379 option_strings.append(option_string)
1380 if option_string[0] in self.prefix_chars:
1381 if len(option_string) > 1:
1382 if option_string[1] in self.prefix_chars:
1383 long_option_strings.append(option_string)
1384
1385 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1386 dest = kwargs.pop('dest', None)
1387 if dest is None:
1388 if long_option_strings:
1389 dest_option_string = long_option_strings[0]
1390 else:
1391 dest_option_string = option_strings[0]
1392 dest = dest_option_string.lstrip(self.prefix_chars)
1393 if not dest:
1394 msg = _('dest= is required for options like %r')
1395 raise ValueError(msg % option_string)
1396 dest = dest.replace('-', '_')
1397
1398 # return the updated keyword arguments
1399 return dict(kwargs, dest=dest, option_strings=option_strings)
1400
1401 def _pop_action_class(self, kwargs, default=None):
1402 action = kwargs.pop('action', default)
1403 return self._registry_get('action', action, action)
1404
1405 def _get_handler(self):
1406 # determine function from conflict handler string
1407 handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1408 try:
1409 return getattr(self, handler_func_name)
1410 except AttributeError:
1411 msg = _('invalid conflict_resolution value: %r')
1412 raise ValueError(msg % self.conflict_handler)
1413
1414 def _check_conflict(self, action):
1415
1416 # find all options that conflict with this option
1417 confl_optionals = []
1418 for option_string in action.option_strings:
1419 if option_string in self._option_string_actions:
1420 confl_optional = self._option_string_actions[option_string]
1421 confl_optionals.append((option_string, confl_optional))
1422
1423 # resolve any conflicts
1424 if confl_optionals:
1425 conflict_handler = self._get_handler()
1426 conflict_handler(action, confl_optionals)
1427
1428 def _handle_conflict_error(self, action, conflicting_actions):
1429 message = _('conflicting option string(s): %s')
1430 conflict_string = ', '.join([option_string
1431 for option_string, action
1432 in conflicting_actions])
1433 raise ArgumentError(action, message % conflict_string)
1434
1435 def _handle_conflict_resolve(self, action, conflicting_actions):
1436
1437 # remove all conflicting options
1438 for option_string, action in conflicting_actions:
1439
1440 # remove the conflicting option
1441 action.option_strings.remove(option_string)
1442 self._option_string_actions.pop(option_string, None)
1443
1444 # if the option now has no option string, remove it from the
1445 # container holding it
1446 if not action.option_strings:
1447 action.container._remove_action(action)
1448
1449
1450class _ArgumentGroup(_ActionsContainer):
1451
1452 def __init__(self, container, title=None, description=None, **kwargs):
1453 # add any missing keyword arguments by checking the container
1454 update = kwargs.setdefault
1455 update('conflict_handler', container.conflict_handler)
1456 update('prefix_chars', container.prefix_chars)
1457 update('argument_default', container.argument_default)
1458 super_init = super(_ArgumentGroup, self).__init__
1459 super_init(description=description, **kwargs)
1460
1461 # group attributes
1462 self.title = title
1463 self._group_actions = []
1464
1465 # share most attributes with the container
1466 self._registries = container._registries
1467 self._actions = container._actions
1468 self._option_string_actions = container._option_string_actions
1469 self._defaults = container._defaults
1470 self._has_negative_number_optionals = \
1471 container._has_negative_number_optionals
1472
1473 def _add_action(self, action):
1474 action = super(_ArgumentGroup, self)._add_action(action)
1475 self._group_actions.append(action)
1476 return action
1477
1478 def _remove_action(self, action):
1479 super(_ArgumentGroup, self)._remove_action(action)
1480 self._group_actions.remove(action)
1481
1482
1483class _MutuallyExclusiveGroup(_ArgumentGroup):
1484
1485 def __init__(self, container, required=False):
1486 super(_MutuallyExclusiveGroup, self).__init__(container)
1487 self.required = required
1488 self._container = container
1489
1490 def _add_action(self, action):
1491 if action.required:
1492 msg = _('mutually exclusive arguments must be optional')
1493 raise ValueError(msg)
1494 action = self._container._add_action(action)
1495 self._group_actions.append(action)
1496 return action
1497
1498 def _remove_action(self, action):
1499 self._container._remove_action(action)
1500 self._group_actions.remove(action)
1501
1502
1503class ArgumentParser(_AttributeHolder, _ActionsContainer):
1504 """Object for parsing command line strings into Python objects.
1505
1506 Keyword Arguments:
1507 - prog -- The name of the program (default: sys.argv[0])
1508 - usage -- A usage message (default: auto-generated from arguments)
1509 - description -- A description of what the program does
1510 - epilog -- Text following the argument descriptions
1511 - parents -- Parsers whose arguments should be copied into this one
1512 - formatter_class -- HelpFormatter class for printing help messages
1513 - prefix_chars -- Characters that prefix optional arguments
1514 - fromfile_prefix_chars -- Characters that prefix files containing
1515 additional arguments
1516 - argument_default -- The default value for all arguments
1517 - conflict_handler -- String indicating how to handle conflicts
1518 - add_help -- Add a -h/-help option
1519 """
1520
1521 def __init__(self,
1522 prog=None,
1523 usage=None,
1524 description=None,
1525 epilog=None,
1526 version=None,
1527 parents=[],
1528 formatter_class=HelpFormatter,
1529 prefix_chars='-',
1530 fromfile_prefix_chars=None,
1531 argument_default=None,
1532 conflict_handler='error',
1533 add_help=True):
1534
1535 if version is not None:
1536 import warnings
1537 warnings.warn(
1538 """The "version" argument to ArgumentParser is deprecated. """
1539 """Please use """
1540 """"add_argument(..., action='version', version="N", ...)" """
1541 """instead""", DeprecationWarning)
1542
1543 superinit = super(ArgumentParser, self).__init__
1544 superinit(description=description,
1545 prefix_chars=prefix_chars,
1546 argument_default=argument_default,
1547 conflict_handler=conflict_handler)
1548
1549 # default setting for prog
1550 if prog is None:
1551 prog = _os.path.basename(_sys.argv[0])
1552
1553 self.prog = prog
1554 self.usage = usage
1555 self.epilog = epilog
1556 self.version = version
1557 self.formatter_class = formatter_class
1558 self.fromfile_prefix_chars = fromfile_prefix_chars
1559 self.add_help = add_help
1560
1561 add_group = self.add_argument_group
1562 self._positionals = add_group(_('positional arguments'))
1563 self._optionals = add_group(_('optional arguments'))
1564 self._subparsers = None
1565
1566 # register types
1567 def identity(string):
1568 return string
1569 self.register('type', None, identity)
1570
1571 # add help and version arguments if necessary
1572 # (using explicit default to override global argument_default)
R. David Murray1cbf78e2010-08-03 18:14:01 +00001573 default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
Benjamin Petersona39e9662010-03-02 22:05:59 +00001574 if self.add_help:
1575 self.add_argument(
R. David Murray1cbf78e2010-08-03 18:14:01 +00001576 default_prefix+'h', default_prefix*2+'help',
1577 action='help', default=SUPPRESS,
Benjamin Petersona39e9662010-03-02 22:05:59 +00001578 help=_('show this help message and exit'))
1579 if self.version:
1580 self.add_argument(
R. David Murray1cbf78e2010-08-03 18:14:01 +00001581 default_prefix+'v', default_prefix*2+'version',
1582 action='version', default=SUPPRESS,
Benjamin Petersona39e9662010-03-02 22:05:59 +00001583 version=self.version,
1584 help=_("show program's version number and exit"))
1585
1586 # add parent arguments and defaults
1587 for parent in parents:
1588 self._add_container_actions(parent)
1589 try:
1590 defaults = parent._defaults
1591 except AttributeError:
1592 pass
1593 else:
1594 self._defaults.update(defaults)
1595
1596 # =======================
1597 # Pretty __repr__ methods
1598 # =======================
1599 def _get_kwargs(self):
1600 names = [
1601 'prog',
1602 'usage',
1603 'description',
1604 'version',
1605 'formatter_class',
1606 'conflict_handler',
1607 'add_help',
1608 ]
1609 return [(name, getattr(self, name)) for name in names]
1610
1611 # ==================================
1612 # Optional/Positional adding methods
1613 # ==================================
1614 def add_subparsers(self, **kwargs):
1615 if self._subparsers is not None:
1616 self.error(_('cannot have multiple subparser arguments'))
1617
1618 # add the parser class to the arguments if it's not present
1619 kwargs.setdefault('parser_class', type(self))
1620
1621 if 'title' in kwargs or 'description' in kwargs:
1622 title = _(kwargs.pop('title', 'subcommands'))
1623 description = _(kwargs.pop('description', None))
1624 self._subparsers = self.add_argument_group(title, description)
1625 else:
1626 self._subparsers = self._positionals
1627
1628 # prog defaults to the usage message of this parser, skipping
1629 # optional arguments and with no "usage:" prefix
1630 if kwargs.get('prog') is None:
1631 formatter = self._get_formatter()
1632 positionals = self._get_positional_actions()
1633 groups = self._mutually_exclusive_groups
1634 formatter.add_usage(self.usage, positionals, groups, '')
1635 kwargs['prog'] = formatter.format_help().strip()
1636
1637 # create the parsers action and add it to the positionals list
1638 parsers_class = self._pop_action_class(kwargs, 'parsers')
1639 action = parsers_class(option_strings=[], **kwargs)
1640 self._subparsers._add_action(action)
1641
1642 # return the created parsers action
1643 return action
1644
1645 def _add_action(self, action):
1646 if action.option_strings:
1647 self._optionals._add_action(action)
1648 else:
1649 self._positionals._add_action(action)
1650 return action
1651
1652 def _get_optional_actions(self):
1653 return [action
1654 for action in self._actions
1655 if action.option_strings]
1656
1657 def _get_positional_actions(self):
1658 return [action
1659 for action in self._actions
1660 if not action.option_strings]
1661
1662 # =====================================
1663 # Command line argument parsing methods
1664 # =====================================
1665 def parse_args(self, args=None, namespace=None):
1666 args, argv = self.parse_known_args(args, namespace)
1667 if argv:
1668 msg = _('unrecognized arguments: %s')
1669 self.error(msg % ' '.join(argv))
1670 return args
1671
1672 def parse_known_args(self, args=None, namespace=None):
1673 # args default to the system args
1674 if args is None:
1675 args = _sys.argv[1:]
1676
1677 # default Namespace built from parser defaults
1678 if namespace is None:
1679 namespace = Namespace()
1680
1681 # add any action defaults that aren't present
1682 for action in self._actions:
1683 if action.dest is not SUPPRESS:
1684 if not hasattr(namespace, action.dest):
1685 if action.default is not SUPPRESS:
1686 default = action.default
Benjamin Peterson0e717ad2010-03-02 23:02:02 +00001687 if isinstance(action.default, basestring):
Benjamin Petersona39e9662010-03-02 22:05:59 +00001688 default = self._get_value(action, default)
1689 setattr(namespace, action.dest, default)
1690
1691 # add any parser defaults that aren't present
1692 for dest in self._defaults:
1693 if not hasattr(namespace, dest):
1694 setattr(namespace, dest, self._defaults[dest])
1695
1696 # parse the arguments and exit if there are any errors
1697 try:
1698 return self._parse_known_args(args, namespace)
1699 except ArgumentError:
1700 err = _sys.exc_info()[1]
1701 self.error(str(err))
1702
1703 def _parse_known_args(self, arg_strings, namespace):
1704 # replace arg strings that are file references
1705 if self.fromfile_prefix_chars is not None:
1706 arg_strings = self._read_args_from_files(arg_strings)
1707
1708 # map all mutually exclusive arguments to the other arguments
1709 # they can't occur with
1710 action_conflicts = {}
1711 for mutex_group in self._mutually_exclusive_groups:
1712 group_actions = mutex_group._group_actions
1713 for i, mutex_action in enumerate(mutex_group._group_actions):
1714 conflicts = action_conflicts.setdefault(mutex_action, [])
1715 conflicts.extend(group_actions[:i])
1716 conflicts.extend(group_actions[i + 1:])
1717
1718 # find all option indices, and determine the arg_string_pattern
1719 # which has an 'O' if there is an option at an index,
1720 # an 'A' if there is an argument, or a '-' if there is a '--'
1721 option_string_indices = {}
1722 arg_string_pattern_parts = []
1723 arg_strings_iter = iter(arg_strings)
1724 for i, arg_string in enumerate(arg_strings_iter):
1725
1726 # all args after -- are non-options
1727 if arg_string == '--':
1728 arg_string_pattern_parts.append('-')
1729 for arg_string in arg_strings_iter:
1730 arg_string_pattern_parts.append('A')
1731
1732 # otherwise, add the arg to the arg strings
1733 # and note the index if it was an option
1734 else:
1735 option_tuple = self._parse_optional(arg_string)
1736 if option_tuple is None:
1737 pattern = 'A'
1738 else:
1739 option_string_indices[i] = option_tuple
1740 pattern = 'O'
1741 arg_string_pattern_parts.append(pattern)
1742
1743 # join the pieces together to form the pattern
1744 arg_strings_pattern = ''.join(arg_string_pattern_parts)
1745
1746 # converts arg strings to the appropriate and then takes the action
Benjamin Peterson0e717ad2010-03-02 23:02:02 +00001747 seen_actions = set()
1748 seen_non_default_actions = set()
Benjamin Petersona39e9662010-03-02 22:05:59 +00001749
1750 def take_action(action, argument_strings, option_string=None):
1751 seen_actions.add(action)
1752 argument_values = self._get_values(action, argument_strings)
1753
1754 # error if this argument is not allowed with other previously
1755 # seen arguments, assuming that actions that use the default
1756 # value don't really count as "present"
1757 if argument_values is not action.default:
1758 seen_non_default_actions.add(action)
1759 for conflict_action in action_conflicts.get(action, []):
1760 if conflict_action in seen_non_default_actions:
1761 msg = _('not allowed with argument %s')
1762 action_name = _get_action_name(conflict_action)
1763 raise ArgumentError(action, msg % action_name)
1764
1765 # take the action if we didn't receive a SUPPRESS value
1766 # (e.g. from a default)
1767 if argument_values is not SUPPRESS:
1768 action(self, namespace, argument_values, option_string)
1769
1770 # function to convert arg_strings into an optional action
1771 def consume_optional(start_index):
1772
1773 # get the optional identified at this index
1774 option_tuple = option_string_indices[start_index]
1775 action, option_string, explicit_arg = option_tuple
1776
1777 # identify additional optionals in the same arg string
1778 # (e.g. -xyz is the same as -x -y -z if no args are required)
1779 match_argument = self._match_argument
1780 action_tuples = []
1781 while True:
1782
1783 # if we found no optional action, skip it
1784 if action is None:
1785 extras.append(arg_strings[start_index])
1786 return start_index + 1
1787
1788 # if there is an explicit argument, try to match the
1789 # optional's string arguments to only this
1790 if explicit_arg is not None:
1791 arg_count = match_argument(action, 'A')
1792
1793 # if the action is a single-dash option and takes no
1794 # arguments, try to parse more single-dash options out
1795 # of the tail of the option string
1796 chars = self.prefix_chars
1797 if arg_count == 0 and option_string[1] not in chars:
1798 action_tuples.append((action, [], option_string))
1799 for char in self.prefix_chars:
1800 option_string = char + explicit_arg[0]
1801 explicit_arg = explicit_arg[1:] or None
1802 optionals_map = self._option_string_actions
1803 if option_string in optionals_map:
1804 action = optionals_map[option_string]
1805 break
1806 else:
1807 msg = _('ignored explicit argument %r')
1808 raise ArgumentError(action, msg % explicit_arg)
1809
1810 # if the action expect exactly one argument, we've
1811 # successfully matched the option; exit the loop
1812 elif arg_count == 1:
1813 stop = start_index + 1
1814 args = [explicit_arg]
1815 action_tuples.append((action, args, option_string))
1816 break
1817
1818 # error if a double-dash option did not use the
1819 # explicit argument
1820 else:
1821 msg = _('ignored explicit argument %r')
1822 raise ArgumentError(action, msg % explicit_arg)
1823
1824 # if there is no explicit argument, try to match the
1825 # optional's string arguments with the following strings
1826 # if successful, exit the loop
1827 else:
1828 start = start_index + 1
1829 selected_patterns = arg_strings_pattern[start:]
1830 arg_count = match_argument(action, selected_patterns)
1831 stop = start + arg_count
1832 args = arg_strings[start:stop]
1833 action_tuples.append((action, args, option_string))
1834 break
1835
1836 # add the Optional to the list and return the index at which
1837 # the Optional's string args stopped
1838 assert action_tuples
1839 for action, args, option_string in action_tuples:
1840 take_action(action, args, option_string)
1841 return stop
1842
1843 # the list of Positionals left to be parsed; this is modified
1844 # by consume_positionals()
1845 positionals = self._get_positional_actions()
1846
1847 # function to convert arg_strings into positional actions
1848 def consume_positionals(start_index):
1849 # match as many Positionals as possible
1850 match_partial = self._match_arguments_partial
1851 selected_pattern = arg_strings_pattern[start_index:]
1852 arg_counts = match_partial(positionals, selected_pattern)
1853
1854 # slice off the appropriate arg strings for each Positional
1855 # and add the Positional and its args to the list
1856 for action, arg_count in zip(positionals, arg_counts):
1857 args = arg_strings[start_index: start_index + arg_count]
1858 start_index += arg_count
1859 take_action(action, args)
1860
1861 # slice off the Positionals that we just parsed and return the
1862 # index at which the Positionals' string args stopped
1863 positionals[:] = positionals[len(arg_counts):]
1864 return start_index
1865
1866 # consume Positionals and Optionals alternately, until we have
1867 # passed the last option string
1868 extras = []
1869 start_index = 0
1870 if option_string_indices:
1871 max_option_string_index = max(option_string_indices)
1872 else:
1873 max_option_string_index = -1
1874 while start_index <= max_option_string_index:
1875
1876 # consume any Positionals preceding the next option
1877 next_option_string_index = min([
1878 index
1879 for index in option_string_indices
1880 if index >= start_index])
1881 if start_index != next_option_string_index:
1882 positionals_end_index = consume_positionals(start_index)
1883
1884 # only try to parse the next optional if we didn't consume
1885 # the option string during the positionals parsing
1886 if positionals_end_index > start_index:
1887 start_index = positionals_end_index
1888 continue
1889 else:
1890 start_index = positionals_end_index
1891
1892 # if we consumed all the positionals we could and we're not
1893 # at the index of an option string, there were extra arguments
1894 if start_index not in option_string_indices:
1895 strings = arg_strings[start_index:next_option_string_index]
1896 extras.extend(strings)
1897 start_index = next_option_string_index
1898
1899 # consume the next optional and any arguments for it
1900 start_index = consume_optional(start_index)
1901
1902 # consume any positionals following the last Optional
1903 stop_index = consume_positionals(start_index)
1904
1905 # if we didn't consume all the argument strings, there were extras
1906 extras.extend(arg_strings[stop_index:])
1907
1908 # if we didn't use all the Positional objects, there were too few
1909 # arg strings supplied.
1910 if positionals:
1911 self.error(_('too few arguments'))
1912
1913 # make sure all required actions were present
1914 for action in self._actions:
1915 if action.required:
1916 if action not in seen_actions:
1917 name = _get_action_name(action)
1918 self.error(_('argument %s is required') % name)
1919
1920 # make sure all required groups had one option present
1921 for group in self._mutually_exclusive_groups:
1922 if group.required:
1923 for action in group._group_actions:
1924 if action in seen_non_default_actions:
1925 break
1926
1927 # if no actions were used, report the error
1928 else:
1929 names = [_get_action_name(action)
1930 for action in group._group_actions
1931 if action.help is not SUPPRESS]
1932 msg = _('one of the arguments %s is required')
1933 self.error(msg % ' '.join(names))
1934
1935 # return the updated namespace and the extra arguments
1936 return namespace, extras
1937
1938 def _read_args_from_files(self, arg_strings):
1939 # expand arguments referencing files
1940 new_arg_strings = []
1941 for arg_string in arg_strings:
1942
1943 # for regular arguments, just add them back into the list
1944 if arg_string[0] not in self.fromfile_prefix_chars:
1945 new_arg_strings.append(arg_string)
1946
1947 # replace arguments referencing files with the file content
1948 else:
1949 try:
1950 args_file = open(arg_string[1:])
1951 try:
1952 arg_strings = []
1953 for arg_line in args_file.read().splitlines():
1954 for arg in self.convert_arg_line_to_args(arg_line):
1955 arg_strings.append(arg)
1956 arg_strings = self._read_args_from_files(arg_strings)
1957 new_arg_strings.extend(arg_strings)
1958 finally:
1959 args_file.close()
1960 except IOError:
1961 err = _sys.exc_info()[1]
1962 self.error(str(err))
1963
1964 # return the modified argument list
1965 return new_arg_strings
1966
1967 def convert_arg_line_to_args(self, arg_line):
1968 return [arg_line]
1969
1970 def _match_argument(self, action, arg_strings_pattern):
1971 # match the pattern for this action to the arg strings
1972 nargs_pattern = self._get_nargs_pattern(action)
1973 match = _re.match(nargs_pattern, arg_strings_pattern)
1974
1975 # raise an exception if we weren't able to find a match
1976 if match is None:
1977 nargs_errors = {
1978 None: _('expected one argument'),
1979 OPTIONAL: _('expected at most one argument'),
1980 ONE_OR_MORE: _('expected at least one argument'),
1981 }
1982 default = _('expected %s argument(s)') % action.nargs
1983 msg = nargs_errors.get(action.nargs, default)
1984 raise ArgumentError(action, msg)
1985
1986 # return the number of arguments matched
1987 return len(match.group(1))
1988
1989 def _match_arguments_partial(self, actions, arg_strings_pattern):
1990 # progressively shorten the actions list by slicing off the
1991 # final actions until we find a match
1992 result = []
1993 for i in range(len(actions), 0, -1):
1994 actions_slice = actions[:i]
1995 pattern = ''.join([self._get_nargs_pattern(action)
1996 for action in actions_slice])
1997 match = _re.match(pattern, arg_strings_pattern)
1998 if match is not None:
1999 result.extend([len(string) for string in match.groups()])
2000 break
2001
2002 # return the list of arg string counts
2003 return result
2004
2005 def _parse_optional(self, arg_string):
2006 # if it's an empty string, it was meant to be a positional
2007 if not arg_string:
2008 return None
2009
2010 # if it doesn't start with a prefix, it was meant to be positional
2011 if not arg_string[0] in self.prefix_chars:
2012 return None
2013
2014 # if the option string is present in the parser, return the action
2015 if arg_string in self._option_string_actions:
2016 action = self._option_string_actions[arg_string]
2017 return action, arg_string, None
2018
2019 # if it's just a single character, it was meant to be positional
2020 if len(arg_string) == 1:
2021 return None
2022
2023 # if the option string before the "=" is present, return the action
2024 if '=' in arg_string:
2025 option_string, explicit_arg = arg_string.split('=', 1)
2026 if option_string in self._option_string_actions:
2027 action = self._option_string_actions[option_string]
2028 return action, option_string, explicit_arg
2029
2030 # search through all possible prefixes of the option string
2031 # and all actions in the parser for possible interpretations
2032 option_tuples = self._get_option_tuples(arg_string)
2033
2034 # if multiple actions match, the option string was ambiguous
2035 if len(option_tuples) > 1:
2036 options = ', '.join([option_string
2037 for action, option_string, explicit_arg in option_tuples])
2038 tup = arg_string, options
2039 self.error(_('ambiguous option: %s could match %s') % tup)
2040
2041 # if exactly one action matched, this segmentation is good,
2042 # so return the parsed action
2043 elif len(option_tuples) == 1:
2044 option_tuple, = option_tuples
2045 return option_tuple
2046
2047 # if it was not found as an option, but it looks like a negative
2048 # number, it was meant to be positional
2049 # unless there are negative-number-like options
2050 if self._negative_number_matcher.match(arg_string):
2051 if not self._has_negative_number_optionals:
2052 return None
2053
2054 # if it contains a space, it was meant to be a positional
2055 if ' ' in arg_string:
2056 return None
2057
2058 # it was meant to be an optional but there is no such option
2059 # in this parser (though it might be a valid option in a subparser)
2060 return None, arg_string, None
2061
2062 def _get_option_tuples(self, option_string):
2063 result = []
2064
2065 # option strings starting with two prefix characters are only
2066 # split at the '='
2067 chars = self.prefix_chars
2068 if option_string[0] in chars and option_string[1] in chars:
2069 if '=' in option_string:
2070 option_prefix, explicit_arg = option_string.split('=', 1)
2071 else:
2072 option_prefix = option_string
2073 explicit_arg = None
2074 for option_string in self._option_string_actions:
2075 if option_string.startswith(option_prefix):
2076 action = self._option_string_actions[option_string]
2077 tup = action, option_string, explicit_arg
2078 result.append(tup)
2079
2080 # single character options can be concatenated with their arguments
2081 # but multiple character options always have to have their argument
2082 # separate
2083 elif option_string[0] in chars and option_string[1] not in chars:
2084 option_prefix = option_string
2085 explicit_arg = None
2086 short_option_prefix = option_string[:2]
2087 short_explicit_arg = option_string[2:]
2088
2089 for option_string in self._option_string_actions:
2090 if option_string == short_option_prefix:
2091 action = self._option_string_actions[option_string]
2092 tup = action, option_string, short_explicit_arg
2093 result.append(tup)
2094 elif option_string.startswith(option_prefix):
2095 action = self._option_string_actions[option_string]
2096 tup = action, option_string, explicit_arg
2097 result.append(tup)
2098
2099 # shouldn't ever get here
2100 else:
2101 self.error(_('unexpected option string: %s') % option_string)
2102
2103 # return the collected option tuples
2104 return result
2105
2106 def _get_nargs_pattern(self, action):
2107 # in all examples below, we have to allow for '--' args
2108 # which are represented as '-' in the pattern
2109 nargs = action.nargs
2110
2111 # the default (None) is assumed to be a single argument
2112 if nargs is None:
2113 nargs_pattern = '(-*A-*)'
2114
2115 # allow zero or one arguments
2116 elif nargs == OPTIONAL:
2117 nargs_pattern = '(-*A?-*)'
2118
2119 # allow zero or more arguments
2120 elif nargs == ZERO_OR_MORE:
2121 nargs_pattern = '(-*[A-]*)'
2122
2123 # allow one or more arguments
2124 elif nargs == ONE_OR_MORE:
2125 nargs_pattern = '(-*A[A-]*)'
2126
2127 # allow any number of options or arguments
2128 elif nargs == REMAINDER:
2129 nargs_pattern = '([-AO]*)'
2130
2131 # allow one argument followed by any number of options or arguments
2132 elif nargs == PARSER:
2133 nargs_pattern = '(-*A[-AO]*)'
2134
2135 # all others should be integers
2136 else:
2137 nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2138
2139 # if this is an optional action, -- is not allowed
2140 if action.option_strings:
2141 nargs_pattern = nargs_pattern.replace('-*', '')
2142 nargs_pattern = nargs_pattern.replace('-', '')
2143
2144 # return the pattern
2145 return nargs_pattern
2146
2147 # ========================
2148 # Value conversion methods
2149 # ========================
2150 def _get_values(self, action, arg_strings):
2151 # for everything but PARSER args, strip out '--'
2152 if action.nargs not in [PARSER, REMAINDER]:
2153 arg_strings = [s for s in arg_strings if s != '--']
2154
2155 # optional argument produces a default when not present
2156 if not arg_strings and action.nargs == OPTIONAL:
2157 if action.option_strings:
2158 value = action.const
2159 else:
2160 value = action.default
Benjamin Peterson0e717ad2010-03-02 23:02:02 +00002161 if isinstance(value, basestring):
Benjamin Petersona39e9662010-03-02 22:05:59 +00002162 value = self._get_value(action, value)
2163 self._check_value(action, value)
2164
2165 # when nargs='*' on a positional, if there were no command-line
2166 # args, use the default if it is anything other than None
2167 elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2168 not action.option_strings):
2169 if action.default is not None:
2170 value = action.default
2171 else:
2172 value = arg_strings
2173 self._check_value(action, value)
2174
2175 # single argument or optional argument produces a single value
2176 elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2177 arg_string, = arg_strings
2178 value = self._get_value(action, arg_string)
2179 self._check_value(action, value)
2180
2181 # REMAINDER arguments convert all values, checking none
2182 elif action.nargs == REMAINDER:
2183 value = [self._get_value(action, v) for v in arg_strings]
2184
2185 # PARSER arguments convert all values, but check only the first
2186 elif action.nargs == PARSER:
2187 value = [self._get_value(action, v) for v in arg_strings]
2188 self._check_value(action, value[0])
2189
2190 # all other types of nargs produce a list
2191 else:
2192 value = [self._get_value(action, v) for v in arg_strings]
2193 for v in value:
2194 self._check_value(action, v)
2195
2196 # return the converted value
2197 return value
2198
2199 def _get_value(self, action, arg_string):
2200 type_func = self._registry_get('type', action.type, action.type)
2201 if not _callable(type_func):
2202 msg = _('%r is not callable')
2203 raise ArgumentError(action, msg % type_func)
2204
2205 # convert the value to the appropriate type
2206 try:
2207 result = type_func(arg_string)
2208
2209 # ArgumentTypeErrors indicate errors
2210 except ArgumentTypeError:
2211 name = getattr(action.type, '__name__', repr(action.type))
2212 msg = str(_sys.exc_info()[1])
2213 raise ArgumentError(action, msg)
2214
2215 # TypeErrors or ValueErrors also indicate errors
2216 except (TypeError, ValueError):
2217 name = getattr(action.type, '__name__', repr(action.type))
2218 msg = _('invalid %s value: %r')
2219 raise ArgumentError(action, msg % (name, arg_string))
2220
2221 # return the converted value
2222 return result
2223
2224 def _check_value(self, action, value):
2225 # converted value must be one of the choices (if specified)
2226 if action.choices is not None and value not in action.choices:
2227 tup = value, ', '.join(map(repr, action.choices))
2228 msg = _('invalid choice: %r (choose from %s)') % tup
2229 raise ArgumentError(action, msg)
2230
2231 # =======================
2232 # Help-formatting methods
2233 # =======================
2234 def format_usage(self):
2235 formatter = self._get_formatter()
2236 formatter.add_usage(self.usage, self._actions,
2237 self._mutually_exclusive_groups)
2238 return formatter.format_help()
2239
2240 def format_help(self):
2241 formatter = self._get_formatter()
2242
2243 # usage
2244 formatter.add_usage(self.usage, self._actions,
2245 self._mutually_exclusive_groups)
2246
2247 # description
2248 formatter.add_text(self.description)
2249
2250 # positionals, optionals and user-defined groups
2251 for action_group in self._action_groups:
2252 formatter.start_section(action_group.title)
2253 formatter.add_text(action_group.description)
2254 formatter.add_arguments(action_group._group_actions)
2255 formatter.end_section()
2256
2257 # epilog
2258 formatter.add_text(self.epilog)
2259
2260 # determine help from format above
2261 return formatter.format_help()
2262
2263 def format_version(self):
2264 import warnings
2265 warnings.warn(
2266 'The format_version method is deprecated -- the "version" '
2267 'argument to ArgumentParser is no longer supported.',
2268 DeprecationWarning)
2269 formatter = self._get_formatter()
2270 formatter.add_text(self.version)
2271 return formatter.format_help()
2272
2273 def _get_formatter(self):
2274 return self.formatter_class(prog=self.prog)
2275
2276 # =====================
2277 # Help-printing methods
2278 # =====================
2279 def print_usage(self, file=None):
2280 if file is None:
2281 file = _sys.stdout
2282 self._print_message(self.format_usage(), file)
2283
2284 def print_help(self, file=None):
2285 if file is None:
2286 file = _sys.stdout
2287 self._print_message(self.format_help(), file)
2288
2289 def print_version(self, file=None):
2290 import warnings
2291 warnings.warn(
2292 'The print_version method is deprecated -- the "version" '
2293 'argument to ArgumentParser is no longer supported.',
2294 DeprecationWarning)
2295 self._print_message(self.format_version(), file)
2296
2297 def _print_message(self, message, file=None):
2298 if message:
2299 if file is None:
2300 file = _sys.stderr
2301 file.write(message)
2302
2303 # ===============
2304 # Exiting methods
2305 # ===============
2306 def exit(self, status=0, message=None):
2307 if message:
2308 self._print_message(message, _sys.stderr)
2309 _sys.exit(status)
2310
2311 def error(self, message):
2312 """error(message: string)
2313
2314 Prints a usage message incorporating the message to stderr and
2315 exits.
2316
2317 If you override this in a subclass, it should not return -- it
2318 should either exit or raise an exception.
2319 """
2320 self.print_usage(_sys.stderr)
2321 self.exit(2, _('%s: error: %s\n') % (self.prog, message))