1 # This is a local copy of the standard library argparse module taken from PyPI.
2 # It is licensed under the Python Software Foundation License. This is a
3 # fallback for Python 2.6 which does not include this module. Python 2.7+ and
4 # 3+ will never load this module because built-in modules are loaded before
5 # anything in sys.path.
7 # If your script is not located in the same directory as this file, import it
12 # sys.path.append(os.path.join(os.path.dirname(__file__), ..., 'scripts'))
15 # Author: Steven J. Bethard <steven.bethard@gmail.com>.
16 # Maintainer: Thomas Waldmann <tw@waldmann-edv.de>
18 """Command-line parsing library
20 This module is an optparse-inspired command-line parsing library that:
22 - handles both optional and positional arguments
23 - produces highly informative usage messages
24 - supports parsers that dispatch to sub-parsers
26 The following is a simple usage example that sums integers from the
27 command-line and writes the result to a file::
29 parser = argparse.ArgumentParser(
30 description='sum the integers at the command line')
32 'integers', metavar='int', nargs='+', type=int,
33 help='an integer to be summed')
35 '--log', default=sys.stdout, type=argparse.FileType('w'),
36 help='the file where the sum should be written')
37 args = parser.parse_args()
38 args.log.write('%s' % sum(args.integers))
41 The module contains the following public classes:
43 - ArgumentParser -- The main entry point for command-line parsing. As the
44 example above shows, the add_argument() method is used to populate
45 the parser with actions for optional and positional arguments. Then
46 the parse_args() method is invoked to convert the args at the
47 command-line into an object with attributes.
49 - ArgumentError -- The exception raised by ArgumentParser objects when
50 there are errors with the parser's actions. Errors raised while
51 parsing the command-line are caught by ArgumentParser and emitted
52 as command-line messages.
54 - FileType -- A factory for defining types of files to be created. As the
55 example above shows, instances of FileType are typically passed as
56 the type= argument of add_argument() calls.
58 - Action -- The base class for parser actions. Typically actions are
59 selected by passing strings like 'store_true' or 'append_const' to
60 the action= argument of add_argument(). However, for greater
61 customization of ArgumentParser actions, subclasses of Action may
62 be defined and passed as the action= argument.
64 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
65 ArgumentDefaultsHelpFormatter -- Formatter classes which
66 may be passed as the formatter_class= argument to the
67 ArgumentParser constructor. HelpFormatter is the default,
68 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
69 not to change the formatting for help text, and
70 ArgumentDefaultsHelpFormatter adds information about argument defaults
73 All other classes in this module are considered implementation details.
74 (Also note that HelpFormatter and RawDescriptionHelpFormatter are only
75 considered public as object names -- the API of the formatter objects is
76 still considered an implementation detail.)
79 __version__
= '1.4.0' # we use our own version number independant of the
80 # one in stdlib and we release this on pypi.
82 __external_lib__
= True # to make sure the tests really test THIS lib,
83 # not the builtin one in Python stdlib
91 'ArgumentDefaultsHelpFormatter',
92 'RawDescriptionHelpFormatter',
93 'RawTextHelpFormatter',
109 import textwrap
as _textwrap
111 from gettext
import gettext
as _
116 # for python < 2.4 compatibility (sets module is there since 2.3):
117 from sets
import Set
as set
127 # for python < 2.4 compatibility:
128 def sorted(iterable
, reverse
=False):
129 result
= list(iterable
)
137 return hasattr(obj
, '__call__') or hasattr(obj
, '__bases__')
140 SUPPRESS
= '==SUPPRESS=='
147 _UNRECOGNIZED_ARGS_ATTR
= '_unrecognized_args'
149 # =============================
150 # Utility functions and classes
151 # =============================
153 class _AttributeHolder(object):
154 """Abstract base class that provides __repr__.
156 The __repr__ method returns a string in the format::
157 ClassName(attr=name, attr=name, ...)
158 The attributes are determined either by a class-level attribute,
159 '_kwarg_names', or by inspecting the instance __dict__.
163 type_name
= type(self
).__name
__
165 for arg
in self
._get
_args
():
166 arg_strings
.append(repr(arg
))
167 for name
, value
in self
._get
_kwargs
():
168 arg_strings
.append('%s=%r' % (name
, value
))
169 return '%s(%s)' % (type_name
, ', '.join(arg_strings
))
171 def _get_kwargs(self
):
172 return sorted(self
.__dict
__.items())
178 def _ensure_value(namespace
, name
, value
):
179 if getattr(namespace
, name
, None) is None:
180 setattr(namespace
, name
, value
)
181 return getattr(namespace
, name
)
188 class HelpFormatter(object):
189 """Formatter for generating usage messages and argument help strings.
191 Only the name of this class is considered a public API. All the methods
192 provided by the class are considered an implementation detail.
198 max_help_position
=24,
201 # default setting for width
204 width
= int(_os
.environ
['COLUMNS'])
205 except (KeyError, ValueError):
210 self
._indent
_increment
= indent_increment
211 self
._max
_help
_position
= max_help_position
214 self
._current
_indent
= 0
216 self
._action
_max
_length
= 0
218 self
._root
_section
= self
._Section
(self
, None)
219 self
._current
_section
= self
._root
_section
221 self
._whitespace
_matcher
= _re
.compile(r
'\s+')
222 self
._long
_break
_matcher
= _re
.compile(r
'\n\n\n+')
224 # ===============================
225 # Section and indentation methods
226 # ===============================
228 self
._current
_indent
+= self
._indent
_increment
232 self
._current
_indent
-= self
._indent
_increment
233 assert self
._current
_indent
>= 0, 'Indent decreased below 0.'
236 class _Section(object):
238 def __init__(self
, formatter
, parent
, heading
=None):
239 self
.formatter
= formatter
241 self
.heading
= heading
244 def format_help(self
):
245 # format the indented section
246 if self
.parent
is not None:
247 self
.formatter
._indent
()
248 join
= self
.formatter
._join
_parts
249 for func
, args
in self
.items
:
251 item_help
= join([func(*args
) for func
, args
in self
.items
])
252 if self
.parent
is not None:
253 self
.formatter
._dedent
()
255 # return nothing if the section was empty
259 # add the heading if the section was non-empty
260 if self
.heading
is not SUPPRESS
and self
.heading
is not None:
261 current_indent
= self
.formatter
._current
_indent
262 heading
= '%*s%s:\n' % (current_indent
, '', self
.heading
)
266 # join the section-initial newline, the heading and the help
267 return join(['\n', heading
, item_help
, '\n'])
269 def _add_item(self
, func
, args
):
270 self
._current
_section
.items
.append((func
, args
))
272 # ========================
273 # Message building methods
274 # ========================
275 def start_section(self
, heading
):
277 section
= self
._Section
(self
, self
._current
_section
, heading
)
278 self
._add
_item
(section
.format_help
, [])
279 self
._current
_section
= section
281 def end_section(self
):
282 self
._current
_section
= self
._current
_section
.parent
285 def add_text(self
, text
):
286 if text
is not SUPPRESS
and text
is not None:
287 self
._add
_item
(self
._format
_text
, [text
])
289 def add_usage(self
, usage
, actions
, groups
, prefix
=None):
290 if usage
is not SUPPRESS
:
291 args
= usage
, actions
, groups
, prefix
292 self
._add
_item
(self
._format
_usage
, args
)
294 def add_argument(self
, action
):
295 if action
.help is not SUPPRESS
:
297 # find all invocations
298 get_invocation
= self
._format
_action
_invocation
299 invocations
= [get_invocation(action
)]
300 for subaction
in self
._iter
_indented
_subactions
(action
):
301 invocations
.append(get_invocation(subaction
))
303 # update the maximum item length
304 invocation_length
= max([len(s
) for s
in invocations
])
305 action_length
= invocation_length
+ self
._current
_indent
306 self
._action
_max
_length
= max(self
._action
_max
_length
,
309 # add the item to the list
310 self
._add
_item
(self
._format
_action
, [action
])
312 def add_arguments(self
, actions
):
313 for action
in actions
:
314 self
.add_argument(action
)
316 # =======================
317 # Help-formatting methods
318 # =======================
319 def format_help(self
):
320 help = self
._root
_section
.format_help()
322 help = self
._long
_break
_matcher
.sub('\n\n', help)
323 help = help.strip('\n') + '\n'
326 def _join_parts(self
, part_strings
):
328 for part
in part_strings
329 if part
and part
is not SUPPRESS
])
331 def _format_usage(self
, usage
, actions
, groups
, prefix
):
333 prefix
= _('usage: ')
335 # if usage is specified, use that
336 if usage
is not None:
337 usage
= usage
% dict(prog
=self
._prog
)
339 # if no optionals or positionals are available, usage is just prog
340 elif usage
is None and not actions
:
341 usage
= '%(prog)s' % dict(prog
=self
._prog
)
343 # if optionals and positionals are available, calculate usage
345 prog
= '%(prog)s' % dict(prog
=self
._prog
)
347 # split optionals from positionals
350 for action
in actions
:
351 if action
.option_strings
:
352 optionals
.append(action
)
354 positionals
.append(action
)
356 # build full usage string
357 format
= self
._format
_actions
_usage
358 action_usage
= format(optionals
+ positionals
, groups
)
359 usage
= ' '.join([s
for s
in [prog
, action_usage
] if s
])
361 # wrap the usage parts if it's too long
362 text_width
= self
._width
- self
._current
_indent
363 if len(prefix
) + len(usage
) > text_width
:
365 # break usage into wrappable parts
366 part_regexp
= r
'\(.*?\)+|\[.*?\]+|\S+'
367 opt_usage
= format(optionals
, groups
)
368 pos_usage
= format(positionals
, groups
)
369 opt_parts
= _re
.findall(part_regexp
, opt_usage
)
370 pos_parts
= _re
.findall(part_regexp
, pos_usage
)
371 assert ' '.join(opt_parts
) == opt_usage
372 assert ' '.join(pos_parts
) == pos_usage
374 # helper for wrapping lines
375 def get_lines(parts
, indent
, prefix
=None):
378 if prefix
is not None:
379 line_len
= len(prefix
) - 1
381 line_len
= len(indent
) - 1
383 if line_len
+ 1 + len(part
) > text_width
:
384 lines
.append(indent
+ ' '.join(line
))
386 line_len
= len(indent
) - 1
388 line_len
+= len(part
) + 1
390 lines
.append(indent
+ ' '.join(line
))
391 if prefix
is not None:
392 lines
[0] = lines
[0][len(indent
):]
395 # if prog is short, follow it with optionals or positionals
396 if len(prefix
) + len(prog
) <= 0.75 * text_width
:
397 indent
= ' ' * (len(prefix
) + len(prog
) + 1)
399 lines
= get_lines([prog
] + opt_parts
, indent
, prefix
)
400 lines
.extend(get_lines(pos_parts
, indent
))
402 lines
= get_lines([prog
] + pos_parts
, indent
, prefix
)
406 # if prog is long, put it on its own line
408 indent
= ' ' * len(prefix
)
409 parts
= opt_parts
+ pos_parts
410 lines
= get_lines(parts
, indent
)
413 lines
.extend(get_lines(opt_parts
, indent
))
414 lines
.extend(get_lines(pos_parts
, indent
))
415 lines
= [prog
] + lines
417 # join lines into usage
418 usage
= '\n'.join(lines
)
420 # prefix with 'usage:'
421 return '%s%s\n\n' % (prefix
, usage
)
423 def _format_actions_usage(self
, actions
, groups
):
424 # find group indices and identify actions in groups
425 group_actions
= set()
429 start
= actions
.index(group
._group
_actions
[0])
433 end
= start
+ len(group
._group
_actions
)
434 if actions
[start
:end
] == group
._group
_actions
:
435 for action
in group
._group
_actions
:
436 group_actions
.add(action
)
437 if not group
.required
:
439 inserts
[start
] += ' ['
445 inserts
[start
] += ' ('
449 for i
in range(start
+ 1, end
):
452 # collect all actions format strings
454 for i
, action
in enumerate(actions
):
456 # suppressed arguments are marked with None
457 # remove | separators for suppressed arguments
458 if action
.help is SUPPRESS
:
460 if inserts
.get(i
) == '|':
462 elif inserts
.get(i
+ 1) == '|':
465 # produce all arg strings
466 elif not action
.option_strings
:
467 part
= self
._format
_args
(action
, action
.dest
)
469 # if it's in a group, strip the outer []
470 if action
in group_actions
:
471 if part
[0] == '[' and part
[-1] == ']':
474 # add the action string to the list
477 # produce the first way to invoke the option in brackets
479 option_string
= action
.option_strings
[0]
481 # if the Optional doesn't take a value, format is:
483 if action
.nargs
== 0:
484 part
= '%s' % option_string
486 # if the Optional takes a value, format is:
487 # -s ARGS or --long ARGS
489 default
= action
.dest
.upper()
490 args_string
= self
._format
_args
(action
, default
)
491 part
= '%s %s' % (option_string
, args_string
)
493 # make it look optional if it's not required or in a group
494 if not action
.required
and action
not in group_actions
:
497 # add the action string to the list
500 # insert things at the necessary indices
501 for i
in sorted(inserts
, reverse
=True):
502 parts
[i
:i
] = [inserts
[i
]]
504 # join all the action items with spaces
505 text
= ' '.join([item
for item
in parts
if item
is not None])
507 # clean up separators for mutually exclusive groups
510 text
= _re
.sub(r
'(%s) ' % open, r
'\1', text
)
511 text
= _re
.sub(r
' (%s)' % close
, r
'\1', text
)
512 text
= _re
.sub(r
'%s *%s' % (open, close
), r
'', text
)
513 text
= _re
.sub(r
'\(([^|]*)\)', r
'\1', text
)
519 def _format_text(self
, text
):
520 if '%(prog)' in text
:
521 text
= text
% dict(prog
=self
._prog
)
522 text_width
= self
._width
- self
._current
_indent
523 indent
= ' ' * self
._current
_indent
524 return self
._fill
_text
(text
, text_width
, indent
) + '\n\n'
526 def _format_action(self
, action
):
527 # determine the required width and the entry label
528 help_position
= min(self
._action
_max
_length
+ 2,
529 self
._max
_help
_position
)
530 help_width
= self
._width
- help_position
531 action_width
= help_position
- self
._current
_indent
- 2
532 action_header
= self
._format
_action
_invocation
(action
)
534 # ho nelp; start on same line and add a final newline
536 tup
= self
._current
_indent
, '', action_header
537 action_header
= '%*s%s\n' % tup
539 # short action name; start on the same line and pad two spaces
540 elif len(action_header
) <= action_width
:
541 tup
= self
._current
_indent
, '', action_width
, action_header
542 action_header
= '%*s%-*s ' % tup
545 # long action name; start on the next line
547 tup
= self
._current
_indent
, '', action_header
548 action_header
= '%*s%s\n' % tup
549 indent_first
= help_position
551 # collect the pieces of the action help
552 parts
= [action_header
]
554 # if there was help for the action, add lines of help text
556 help_text
= self
._expand
_help
(action
)
557 help_lines
= self
._split
_lines
(help_text
, help_width
)
558 parts
.append('%*s%s\n' % (indent_first
, '', help_lines
[0]))
559 for line
in help_lines
[1:]:
560 parts
.append('%*s%s\n' % (help_position
, '', line
))
562 # or add a newline if the description doesn't end with one
563 elif not action_header
.endswith('\n'):
566 # if there are any sub-actions, add their help as well
567 for subaction
in self
._iter
_indented
_subactions
(action
):
568 parts
.append(self
._format
_action
(subaction
))
570 # return a single string
571 return self
._join
_parts
(parts
)
573 def _format_action_invocation(self
, action
):
574 if not action
.option_strings
:
575 metavar
, = self
._metavar
_formatter
(action
, action
.dest
)(1)
581 # if the Optional doesn't take a value, format is:
583 if action
.nargs
== 0:
584 parts
.extend(action
.option_strings
)
586 # if the Optional takes a value, format is:
587 # -s ARGS, --long ARGS
589 default
= action
.dest
.upper()
590 args_string
= self
._format
_args
(action
, default
)
591 for option_string
in action
.option_strings
:
592 parts
.append('%s %s' % (option_string
, args_string
))
594 return ', '.join(parts
)
596 def _metavar_formatter(self
, action
, default_metavar
):
597 if action
.metavar
is not None:
598 result
= action
.metavar
599 elif action
.choices
is not None:
600 choice_strs
= [str(choice
) for choice
in action
.choices
]
601 result
= '{%s}' % ','.join(choice_strs
)
603 result
= default_metavar
605 def format(tuple_size
):
606 if isinstance(result
, tuple):
609 return (result
, ) * tuple_size
612 def _format_args(self
, action
, default_metavar
):
613 get_metavar
= self
._metavar
_formatter
(action
, default_metavar
)
614 if action
.nargs
is None:
615 result
= '%s' % get_metavar(1)
616 elif action
.nargs
== OPTIONAL
:
617 result
= '[%s]' % get_metavar(1)
618 elif action
.nargs
== ZERO_OR_MORE
:
619 result
= '[%s [%s ...]]' % get_metavar(2)
620 elif action
.nargs
== ONE_OR_MORE
:
621 result
= '%s [%s ...]' % get_metavar(2)
622 elif action
.nargs
== REMAINDER
:
624 elif action
.nargs
== PARSER
:
625 result
= '%s ...' % get_metavar(1)
627 formats
= ['%s' for _
in range(action
.nargs
)]
628 result
= ' '.join(formats
) % get_metavar(action
.nargs
)
631 def _expand_help(self
, action
):
632 params
= dict(vars(action
), prog
=self
._prog
)
633 for name
in list(params
):
634 if params
[name
] is SUPPRESS
:
636 for name
in list(params
):
637 if hasattr(params
[name
], '__name__'):
638 params
[name
] = params
[name
].__name
__
639 if params
.get('choices') is not None:
640 choices_str
= ', '.join([str(c
) for c
in params
['choices']])
641 params
['choices'] = choices_str
642 return self
._get
_help
_string
(action
) % params
644 def _iter_indented_subactions(self
, action
):
646 get_subactions
= action
._get
_subactions
647 except AttributeError:
651 for subaction
in get_subactions():
655 def _split_lines(self
, text
, width
):
656 text
= self
._whitespace
_matcher
.sub(' ', text
).strip()
657 return _textwrap
.wrap(text
, width
)
659 def _fill_text(self
, text
, width
, indent
):
660 text
= self
._whitespace
_matcher
.sub(' ', text
).strip()
661 return _textwrap
.fill(text
, width
, initial_indent
=indent
,
662 subsequent_indent
=indent
)
664 def _get_help_string(self
, action
):
668 class RawDescriptionHelpFormatter(HelpFormatter
):
669 """Help message formatter which retains any formatting in descriptions.
671 Only the name of this class is considered a public API. All the methods
672 provided by the class are considered an implementation detail.
675 def _fill_text(self
, text
, width
, indent
):
676 return ''.join([indent
+ line
for line
in text
.splitlines(True)])
679 class RawTextHelpFormatter(RawDescriptionHelpFormatter
):
680 """Help message formatter which retains formatting of all help text.
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.
686 def _split_lines(self
, text
, width
):
687 return text
.splitlines()
690 class ArgumentDefaultsHelpFormatter(HelpFormatter
):
691 """Help message formatter which adds default values to argument help.
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.
697 def _get_help_string(self
, action
):
699 if '%(default)' not in action
.help:
700 if action
.default
is not SUPPRESS
:
701 defaulting_nargs
= [OPTIONAL
, ZERO_OR_MORE
]
702 if action
.option_strings
or action
.nargs
in defaulting_nargs
:
703 help += ' (default: %(default)s)'
707 # =====================
708 # Options and Arguments
709 # =====================
711 def _get_action_name(argument
):
714 elif argument
.option_strings
:
715 return '/'.join(argument
.option_strings
)
716 elif argument
.metavar
not in (None, SUPPRESS
):
717 return argument
.metavar
718 elif argument
.dest
not in (None, SUPPRESS
):
724 class ArgumentError(Exception):
725 """An error from creating or using an argument (optional or positional).
727 The string value of this exception is the message, augmented with
728 information about the argument that caused it.
731 def __init__(self
, argument
, message
):
732 self
.argument_name
= _get_action_name(argument
)
733 self
.message
= message
736 if self
.argument_name
is None:
737 format
= '%(message)s'
739 format
= 'argument %(argument_name)s: %(message)s'
740 return format
% dict(message
=self
.message
,
741 argument_name
=self
.argument_name
)
744 class ArgumentTypeError(Exception):
745 """An error from trying to convert a command line string to a type."""
753 class Action(_AttributeHolder
):
754 """Information about how to convert command line strings to Python objects.
756 Action objects are used by an ArgumentParser to represent the information
757 needed to parse a single argument from one or more strings from the
758 command line. The keyword arguments to the Action constructor are also
759 all attributes of Action instances.
763 - option_strings -- A list of command-line option strings which
764 should be associated with this action.
766 - dest -- The name of the attribute to hold the created object(s)
768 - nargs -- The number of command-line arguments that should be
769 consumed. By default, one argument will be consumed and a single
770 value will be produced. Other values include:
771 - N (an integer) consumes N arguments (and produces a list)
772 - '?' consumes zero or one arguments
773 - '*' consumes zero or more arguments (and produces a list)
774 - '+' consumes one or more arguments (and produces a list)
775 Note that the difference between the default and nargs=1 is that
776 with the default, a single value will be produced, while with
777 nargs=1, a list containing a single value will be produced.
779 - const -- The value to be produced if the option is specified and the
780 option uses an action that takes no values.
782 - default -- The value to be produced if the option is not specified.
784 - type -- The type which the command-line arguments should be converted
785 to, should be one of 'string', 'int', 'float', 'complex' or a
786 callable object that accepts a single string argument. If None,
789 - choices -- A container of values that should be allowed. If not None,
790 after a command-line argument has been converted to the appropriate
791 type, an exception will be raised if it is not a member of this
794 - required -- True if the action must always be specified at the
795 command line. This is only meaningful for optional command-line
798 - help -- The help string describing the argument.
800 - metavar -- The name to be used for the option's argument with the
801 help string. If None, the 'dest' value will be used as the name.
815 self
.option_strings
= option_strings
819 self
.default
= default
821 self
.choices
= choices
822 self
.required
= required
824 self
.metavar
= metavar
826 def _get_kwargs(self
):
838 return [(name
, getattr(self
, name
)) for name
in names
]
840 def __call__(self
, parser
, namespace
, values
, option_string
=None):
841 raise NotImplementedError(_('.__call__() not defined'))
844 class _StoreAction(Action
):
858 raise ValueError('nargs for store actions must be > 0; if you '
859 'have nothing to store, actions such as store '
860 'true or store const may be more appropriate')
861 if const
is not None and nargs
!= OPTIONAL
:
862 raise ValueError('nargs must be %r to supply const' % OPTIONAL
)
863 super(_StoreAction
, self
).__init
__(
864 option_strings
=option_strings
,
875 def __call__(self
, parser
, namespace
, values
, option_string
=None):
876 setattr(namespace
, self
.dest
, values
)
879 class _StoreConstAction(Action
):
889 super(_StoreConstAction
, self
).__init
__(
890 option_strings
=option_strings
,
898 def __call__(self
, parser
, namespace
, values
, option_string
=None):
899 setattr(namespace
, self
.dest
, self
.const
)
902 class _StoreTrueAction(_StoreConstAction
):
910 super(_StoreTrueAction
, self
).__init
__(
911 option_strings
=option_strings
,
919 class _StoreFalseAction(_StoreConstAction
):
927 super(_StoreFalseAction
, self
).__init
__(
928 option_strings
=option_strings
,
936 class _AppendAction(Action
):
950 raise ValueError('nargs for append actions must be > 0; if arg '
951 'strings are not supplying the value to append, '
952 'the append const action may be more appropriate')
953 if const
is not None and nargs
!= OPTIONAL
:
954 raise ValueError('nargs must be %r to supply const' % OPTIONAL
)
955 super(_AppendAction
, self
).__init
__(
956 option_strings
=option_strings
,
967 def __call__(self
, parser
, namespace
, values
, option_string
=None):
968 items
= _copy
.copy(_ensure_value(namespace
, self
.dest
, []))
970 setattr(namespace
, self
.dest
, items
)
973 class _AppendConstAction(Action
):
983 super(_AppendConstAction
, self
).__init
__(
984 option_strings
=option_strings
,
993 def __call__(self
, parser
, namespace
, values
, option_string
=None):
994 items
= _copy
.copy(_ensure_value(namespace
, self
.dest
, []))
995 items
.append(self
.const
)
996 setattr(namespace
, self
.dest
, items
)
999 class _CountAction(Action
):
1007 super(_CountAction
, self
).__init
__(
1008 option_strings
=option_strings
,
1015 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1016 new_count
= _ensure_value(namespace
, self
.dest
, 0) + 1
1017 setattr(namespace
, self
.dest
, new_count
)
1020 class _HelpAction(Action
):
1027 super(_HelpAction
, self
).__init
__(
1028 option_strings
=option_strings
,
1034 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1039 class _VersionAction(Action
):
1046 help="show program's version number and exit"):
1047 super(_VersionAction
, self
).__init
__(
1048 option_strings
=option_strings
,
1053 self
.version
= version
1055 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1056 version
= self
.version
1058 version
= parser
.version
1059 formatter
= parser
._get
_formatter
()
1060 formatter
.add_text(version
)
1061 parser
.exit(message
=formatter
.format_help())
1064 class _SubParsersAction(Action
):
1066 class _ChoicesPseudoAction(Action
):
1068 def __init__(self
, name
, aliases
, help):
1069 metavar
= dest
= name
1071 metavar
+= ' (%s)' % ', '.join(aliases
)
1072 sup
= super(_SubParsersAction
._ChoicesPseudoAction
, self
)
1073 sup
.__init
__(option_strings
=[], dest
=dest
, help=help,
1084 self
._prog
_prefix
= prog
1085 self
._parser
_class
= parser_class
1086 self
._name
_parser
_map
= {}
1087 self
._choices
_actions
= []
1089 super(_SubParsersAction
, self
).__init
__(
1090 option_strings
=option_strings
,
1093 choices
=self
._name
_parser
_map
,
1097 def add_parser(self
, name
, **kwargs
):
1098 # set prog from the existing prefix
1099 if kwargs
.get('prog') is None:
1100 kwargs
['prog'] = '%s %s' % (self
._prog
_prefix
, name
)
1102 aliases
= kwargs
.pop('aliases', ())
1104 # create a pseudo-action to hold the choice help
1105 if 'help' in kwargs
:
1106 help = kwargs
.pop('help')
1107 choice_action
= self
._ChoicesPseudoAction
(name
, aliases
, help)
1108 self
._choices
_actions
.append(choice_action
)
1110 # create the parser and add it to the map
1111 parser
= self
._parser
_class
(**kwargs
)
1112 self
._name
_parser
_map
[name
] = parser
1114 # make parser available under aliases also
1115 for alias
in aliases
:
1116 self
._name
_parser
_map
[alias
] = parser
1120 def _get_subactions(self
):
1121 return self
._choices
_actions
1123 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1124 parser_name
= values
[0]
1125 arg_strings
= values
[1:]
1127 # set the parser name if requested
1128 if self
.dest
is not SUPPRESS
:
1129 setattr(namespace
, self
.dest
, parser_name
)
1133 parser
= self
._name
_parser
_map
[parser_name
]
1135 tup
= parser_name
, ', '.join(self
._name
_parser
_map
)
1136 msg
= _('unknown parser %r (choices: %s)' % tup
)
1137 raise ArgumentError(self
, msg
)
1139 # parse all the remaining options into the namespace
1140 # store any unrecognized options on the object, so that the top
1141 # level parser can decide what to do with them
1142 namespace
, arg_strings
= parser
.parse_known_args(arg_strings
, namespace
)
1144 vars(namespace
).setdefault(_UNRECOGNIZED_ARGS_ATTR
, [])
1145 getattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
).extend(arg_strings
)
1152 class FileType(object):
1153 """Factory for creating file object types
1155 Instances of FileType are typically passed as type= arguments to the
1156 ArgumentParser add_argument() method.
1159 - mode -- A string indicating how the file is to be opened. Accepts the
1160 same values as the builtin open() function.
1161 - bufsize -- The file's desired buffer size. Accepts the same values as
1162 the builtin open() function.
1165 def __init__(self
, mode
='r', bufsize
=None):
1167 self
._bufsize
= bufsize
1169 def __call__(self
, string
):
1170 # the special argument "-" means sys.std{in,out}
1172 if 'r' in self
._mode
:
1174 elif 'w' in self
._mode
:
1177 msg
= _('argument "-" with mode %r' % self
._mode
)
1178 raise ValueError(msg
)
1181 # all other arguments are used as file names
1183 return open(string
, self
._mode
, self
._bufsize
)
1185 return open(string
, self
._mode
)
1187 err
= _sys
.exc_info()[1]
1188 message
= _("can't open '%s': %s")
1189 raise ArgumentTypeError(message
% (string
, err
))
1192 args
= [self
._mode
, self
._bufsize
]
1193 args_str
= ', '.join([repr(arg
) for arg
in args
if arg
is not None])
1194 return '%s(%s)' % (type(self
).__name
__, args_str
)
1196 # ===========================
1197 # Optional and Positional Parsing
1198 # ===========================
1200 class Namespace(_AttributeHolder
):
1201 """Simple object for storing attributes.
1203 Implements equality by attribute names and values, and provides a simple
1204 string representation.
1207 def __init__(self
, **kwargs
):
1209 setattr(self
, name
, kwargs
[name
])
1213 def __eq__(self
, other
):
1214 return vars(self
) == vars(other
)
1216 def __ne__(self
, other
):
1217 return not (self
== other
)
1219 def __contains__(self
, key
):
1220 return key
in self
.__dict
__
1223 class _ActionsContainer(object):
1230 super(_ActionsContainer
, self
).__init
__()
1232 self
.description
= description
1233 self
.argument_default
= argument_default
1234 self
.prefix_chars
= prefix_chars
1235 self
.conflict_handler
= conflict_handler
1238 self
._registries
= {}
1241 self
.register('action', None, _StoreAction
)
1242 self
.register('action', 'store', _StoreAction
)
1243 self
.register('action', 'store_const', _StoreConstAction
)
1244 self
.register('action', 'store_true', _StoreTrueAction
)
1245 self
.register('action', 'store_false', _StoreFalseAction
)
1246 self
.register('action', 'append', _AppendAction
)
1247 self
.register('action', 'append_const', _AppendConstAction
)
1248 self
.register('action', 'count', _CountAction
)
1249 self
.register('action', 'help', _HelpAction
)
1250 self
.register('action', 'version', _VersionAction
)
1251 self
.register('action', 'parsers', _SubParsersAction
)
1253 # raise an exception if the conflict handler is invalid
1258 self
._option
_string
_actions
= {}
1261 self
._action
_groups
= []
1262 self
._mutually
_exclusive
_groups
= []
1267 # determines whether an "option" looks like a negative number
1268 self
._negative
_number
_matcher
= _re
.compile(r
'^-\d+$|^-\d*\.\d+$')
1270 # whether or not there are any optionals that look like negative
1271 # numbers -- uses a list so it can be shared and edited
1272 self
._has
_negative
_number
_optionals
= []
1274 # ====================
1275 # Registration methods
1276 # ====================
1277 def register(self
, registry_name
, value
, object):
1278 registry
= self
._registries
.setdefault(registry_name
, {})
1279 registry
[value
] = object
1281 def _registry_get(self
, registry_name
, value
, default
=None):
1282 return self
._registries
[registry_name
].get(value
, default
)
1284 # ==================================
1285 # Namespace default accessor methods
1286 # ==================================
1287 def set_defaults(self
, **kwargs
):
1288 self
._defaults
.update(kwargs
)
1290 # if these defaults match any existing arguments, replace
1291 # the previous default on the object with the new one
1292 for action
in self
._actions
:
1293 if action
.dest
in kwargs
:
1294 action
.default
= kwargs
[action
.dest
]
1296 def get_default(self
, dest
):
1297 for action
in self
._actions
:
1298 if action
.dest
== dest
and action
.default
is not None:
1299 return action
.default
1300 return self
._defaults
.get(dest
, None)
1303 # =======================
1304 # Adding argument actions
1305 # =======================
1306 def add_argument(self
, *args
, **kwargs
):
1308 add_argument(dest, ..., name=value, ...)
1309 add_argument(option_string, option_string, ..., name=value, ...)
1312 # if no positional args are supplied or only one is supplied and
1313 # it doesn't look like an option string, parse a positional
1315 chars
= self
.prefix_chars
1316 if not args
or len(args
) == 1 and args
[0][0] not in chars
:
1317 if args
and 'dest' in kwargs
:
1318 raise ValueError('dest supplied twice for positional argument')
1319 kwargs
= self
._get
_positional
_kwargs
(*args
, **kwargs
)
1321 # otherwise, we're adding an optional argument
1323 kwargs
= self
._get
_optional
_kwargs
(*args
, **kwargs
)
1325 # if no default was supplied, use the parser-level default
1326 if 'default' not in kwargs
:
1327 dest
= kwargs
['dest']
1328 if dest
in self
._defaults
:
1329 kwargs
['default'] = self
._defaults
[dest
]
1330 elif self
.argument_default
is not None:
1331 kwargs
['default'] = self
.argument_default
1333 # create the action object, and add it to the parser
1334 action_class
= self
._pop
_action
_class
(kwargs
)
1335 if not _callable(action_class
):
1336 raise ValueError('unknown action "%s"' % action_class
)
1337 action
= action_class(**kwargs
)
1339 # raise an error if the action type is not callable
1340 type_func
= self
._registry
_get
('type', action
.type, action
.type)
1341 if not _callable(type_func
):
1342 raise ValueError('%r is not callable' % type_func
)
1344 return self
._add
_action
(action
)
1346 def add_argument_group(self
, *args
, **kwargs
):
1347 group
= _ArgumentGroup(self
, *args
, **kwargs
)
1348 self
._action
_groups
.append(group
)
1351 def add_mutually_exclusive_group(self
, **kwargs
):
1352 group
= _MutuallyExclusiveGroup(self
, **kwargs
)
1353 self
._mutually
_exclusive
_groups
.append(group
)
1356 def _add_action(self
, action
):
1357 # resolve any conflicts
1358 self
._check
_conflict
(action
)
1360 # add to actions list
1361 self
._actions
.append(action
)
1362 action
.container
= self
1364 # index the action by any option strings it has
1365 for option_string
in action
.option_strings
:
1366 self
._option
_string
_actions
[option_string
] = action
1368 # set the flag if any option strings look like negative numbers
1369 for option_string
in action
.option_strings
:
1370 if self
._negative
_number
_matcher
.match(option_string
):
1371 if not self
._has
_negative
_number
_optionals
:
1372 self
._has
_negative
_number
_optionals
.append(True)
1374 # return the created action
1377 def _remove_action(self
, action
):
1378 self
._actions
.remove(action
)
1380 def _add_container_actions(self
, container
):
1381 # collect groups by titles
1382 title_group_map
= {}
1383 for group
in self
._action
_groups
:
1384 if group
.title
in title_group_map
:
1385 msg
= _('cannot merge actions - two groups are named %r')
1386 raise ValueError(msg
% (group
.title
))
1387 title_group_map
[group
.title
] = group
1389 # map each action to its group
1391 for group
in container
._action
_groups
:
1393 # if a group with the title exists, use that, otherwise
1394 # create a new group matching the container's group
1395 if group
.title
not in title_group_map
:
1396 title_group_map
[group
.title
] = self
.add_argument_group(
1398 description
=group
.description
,
1399 conflict_handler
=group
.conflict_handler
)
1401 # map the actions to their new group
1402 for action
in group
._group
_actions
:
1403 group_map
[action
] = title_group_map
[group
.title
]
1405 # add container's mutually exclusive groups
1406 # NOTE: if add_mutually_exclusive_group ever gains title= and
1407 # description= then this code will need to be expanded as above
1408 for group
in container
._mutually
_exclusive
_groups
:
1409 mutex_group
= self
.add_mutually_exclusive_group(
1410 required
=group
.required
)
1412 # map the actions to their new mutex group
1413 for action
in group
._group
_actions
:
1414 group_map
[action
] = mutex_group
1416 # add all actions to this container or their group
1417 for action
in container
._actions
:
1418 group_map
.get(action
, self
)._add
_action
(action
)
1420 def _get_positional_kwargs(self
, dest
, **kwargs
):
1421 # make sure required is not specified
1422 if 'required' in kwargs
:
1423 msg
= _("'required' is an invalid argument for positionals")
1424 raise TypeError(msg
)
1426 # mark positional arguments as required if at least one is
1428 if kwargs
.get('nargs') not in [OPTIONAL
, ZERO_OR_MORE
]:
1429 kwargs
['required'] = True
1430 if kwargs
.get('nargs') == ZERO_OR_MORE
and 'default' not in kwargs
:
1431 kwargs
['required'] = True
1433 # return the keyword arguments with no option strings
1434 return dict(kwargs
, dest
=dest
, option_strings
=[])
1436 def _get_optional_kwargs(self
, *args
, **kwargs
):
1437 # determine short and long option strings
1439 long_option_strings
= []
1440 for option_string
in args
:
1441 # error on strings that don't start with an appropriate prefix
1442 if not option_string
[0] in self
.prefix_chars
:
1443 msg
= _('invalid option string %r: '
1444 'must start with a character %r')
1445 tup
= option_string
, self
.prefix_chars
1446 raise ValueError(msg
% tup
)
1448 # strings starting with two prefix characters are long options
1449 option_strings
.append(option_string
)
1450 if option_string
[0] in self
.prefix_chars
:
1451 if len(option_string
) > 1:
1452 if option_string
[1] in self
.prefix_chars
:
1453 long_option_strings
.append(option_string
)
1455 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1456 dest
= kwargs
.pop('dest', None)
1458 if long_option_strings
:
1459 dest_option_string
= long_option_strings
[0]
1461 dest_option_string
= option_strings
[0]
1462 dest
= dest_option_string
.lstrip(self
.prefix_chars
)
1464 msg
= _('dest= is required for options like %r')
1465 raise ValueError(msg
% option_string
)
1466 dest
= dest
.replace('-', '_')
1468 # return the updated keyword arguments
1469 return dict(kwargs
, dest
=dest
, option_strings
=option_strings
)
1471 def _pop_action_class(self
, kwargs
, default
=None):
1472 action
= kwargs
.pop('action', default
)
1473 return self
._registry
_get
('action', action
, action
)
1475 def _get_handler(self
):
1476 # determine function from conflict handler string
1477 handler_func_name
= '_handle_conflict_%s' % self
.conflict_handler
1479 return getattr(self
, handler_func_name
)
1480 except AttributeError:
1481 msg
= _('invalid conflict_resolution value: %r')
1482 raise ValueError(msg
% self
.conflict_handler
)
1484 def _check_conflict(self
, action
):
1486 # find all options that conflict with this option
1487 confl_optionals
= []
1488 for option_string
in action
.option_strings
:
1489 if option_string
in self
._option
_string
_actions
:
1490 confl_optional
= self
._option
_string
_actions
[option_string
]
1491 confl_optionals
.append((option_string
, confl_optional
))
1493 # resolve any conflicts
1495 conflict_handler
= self
._get
_handler
()
1496 conflict_handler(action
, confl_optionals
)
1498 def _handle_conflict_error(self
, action
, conflicting_actions
):
1499 message
= _('conflicting option string(s): %s')
1500 conflict_string
= ', '.join([option_string
1501 for option_string
, action
1502 in conflicting_actions
])
1503 raise ArgumentError(action
, message
% conflict_string
)
1505 def _handle_conflict_resolve(self
, action
, conflicting_actions
):
1507 # remove all conflicting options
1508 for option_string
, action
in conflicting_actions
:
1510 # remove the conflicting option
1511 action
.option_strings
.remove(option_string
)
1512 self
._option
_string
_actions
.pop(option_string
, None)
1514 # if the option now has no option string, remove it from the
1515 # container holding it
1516 if not action
.option_strings
:
1517 action
.container
._remove
_action
(action
)
1520 class _ArgumentGroup(_ActionsContainer
):
1522 def __init__(self
, container
, title
=None, description
=None, **kwargs
):
1523 # add any missing keyword arguments by checking the container
1524 update
= kwargs
.setdefault
1525 update('conflict_handler', container
.conflict_handler
)
1526 update('prefix_chars', container
.prefix_chars
)
1527 update('argument_default', container
.argument_default
)
1528 super_init
= super(_ArgumentGroup
, self
).__init
__
1529 super_init(description
=description
, **kwargs
)
1533 self
._group
_actions
= []
1535 # share most attributes with the container
1536 self
._registries
= container
._registries
1537 self
._actions
= container
._actions
1538 self
._option
_string
_actions
= container
._option
_string
_actions
1539 self
._defaults
= container
._defaults
1540 self
._has
_negative
_number
_optionals
= \
1541 container
._has
_negative
_number
_optionals
1543 def _add_action(self
, action
):
1544 action
= super(_ArgumentGroup
, self
)._add
_action
(action
)
1545 self
._group
_actions
.append(action
)
1548 def _remove_action(self
, action
):
1549 super(_ArgumentGroup
, self
)._remove
_action
(action
)
1550 self
._group
_actions
.remove(action
)
1553 class _MutuallyExclusiveGroup(_ArgumentGroup
):
1555 def __init__(self
, container
, required
=False):
1556 super(_MutuallyExclusiveGroup
, self
).__init
__(container
)
1557 self
.required
= required
1558 self
._container
= container
1560 def _add_action(self
, action
):
1562 msg
= _('mutually exclusive arguments must be optional')
1563 raise ValueError(msg
)
1564 action
= self
._container
._add
_action
(action
)
1565 self
._group
_actions
.append(action
)
1568 def _remove_action(self
, action
):
1569 self
._container
._remove
_action
(action
)
1570 self
._group
_actions
.remove(action
)
1573 class ArgumentParser(_AttributeHolder
, _ActionsContainer
):
1574 """Object for parsing command line strings into Python objects.
1577 - prog -- The name of the program (default: sys.argv[0])
1578 - usage -- A usage message (default: auto-generated from arguments)
1579 - description -- A description of what the program does
1580 - epilog -- Text following the argument descriptions
1581 - parents -- Parsers whose arguments should be copied into this one
1582 - formatter_class -- HelpFormatter class for printing help messages
1583 - prefix_chars -- Characters that prefix optional arguments
1584 - fromfile_prefix_chars -- Characters that prefix files containing
1585 additional arguments
1586 - argument_default -- The default value for all arguments
1587 - conflict_handler -- String indicating how to handle conflicts
1588 - add_help -- Add a -h/-help option
1598 formatter_class
=HelpFormatter
,
1600 fromfile_prefix_chars
=None,
1601 argument_default
=None,
1602 conflict_handler
='error',
1605 if version
is not None:
1608 """The "version" argument to ArgumentParser is deprecated. """
1610 """"add_argument(..., action='version', version="N", ...)" """
1611 """instead""", DeprecationWarning)
1613 superinit
= super(ArgumentParser
, self
).__init
__
1614 superinit(description
=description
,
1615 prefix_chars
=prefix_chars
,
1616 argument_default
=argument_default
,
1617 conflict_handler
=conflict_handler
)
1619 # default setting for prog
1621 prog
= _os
.path
.basename(_sys
.argv
[0])
1625 self
.epilog
= epilog
1626 self
.version
= version
1627 self
.formatter_class
= formatter_class
1628 self
.fromfile_prefix_chars
= fromfile_prefix_chars
1629 self
.add_help
= add_help
1631 add_group
= self
.add_argument_group
1632 self
._positionals
= add_group(_('positional arguments'))
1633 self
._optionals
= add_group(_('optional arguments'))
1634 self
._subparsers
= None
1637 def identity(string
):
1639 self
.register('type', None, identity
)
1641 # add help and version arguments if necessary
1642 # (using explicit default to override global argument_default)
1643 if '-' in prefix_chars
:
1644 default_prefix
= '-'
1646 default_prefix
= prefix_chars
[0]
1649 default_prefix
+'h', default_prefix
*2+'help',
1650 action
='help', default
=SUPPRESS
,
1651 help=_('show this help message and exit'))
1654 default_prefix
+'v', default_prefix
*2+'version',
1655 action
='version', default
=SUPPRESS
,
1656 version
=self
.version
,
1657 help=_("show program's version number and exit"))
1659 # add parent arguments and defaults
1660 for parent
in parents
:
1661 self
._add
_container
_actions
(parent
)
1663 defaults
= parent
._defaults
1664 except AttributeError:
1667 self
._defaults
.update(defaults
)
1669 # =======================
1670 # Pretty __repr__ methods
1671 # =======================
1672 def _get_kwargs(self
):
1682 return [(name
, getattr(self
, name
)) for name
in names
]
1684 # ==================================
1685 # Optional/Positional adding methods
1686 # ==================================
1687 def add_subparsers(self
, **kwargs
):
1688 if self
._subparsers
is not None:
1689 self
.error(_('cannot have multiple subparser arguments'))
1691 # add the parser class to the arguments if it's not present
1692 kwargs
.setdefault('parser_class', type(self
))
1694 if 'title' in kwargs
or 'description' in kwargs
:
1695 title
= _(kwargs
.pop('title', 'subcommands'))
1696 description
= _(kwargs
.pop('description', None))
1697 self
._subparsers
= self
.add_argument_group(title
, description
)
1699 self
._subparsers
= self
._positionals
1701 # prog defaults to the usage message of this parser, skipping
1702 # optional arguments and with no "usage:" prefix
1703 if kwargs
.get('prog') is None:
1704 formatter
= self
._get
_formatter
()
1705 positionals
= self
._get
_positional
_actions
()
1706 groups
= self
._mutually
_exclusive
_groups
1707 formatter
.add_usage(self
.usage
, positionals
, groups
, '')
1708 kwargs
['prog'] = formatter
.format_help().strip()
1710 # create the parsers action and add it to the positionals list
1711 parsers_class
= self
._pop
_action
_class
(kwargs
, 'parsers')
1712 action
= parsers_class(option_strings
=[], **kwargs
)
1713 self
._subparsers
._add
_action
(action
)
1715 # return the created parsers action
1718 def _add_action(self
, action
):
1719 if action
.option_strings
:
1720 self
._optionals
._add
_action
(action
)
1722 self
._positionals
._add
_action
(action
)
1725 def _get_optional_actions(self
):
1727 for action
in self
._actions
1728 if action
.option_strings
]
1730 def _get_positional_actions(self
):
1732 for action
in self
._actions
1733 if not action
.option_strings
]
1735 # =====================================
1736 # Command line argument parsing methods
1737 # =====================================
1738 def parse_args(self
, args
=None, namespace
=None):
1739 args
, argv
= self
.parse_known_args(args
, namespace
)
1741 msg
= _('unrecognized arguments: %s')
1742 self
.error(msg
% ' '.join(argv
))
1745 def parse_known_args(self
, args
=None, namespace
=None):
1746 # args default to the system args
1748 args
= _sys
.argv
[1:]
1750 # default Namespace built from parser defaults
1751 if namespace
is None:
1752 namespace
= Namespace()
1754 # add any action defaults that aren't present
1755 for action
in self
._actions
:
1756 if action
.dest
is not SUPPRESS
:
1757 if not hasattr(namespace
, action
.dest
):
1758 if action
.default
is not SUPPRESS
:
1759 setattr(namespace
, action
.dest
, action
.default
)
1761 # add any parser defaults that aren't present
1762 for dest
in self
._defaults
:
1763 if not hasattr(namespace
, dest
):
1764 setattr(namespace
, dest
, self
._defaults
[dest
])
1766 # parse the arguments and exit if there are any errors
1768 namespace
, args
= self
._parse
_known
_args
(args
, namespace
)
1769 if hasattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
):
1770 args
.extend(getattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
))
1771 delattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
)
1772 return namespace
, args
1773 except ArgumentError
:
1774 err
= _sys
.exc_info()[1]
1775 self
.error(str(err
))
1777 def _parse_known_args(self
, arg_strings
, namespace
):
1778 # replace arg strings that are file references
1779 if self
.fromfile_prefix_chars
is not None:
1780 arg_strings
= self
._read
_args
_from
_files
(arg_strings
)
1782 # map all mutually exclusive arguments to the other arguments
1783 # they can't occur with
1784 action_conflicts
= {}
1785 for mutex_group
in self
._mutually
_exclusive
_groups
:
1786 group_actions
= mutex_group
._group
_actions
1787 for i
, mutex_action
in enumerate(mutex_group
._group
_actions
):
1788 conflicts
= action_conflicts
.setdefault(mutex_action
, [])
1789 conflicts
.extend(group_actions
[:i
])
1790 conflicts
.extend(group_actions
[i
+ 1:])
1792 # find all option indices, and determine the arg_string_pattern
1793 # which has an 'O' if there is an option at an index,
1794 # an 'A' if there is an argument, or a '-' if there is a '--'
1795 option_string_indices
= {}
1796 arg_string_pattern_parts
= []
1797 arg_strings_iter
= iter(arg_strings
)
1798 for i
, arg_string
in enumerate(arg_strings_iter
):
1800 # all args after -- are non-options
1801 if arg_string
== '--':
1802 arg_string_pattern_parts
.append('-')
1803 for arg_string
in arg_strings_iter
:
1804 arg_string_pattern_parts
.append('A')
1806 # otherwise, add the arg to the arg strings
1807 # and note the index if it was an option
1809 option_tuple
= self
._parse
_optional
(arg_string
)
1810 if option_tuple
is None:
1813 option_string_indices
[i
] = option_tuple
1815 arg_string_pattern_parts
.append(pattern
)
1817 # join the pieces together to form the pattern
1818 arg_strings_pattern
= ''.join(arg_string_pattern_parts
)
1820 # converts arg strings to the appropriate and then takes the action
1821 seen_actions
= set()
1822 seen_non_default_actions
= set()
1824 def take_action(action
, argument_strings
, option_string
=None):
1825 seen_actions
.add(action
)
1826 argument_values
= self
._get
_values
(action
, argument_strings
)
1828 # error if this argument is not allowed with other previously
1829 # seen arguments, assuming that actions that use the default
1830 # value don't really count as "present"
1831 if argument_values
is not action
.default
:
1832 seen_non_default_actions
.add(action
)
1833 for conflict_action
in action_conflicts
.get(action
, []):
1834 if conflict_action
in seen_non_default_actions
:
1835 msg
= _('not allowed with argument %s')
1836 action_name
= _get_action_name(conflict_action
)
1837 raise ArgumentError(action
, msg
% action_name
)
1839 # take the action if we didn't receive a SUPPRESS value
1840 # (e.g. from a default)
1841 if argument_values
is not SUPPRESS
:
1842 action(self
, namespace
, argument_values
, option_string
)
1844 # function to convert arg_strings into an optional action
1845 def consume_optional(start_index
):
1847 # get the optional identified at this index
1848 option_tuple
= option_string_indices
[start_index
]
1849 action
, option_string
, explicit_arg
= option_tuple
1851 # identify additional optionals in the same arg string
1852 # (e.g. -xyz is the same as -x -y -z if no args are required)
1853 match_argument
= self
._match
_argument
1857 # if we found no optional action, skip it
1859 extras
.append(arg_strings
[start_index
])
1860 return start_index
+ 1
1862 # if there is an explicit argument, try to match the
1863 # optional's string arguments to only this
1864 if explicit_arg
is not None:
1865 arg_count
= match_argument(action
, 'A')
1867 # if the action is a single-dash option and takes no
1868 # arguments, try to parse more single-dash options out
1869 # of the tail of the option string
1870 chars
= self
.prefix_chars
1871 if arg_count
== 0 and option_string
[1] not in chars
:
1872 action_tuples
.append((action
, [], option_string
))
1873 char
= option_string
[0]
1874 option_string
= char
+ explicit_arg
[0]
1875 new_explicit_arg
= explicit_arg
[1:] or None
1876 optionals_map
= self
._option
_string
_actions
1877 if option_string
in optionals_map
:
1878 action
= optionals_map
[option_string
]
1879 explicit_arg
= new_explicit_arg
1881 msg
= _('ignored explicit argument %r')
1882 raise ArgumentError(action
, msg
% explicit_arg
)
1884 # if the action expect exactly one argument, we've
1885 # successfully matched the option; exit the loop
1886 elif arg_count
== 1:
1887 stop
= start_index
+ 1
1888 args
= [explicit_arg
]
1889 action_tuples
.append((action
, args
, option_string
))
1892 # error if a double-dash option did not use the
1895 msg
= _('ignored explicit argument %r')
1896 raise ArgumentError(action
, msg
% explicit_arg
)
1898 # if there is no explicit argument, try to match the
1899 # optional's string arguments with the following strings
1900 # if successful, exit the loop
1902 start
= start_index
+ 1
1903 selected_patterns
= arg_strings_pattern
[start
:]
1904 arg_count
= match_argument(action
, selected_patterns
)
1905 stop
= start
+ arg_count
1906 args
= arg_strings
[start
:stop
]
1907 action_tuples
.append((action
, args
, option_string
))
1910 # add the Optional to the list and return the index at which
1911 # the Optional's string args stopped
1912 assert action_tuples
1913 for action
, args
, option_string
in action_tuples
:
1914 take_action(action
, args
, option_string
)
1917 # the list of Positionals left to be parsed; this is modified
1918 # by consume_positionals()
1919 positionals
= self
._get
_positional
_actions
()
1921 # function to convert arg_strings into positional actions
1922 def consume_positionals(start_index
):
1923 # match as many Positionals as possible
1924 match_partial
= self
._match
_arguments
_partial
1925 selected_pattern
= arg_strings_pattern
[start_index
:]
1926 arg_counts
= match_partial(positionals
, selected_pattern
)
1928 # slice off the appropriate arg strings for each Positional
1929 # and add the Positional and its args to the list
1930 for action
, arg_count
in zip(positionals
, arg_counts
):
1931 args
= arg_strings
[start_index
: start_index
+ arg_count
]
1932 start_index
+= arg_count
1933 take_action(action
, args
)
1935 # slice off the Positionals that we just parsed and return the
1936 # index at which the Positionals' string args stopped
1937 positionals
[:] = positionals
[len(arg_counts
):]
1940 # consume Positionals and Optionals alternately, until we have
1941 # passed the last option string
1944 if option_string_indices
:
1945 max_option_string_index
= max(option_string_indices
)
1947 max_option_string_index
= -1
1948 while start_index
<= max_option_string_index
:
1950 # consume any Positionals preceding the next option
1951 next_option_string_index
= min([
1953 for index
in option_string_indices
1954 if index
>= start_index
])
1955 if start_index
!= next_option_string_index
:
1956 positionals_end_index
= consume_positionals(start_index
)
1958 # only try to parse the next optional if we didn't consume
1959 # the option string during the positionals parsing
1960 if positionals_end_index
> start_index
:
1961 start_index
= positionals_end_index
1964 start_index
= positionals_end_index
1966 # if we consumed all the positionals we could and we're not
1967 # at the index of an option string, there were extra arguments
1968 if start_index
not in option_string_indices
:
1969 strings
= arg_strings
[start_index
:next_option_string_index
]
1970 extras
.extend(strings
)
1971 start_index
= next_option_string_index
1973 # consume the next optional and any arguments for it
1974 start_index
= consume_optional(start_index
)
1976 # consume any positionals following the last Optional
1977 stop_index
= consume_positionals(start_index
)
1979 # if we didn't consume all the argument strings, there were extras
1980 extras
.extend(arg_strings
[stop_index
:])
1982 # if we didn't use all the Positional objects, there were too few
1983 # arg strings supplied.
1985 self
.error(_('too few arguments'))
1987 # make sure all required actions were present, and convert defaults.
1988 for action
in self
._actions
:
1989 if action
not in seen_actions
:
1991 name
= _get_action_name(action
)
1992 self
.error(_('argument %s is required') % name
)
1994 # Convert action default now instead of doing it before
1995 # parsing arguments to avoid calling convert functions
1996 # twice (which may fail) if the argument was given, but
1997 # only if it was defined already in the namespace
1998 if (action
.default
is not None and
1999 isinstance(action
.default
, basestring
) and
2000 hasattr(namespace
, action
.dest
) and
2001 action
.default
is getattr(namespace
, action
.dest
)):
2002 setattr(namespace
, action
.dest
,
2003 self
._get
_value
(action
, action
.default
))
2005 # make sure all required groups had one option present
2006 for group
in self
._mutually
_exclusive
_groups
:
2008 for action
in group
._group
_actions
:
2009 if action
in seen_non_default_actions
:
2012 # if no actions were used, report the error
2014 names
= [_get_action_name(action
)
2015 for action
in group
._group
_actions
2016 if action
.help is not SUPPRESS
]
2017 msg
= _('one of the arguments %s is required')
2018 self
.error(msg
% ' '.join(names
))
2020 # return the updated namespace and the extra arguments
2021 return namespace
, extras
2023 def _read_args_from_files(self
, arg_strings
):
2024 # expand arguments referencing files
2025 new_arg_strings
= []
2026 for arg_string
in arg_strings
:
2028 # for regular arguments, just add them back into the list
2029 if arg_string
[0] not in self
.fromfile_prefix_chars
:
2030 new_arg_strings
.append(arg_string
)
2032 # replace arguments referencing files with the file content
2035 args_file
= open(arg_string
[1:])
2038 for arg_line
in args_file
.read().splitlines():
2039 for arg
in self
.convert_arg_line_to_args(arg_line
):
2040 arg_strings
.append(arg
)
2041 arg_strings
= self
._read
_args
_from
_files
(arg_strings
)
2042 new_arg_strings
.extend(arg_strings
)
2046 err
= _sys
.exc_info()[1]
2047 self
.error(str(err
))
2049 # return the modified argument list
2050 return new_arg_strings
2052 def convert_arg_line_to_args(self
, arg_line
):
2055 def _match_argument(self
, action
, arg_strings_pattern
):
2056 # match the pattern for this action to the arg strings
2057 nargs_pattern
= self
._get
_nargs
_pattern
(action
)
2058 match
= _re
.match(nargs_pattern
, arg_strings_pattern
)
2060 # raise an exception if we weren't able to find a match
2063 None: _('expected one argument'),
2064 OPTIONAL
: _('expected at most one argument'),
2065 ONE_OR_MORE
: _('expected at least one argument'),
2067 default
= _('expected %s argument(s)') % action
.nargs
2068 msg
= nargs_errors
.get(action
.nargs
, default
)
2069 raise ArgumentError(action
, msg
)
2071 # return the number of arguments matched
2072 return len(match
.group(1))
2074 def _match_arguments_partial(self
, actions
, arg_strings_pattern
):
2075 # progressively shorten the actions list by slicing off the
2076 # final actions until we find a match
2078 for i
in range(len(actions
), 0, -1):
2079 actions_slice
= actions
[:i
]
2080 pattern
= ''.join([self
._get
_nargs
_pattern
(action
)
2081 for action
in actions_slice
])
2082 match
= _re
.match(pattern
, arg_strings_pattern
)
2083 if match
is not None:
2084 result
.extend([len(string
) for string
in match
.groups()])
2087 # return the list of arg string counts
2090 def _parse_optional(self
, arg_string
):
2091 # if it's an empty string, it was meant to be a positional
2095 # if it doesn't start with a prefix, it was meant to be positional
2096 if not arg_string
[0] in self
.prefix_chars
:
2099 # if the option string is present in the parser, return the action
2100 if arg_string
in self
._option
_string
_actions
:
2101 action
= self
._option
_string
_actions
[arg_string
]
2102 return action
, arg_string
, None
2104 # if it's just a single character, it was meant to be positional
2105 if len(arg_string
) == 1:
2108 # if the option string before the "=" is present, return the action
2109 if '=' in arg_string
:
2110 option_string
, explicit_arg
= arg_string
.split('=', 1)
2111 if option_string
in self
._option
_string
_actions
:
2112 action
= self
._option
_string
_actions
[option_string
]
2113 return action
, option_string
, explicit_arg
2115 # search through all possible prefixes of the option string
2116 # and all actions in the parser for possible interpretations
2117 option_tuples
= self
._get
_option
_tuples
(arg_string
)
2119 # if multiple actions match, the option string was ambiguous
2120 if len(option_tuples
) > 1:
2121 options
= ', '.join([option_string
2122 for action
, option_string
, explicit_arg
in option_tuples
])
2123 tup
= arg_string
, options
2124 self
.error(_('ambiguous option: %s could match %s') % tup
)
2126 # if exactly one action matched, this segmentation is good,
2127 # so return the parsed action
2128 elif len(option_tuples
) == 1:
2129 option_tuple
, = option_tuples
2132 # if it was not found as an option, but it looks like a negative
2133 # number, it was meant to be positional
2134 # unless there are negative-number-like options
2135 if self
._negative
_number
_matcher
.match(arg_string
):
2136 if not self
._has
_negative
_number
_optionals
:
2139 # if it contains a space, it was meant to be a positional
2140 if ' ' in arg_string
:
2143 # it was meant to be an optional but there is no such option
2144 # in this parser (though it might be a valid option in a subparser)
2145 return None, arg_string
, None
2147 def _get_option_tuples(self
, option_string
):
2150 # option strings starting with two prefix characters are only
2152 chars
= self
.prefix_chars
2153 if option_string
[0] in chars
and option_string
[1] in chars
:
2154 if '=' in option_string
:
2155 option_prefix
, explicit_arg
= option_string
.split('=', 1)
2157 option_prefix
= option_string
2159 for option_string
in self
._option
_string
_actions
:
2160 if option_string
.startswith(option_prefix
):
2161 action
= self
._option
_string
_actions
[option_string
]
2162 tup
= action
, option_string
, explicit_arg
2165 # single character options can be concatenated with their arguments
2166 # but multiple character options always have to have their argument
2168 elif option_string
[0] in chars
and option_string
[1] not in chars
:
2169 option_prefix
= option_string
2171 short_option_prefix
= option_string
[:2]
2172 short_explicit_arg
= option_string
[2:]
2174 for option_string
in self
._option
_string
_actions
:
2175 if option_string
== short_option_prefix
:
2176 action
= self
._option
_string
_actions
[option_string
]
2177 tup
= action
, option_string
, short_explicit_arg
2179 elif option_string
.startswith(option_prefix
):
2180 action
= self
._option
_string
_actions
[option_string
]
2181 tup
= action
, option_string
, explicit_arg
2184 # shouldn't ever get here
2186 self
.error(_('unexpected option string: %s') % option_string
)
2188 # return the collected option tuples
2191 def _get_nargs_pattern(self
, action
):
2192 # in all examples below, we have to allow for '--' args
2193 # which are represented as '-' in the pattern
2194 nargs
= action
.nargs
2196 # the default (None) is assumed to be a single argument
2198 nargs_pattern
= '(-*A-*)'
2200 # allow zero or one arguments
2201 elif nargs
== OPTIONAL
:
2202 nargs_pattern
= '(-*A?-*)'
2204 # allow zero or more arguments
2205 elif nargs
== ZERO_OR_MORE
:
2206 nargs_pattern
= '(-*[A-]*)'
2208 # allow one or more arguments
2209 elif nargs
== ONE_OR_MORE
:
2210 nargs_pattern
= '(-*A[A-]*)'
2212 # allow any number of options or arguments
2213 elif nargs
== REMAINDER
:
2214 nargs_pattern
= '([-AO]*)'
2216 # allow one argument followed by any number of options or arguments
2217 elif nargs
== PARSER
:
2218 nargs_pattern
= '(-*A[-AO]*)'
2220 # all others should be integers
2222 nargs_pattern
= '(-*%s-*)' % '-*'.join('A' * nargs
)
2224 # if this is an optional action, -- is not allowed
2225 if action
.option_strings
:
2226 nargs_pattern
= nargs_pattern
.replace('-*', '')
2227 nargs_pattern
= nargs_pattern
.replace('-', '')
2229 # return the pattern
2230 return nargs_pattern
2232 # ========================
2233 # Value conversion methods
2234 # ========================
2235 def _get_values(self
, action
, arg_strings
):
2236 # for everything but PARSER args, strip out '--'
2237 if action
.nargs
not in [PARSER
, REMAINDER
]:
2238 arg_strings
= [s
for s
in arg_strings
if s
!= '--']
2240 # optional argument produces a default when not present
2241 if not arg_strings
and action
.nargs
== OPTIONAL
:
2242 if action
.option_strings
:
2243 value
= action
.const
2245 value
= action
.default
2246 if isinstance(value
, basestring
):
2247 value
= self
._get
_value
(action
, value
)
2248 self
._check
_value
(action
, value
)
2250 # when nargs='*' on a positional, if there were no command-line
2251 # args, use the default if it is anything other than None
2252 elif (not arg_strings
and action
.nargs
== ZERO_OR_MORE
and
2253 not action
.option_strings
):
2254 if action
.default
is not None:
2255 value
= action
.default
2258 self
._check
_value
(action
, value
)
2260 # single argument or optional argument produces a single value
2261 elif len(arg_strings
) == 1 and action
.nargs
in [None, OPTIONAL
]:
2262 arg_string
, = arg_strings
2263 value
= self
._get
_value
(action
, arg_string
)
2264 self
._check
_value
(action
, value
)
2266 # REMAINDER arguments convert all values, checking none
2267 elif action
.nargs
== REMAINDER
:
2268 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2270 # PARSER arguments convert all values, but check only the first
2271 elif action
.nargs
== PARSER
:
2272 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2273 self
._check
_value
(action
, value
[0])
2275 # all other types of nargs produce a list
2277 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2279 self
._check
_value
(action
, v
)
2281 # return the converted value
2284 def _get_value(self
, action
, arg_string
):
2285 type_func
= self
._registry
_get
('type', action
.type, action
.type)
2286 if not _callable(type_func
):
2287 msg
= _('%r is not callable')
2288 raise ArgumentError(action
, msg
% type_func
)
2290 # convert the value to the appropriate type
2292 result
= type_func(arg_string
)
2294 # ArgumentTypeErrors indicate errors
2295 except ArgumentTypeError
:
2296 name
= getattr(action
.type, '__name__', repr(action
.type))
2297 msg
= str(_sys
.exc_info()[1])
2298 raise ArgumentError(action
, msg
)
2300 # TypeErrors or ValueErrors also indicate errors
2301 except (TypeError, ValueError):
2302 name
= getattr(action
.type, '__name__', repr(action
.type))
2303 msg
= _('invalid %s value: %r')
2304 raise ArgumentError(action
, msg
% (name
, arg_string
))
2306 # return the converted value
2309 def _check_value(self
, action
, value
):
2310 # converted value must be one of the choices (if specified)
2311 if action
.choices
is not None and value
not in action
.choices
:
2312 tup
= value
, ', '.join(map(repr, action
.choices
))
2313 msg
= _('invalid choice: %r (choose from %s)') % tup
2314 raise ArgumentError(action
, msg
)
2316 # =======================
2317 # Help-formatting methods
2318 # =======================
2319 def format_usage(self
):
2320 formatter
= self
._get
_formatter
()
2321 formatter
.add_usage(self
.usage
, self
._actions
,
2322 self
._mutually
_exclusive
_groups
)
2323 return formatter
.format_help()
2325 def format_help(self
):
2326 formatter
= self
._get
_formatter
()
2329 formatter
.add_usage(self
.usage
, self
._actions
,
2330 self
._mutually
_exclusive
_groups
)
2333 formatter
.add_text(self
.description
)
2335 # positionals, optionals and user-defined groups
2336 for action_group
in self
._action
_groups
:
2337 formatter
.start_section(action_group
.title
)
2338 formatter
.add_text(action_group
.description
)
2339 formatter
.add_arguments(action_group
._group
_actions
)
2340 formatter
.end_section()
2343 formatter
.add_text(self
.epilog
)
2345 # determine help from format above
2346 return formatter
.format_help()
2348 def format_version(self
):
2351 'The format_version method is deprecated -- the "version" '
2352 'argument to ArgumentParser is no longer supported.',
2354 formatter
= self
._get
_formatter
()
2355 formatter
.add_text(self
.version
)
2356 return formatter
.format_help()
2358 def _get_formatter(self
):
2359 return self
.formatter_class(prog
=self
.prog
)
2361 # =====================
2362 # Help-printing methods
2363 # =====================
2364 def print_usage(self
, file=None):
2367 self
._print
_message
(self
.format_usage(), file)
2369 def print_help(self
, file=None):
2372 self
._print
_message
(self
.format_help(), file)
2374 def print_version(self
, file=None):
2377 'The print_version method is deprecated -- the "version" '
2378 'argument to ArgumentParser is no longer supported.',
2380 self
._print
_message
(self
.format_version(), file)
2382 def _print_message(self
, message
, file=None):
2391 def exit(self
, status
=0, message
=None):
2393 self
._print
_message
(message
, _sys
.stderr
)
2396 def error(self
, message
):
2397 """error(message: string)
2399 Prints a usage message incorporating the message to stderr and
2402 If you override this in a subclass, it should not return -- it
2403 should either exit or raise an exception.
2405 self
.print_usage(_sys
.stderr
)
2406 self
.exit(2, _('%s: error: %s\n') % (self
.prog
, message
))