Debian Codegraph @

lib-python/3/argparse.py

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