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