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