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