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