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