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