1 # Author: Steven J. Bethard <steven.bethard@gmail.com>.
2 # Maintainer: Thomas Waldmann <tw@waldmann-edv.de>
4 """Command-line parsing library
6 This module is an optparse-inspired command-line parsing library that:
8 - handles both optional and positional arguments
9 - produces highly informative usage messages
10 - supports parsers that dispatch to sub-parsers
12 The following is a simple usage example that sums integers from the
13 command-line and writes the result to a file::
15 parser = argparse.ArgumentParser(
16 description='sum the integers at the command line')
18 'integers', metavar='int', nargs='+', type=int,
19 help='an integer to be summed')
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))
27 The module contains the following public classes:
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.
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.
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.
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.
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
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.)
65 __version__
= '1.4.0' # we use our own version number independant of the
66 # one in stdlib and we release this on pypi.
68 __external_lib__
= True # to make sure the tests really test THIS lib,
69 # not the builtin one in Python stdlib
77 'ArgumentDefaultsHelpFormatter',
78 'RawDescriptionHelpFormatter',
79 'RawTextHelpFormatter',
95 import textwrap
as _textwrap
97 from gettext
import gettext
as _
102 # for python < 2.4 compatibility (sets module is there since 2.3):
103 from sets
import Set
as set
113 # for python < 2.4 compatibility:
114 def sorted(iterable
, reverse
=False):
115 result
= list(iterable
)
123 return hasattr(obj
, '__call__') or hasattr(obj
, '__bases__')
126 SUPPRESS
= '==SUPPRESS=='
133 _UNRECOGNIZED_ARGS_ATTR
= '_unrecognized_args'
135 # =============================
136 # Utility functions and classes
137 # =============================
139 class _AttributeHolder(object):
140 """Abstract base class that provides __repr__.
142 The __repr__ method returns a string in the format::
143 ClassName(attr=name, attr=name, ...)
144 The attributes are determined either by a class-level attribute,
145 '_kwarg_names', or by inspecting the instance __dict__.
149 type_name
= type(self
).__name
__
151 for arg
in self
._get
_args
():
152 arg_strings
.append(repr(arg
))
153 for name
, value
in self
._get
_kwargs
():
154 arg_strings
.append('%s=%r' % (name
, value
))
155 return '%s(%s)' % (type_name
, ', '.join(arg_strings
))
157 def _get_kwargs(self
):
158 return sorted(self
.__dict
__.items())
164 def _ensure_value(namespace
, name
, value
):
165 if getattr(namespace
, name
, None) is None:
166 setattr(namespace
, name
, value
)
167 return getattr(namespace
, name
)
174 class HelpFormatter(object):
175 """Formatter for generating usage messages and argument help strings.
177 Only the name of this class is considered a public API. All the methods
178 provided by the class are considered an implementation detail.
184 max_help_position
=24,
187 # default setting for width
190 width
= int(_os
.environ
['COLUMNS'])
191 except (KeyError, ValueError):
196 self
._indent
_increment
= indent_increment
197 self
._max
_help
_position
= max_help_position
200 self
._current
_indent
= 0
202 self
._action
_max
_length
= 0
204 self
._root
_section
= self
._Section
(self
, None)
205 self
._current
_section
= self
._root
_section
207 self
._whitespace
_matcher
= _re
.compile(r
'\s+')
208 self
._long
_break
_matcher
= _re
.compile(r
'\n\n\n+')
210 # ===============================
211 # Section and indentation methods
212 # ===============================
214 self
._current
_indent
+= self
._indent
_increment
218 self
._current
_indent
-= self
._indent
_increment
219 assert self
._current
_indent
>= 0, 'Indent decreased below 0.'
222 class _Section(object):
224 def __init__(self
, formatter
, parent
, heading
=None):
225 self
.formatter
= formatter
227 self
.heading
= heading
230 def format_help(self
):
231 # format the indented section
232 if self
.parent
is not None:
233 self
.formatter
._indent
()
234 join
= self
.formatter
._join
_parts
235 for func
, args
in self
.items
:
237 item_help
= join([func(*args
) for func
, args
in self
.items
])
238 if self
.parent
is not None:
239 self
.formatter
._dedent
()
241 # return nothing if the section was empty
245 # add the heading if the section was non-empty
246 if self
.heading
is not SUPPRESS
and self
.heading
is not None:
247 current_indent
= self
.formatter
._current
_indent
248 heading
= '%*s%s:\n' % (current_indent
, '', self
.heading
)
252 # join the section-initial newline, the heading and the help
253 return join(['\n', heading
, item_help
, '\n'])
255 def _add_item(self
, func
, args
):
256 self
._current
_section
.items
.append((func
, args
))
258 # ========================
259 # Message building methods
260 # ========================
261 def start_section(self
, heading
):
263 section
= self
._Section
(self
, self
._current
_section
, heading
)
264 self
._add
_item
(section
.format_help
, [])
265 self
._current
_section
= section
267 def end_section(self
):
268 self
._current
_section
= self
._current
_section
.parent
271 def add_text(self
, text
):
272 if text
is not SUPPRESS
and text
is not None:
273 self
._add
_item
(self
._format
_text
, [text
])
275 def add_usage(self
, usage
, actions
, groups
, prefix
=None):
276 if usage
is not SUPPRESS
:
277 args
= usage
, actions
, groups
, prefix
278 self
._add
_item
(self
._format
_usage
, args
)
280 def add_argument(self
, action
):
281 if action
.help is not SUPPRESS
:
283 # find all invocations
284 get_invocation
= self
._format
_action
_invocation
285 invocations
= [get_invocation(action
)]
286 for subaction
in self
._iter
_indented
_subactions
(action
):
287 invocations
.append(get_invocation(subaction
))
289 # update the maximum item length
290 invocation_length
= max([len(s
) for s
in invocations
])
291 action_length
= invocation_length
+ self
._current
_indent
292 self
._action
_max
_length
= max(self
._action
_max
_length
,
295 # add the item to the list
296 self
._add
_item
(self
._format
_action
, [action
])
298 def add_arguments(self
, actions
):
299 for action
in actions
:
300 self
.add_argument(action
)
302 # =======================
303 # Help-formatting methods
304 # =======================
305 def format_help(self
):
306 help = self
._root
_section
.format_help()
308 help = self
._long
_break
_matcher
.sub('\n\n', help)
309 help = help.strip('\n') + '\n'
312 def _join_parts(self
, part_strings
):
314 for part
in part_strings
315 if part
and part
is not SUPPRESS
])
317 def _format_usage(self
, usage
, actions
, groups
, prefix
):
319 prefix
= _('usage: ')
321 # if usage is specified, use that
322 if usage
is not None:
323 usage
= usage
% dict(prog
=self
._prog
)
325 # if no optionals or positionals are available, usage is just prog
326 elif usage
is None and not actions
:
327 usage
= '%(prog)s' % dict(prog
=self
._prog
)
329 # if optionals and positionals are available, calculate usage
331 prog
= '%(prog)s' % dict(prog
=self
._prog
)
333 # split optionals from positionals
336 for action
in actions
:
337 if action
.option_strings
:
338 optionals
.append(action
)
340 positionals
.append(action
)
342 # build full usage string
343 format
= self
._format
_actions
_usage
344 action_usage
= format(optionals
+ positionals
, groups
)
345 usage
= ' '.join([s
for s
in [prog
, action_usage
] if s
])
347 # wrap the usage parts if it's too long
348 text_width
= self
._width
- self
._current
_indent
349 if len(prefix
) + len(usage
) > text_width
:
351 # break usage into wrappable parts
352 part_regexp
= r
'\(.*?\)+|\[.*?\]+|\S+'
353 opt_usage
= format(optionals
, groups
)
354 pos_usage
= format(positionals
, groups
)
355 opt_parts
= _re
.findall(part_regexp
, opt_usage
)
356 pos_parts
= _re
.findall(part_regexp
, pos_usage
)
357 assert ' '.join(opt_parts
) == opt_usage
358 assert ' '.join(pos_parts
) == pos_usage
360 # helper for wrapping lines
361 def get_lines(parts
, indent
, prefix
=None):
364 if prefix
is not None:
365 line_len
= len(prefix
) - 1
367 line_len
= len(indent
) - 1
369 if line_len
+ 1 + len(part
) > text_width
:
370 lines
.append(indent
+ ' '.join(line
))
372 line_len
= len(indent
) - 1
374 line_len
+= len(part
) + 1
376 lines
.append(indent
+ ' '.join(line
))
377 if prefix
is not None:
378 lines
[0] = lines
[0][len(indent
):]
381 # if prog is short, follow it with optionals or positionals
382 if len(prefix
) + len(prog
) <= 0.75 * text_width
:
383 indent
= ' ' * (len(prefix
) + len(prog
) + 1)
385 lines
= get_lines([prog
] + opt_parts
, indent
, prefix
)
386 lines
.extend(get_lines(pos_parts
, indent
))
388 lines
= get_lines([prog
] + pos_parts
, indent
, prefix
)
392 # if prog is long, put it on its own line
394 indent
= ' ' * len(prefix
)
395 parts
= opt_parts
+ pos_parts
396 lines
= get_lines(parts
, indent
)
399 lines
.extend(get_lines(opt_parts
, indent
))
400 lines
.extend(get_lines(pos_parts
, indent
))
401 lines
= [prog
] + lines
403 # join lines into usage
404 usage
= '\n'.join(lines
)
406 # prefix with 'usage:'
407 return '%s%s\n\n' % (prefix
, usage
)
409 def _format_actions_usage(self
, actions
, groups
):
410 # find group indices and identify actions in groups
411 group_actions
= set()
415 start
= actions
.index(group
._group
_actions
[0])
419 end
= start
+ len(group
._group
_actions
)
420 if actions
[start
:end
] == group
._group
_actions
:
421 for action
in group
._group
_actions
:
422 group_actions
.add(action
)
423 if not group
.required
:
425 inserts
[start
] += ' ['
431 inserts
[start
] += ' ('
435 for i
in range(start
+ 1, end
):
438 # collect all actions format strings
440 for i
, action
in enumerate(actions
):
442 # suppressed arguments are marked with None
443 # remove | separators for suppressed arguments
444 if action
.help is SUPPRESS
:
446 if inserts
.get(i
) == '|':
448 elif inserts
.get(i
+ 1) == '|':
451 # produce all arg strings
452 elif not action
.option_strings
:
453 part
= self
._format
_args
(action
, action
.dest
)
455 # if it's in a group, strip the outer []
456 if action
in group_actions
:
457 if part
[0] == '[' and part
[-1] == ']':
460 # add the action string to the list
463 # produce the first way to invoke the option in brackets
465 option_string
= action
.option_strings
[0]
467 # if the Optional doesn't take a value, format is:
469 if action
.nargs
== 0:
470 part
= '%s' % option_string
472 # if the Optional takes a value, format is:
473 # -s ARGS or --long ARGS
475 default
= action
.dest
.upper()
476 args_string
= self
._format
_args
(action
, default
)
477 part
= '%s %s' % (option_string
, args_string
)
479 # make it look optional if it's not required or in a group
480 if not action
.required
and action
not in group_actions
:
483 # add the action string to the list
486 # insert things at the necessary indices
487 for i
in sorted(inserts
, reverse
=True):
488 parts
[i
:i
] = [inserts
[i
]]
490 # join all the action items with spaces
491 text
= ' '.join([item
for item
in parts
if item
is not None])
493 # clean up separators for mutually exclusive groups
496 text
= _re
.sub(r
'(%s) ' % open, r
'\1', text
)
497 text
= _re
.sub(r
' (%s)' % close
, r
'\1', text
)
498 text
= _re
.sub(r
'%s *%s' % (open, close
), r
'', text
)
499 text
= _re
.sub(r
'\(([^|]*)\)', r
'\1', text
)
505 def _format_text(self
, text
):
506 if '%(prog)' in text
:
507 text
= text
% dict(prog
=self
._prog
)
508 text_width
= self
._width
- self
._current
_indent
509 indent
= ' ' * self
._current
_indent
510 return self
._fill
_text
(text
, text_width
, indent
) + '\n\n'
512 def _format_action(self
, action
):
513 # determine the required width and the entry label
514 help_position
= min(self
._action
_max
_length
+ 2,
515 self
._max
_help
_position
)
516 help_width
= self
._width
- help_position
517 action_width
= help_position
- self
._current
_indent
- 2
518 action_header
= self
._format
_action
_invocation
(action
)
520 # ho nelp; start on same line and add a final newline
522 tup
= self
._current
_indent
, '', action_header
523 action_header
= '%*s%s\n' % tup
525 # short action name; start on the same line and pad two spaces
526 elif len(action_header
) <= action_width
:
527 tup
= self
._current
_indent
, '', action_width
, action_header
528 action_header
= '%*s%-*s ' % tup
531 # long action name; start on the next line
533 tup
= self
._current
_indent
, '', action_header
534 action_header
= '%*s%s\n' % tup
535 indent_first
= help_position
537 # collect the pieces of the action help
538 parts
= [action_header
]
540 # if there was help for the action, add lines of help text
542 help_text
= self
._expand
_help
(action
)
543 help_lines
= self
._split
_lines
(help_text
, help_width
)
544 parts
.append('%*s%s\n' % (indent_first
, '', help_lines
[0]))
545 for line
in help_lines
[1:]:
546 parts
.append('%*s%s\n' % (help_position
, '', line
))
548 # or add a newline if the description doesn't end with one
549 elif not action_header
.endswith('\n'):
552 # if there are any sub-actions, add their help as well
553 for subaction
in self
._iter
_indented
_subactions
(action
):
554 parts
.append(self
._format
_action
(subaction
))
556 # return a single string
557 return self
._join
_parts
(parts
)
559 def _format_action_invocation(self
, action
):
560 if not action
.option_strings
:
561 metavar
, = self
._metavar
_formatter
(action
, action
.dest
)(1)
567 # if the Optional doesn't take a value, format is:
569 if action
.nargs
== 0:
570 parts
.extend(action
.option_strings
)
572 # if the Optional takes a value, format is:
573 # -s ARGS, --long ARGS
575 default
= action
.dest
.upper()
576 args_string
= self
._format
_args
(action
, default
)
577 for option_string
in action
.option_strings
:
578 parts
.append('%s %s' % (option_string
, args_string
))
580 return ', '.join(parts
)
582 def _metavar_formatter(self
, action
, default_metavar
):
583 if action
.metavar
is not None:
584 result
= action
.metavar
585 elif action
.choices
is not None:
586 choice_strs
= [str(choice
) for choice
in action
.choices
]
587 result
= '{%s}' % ','.join(choice_strs
)
589 result
= default_metavar
591 def format(tuple_size
):
592 if isinstance(result
, tuple):
595 return (result
, ) * tuple_size
598 def _format_args(self
, action
, default_metavar
):
599 get_metavar
= self
._metavar
_formatter
(action
, default_metavar
)
600 if action
.nargs
is None:
601 result
= '%s' % get_metavar(1)
602 elif action
.nargs
== OPTIONAL
:
603 result
= '[%s]' % get_metavar(1)
604 elif action
.nargs
== ZERO_OR_MORE
:
605 result
= '[%s [%s ...]]' % get_metavar(2)
606 elif action
.nargs
== ONE_OR_MORE
:
607 result
= '%s [%s ...]' % get_metavar(2)
608 elif action
.nargs
== REMAINDER
:
610 elif action
.nargs
== PARSER
:
611 result
= '%s ...' % get_metavar(1)
613 formats
= ['%s' for _
in range(action
.nargs
)]
614 result
= ' '.join(formats
) % get_metavar(action
.nargs
)
617 def _expand_help(self
, action
):
618 params
= dict(vars(action
), prog
=self
._prog
)
619 for name
in list(params
):
620 if params
[name
] is SUPPRESS
:
622 for name
in list(params
):
623 if hasattr(params
[name
], '__name__'):
624 params
[name
] = params
[name
].__name
__
625 if params
.get('choices') is not None:
626 choices_str
= ', '.join([str(c
) for c
in params
['choices']])
627 params
['choices'] = choices_str
628 return self
._get
_help
_string
(action
) % params
630 def _iter_indented_subactions(self
, action
):
632 get_subactions
= action
._get
_subactions
633 except AttributeError:
637 for subaction
in get_subactions():
641 def _split_lines(self
, text
, width
):
642 text
= self
._whitespace
_matcher
.sub(' ', text
).strip()
643 return _textwrap
.wrap(text
, width
)
645 def _fill_text(self
, text
, width
, indent
):
646 text
= self
._whitespace
_matcher
.sub(' ', text
).strip()
647 return _textwrap
.fill(text
, width
, initial_indent
=indent
,
648 subsequent_indent
=indent
)
650 def _get_help_string(self
, action
):
654 class RawDescriptionHelpFormatter(HelpFormatter
):
655 """Help message formatter which retains any formatting in descriptions.
657 Only the name of this class is considered a public API. All the methods
658 provided by the class are considered an implementation detail.
661 def _fill_text(self
, text
, width
, indent
):
662 return ''.join([indent
+ line
for line
in text
.splitlines(True)])
665 class RawTextHelpFormatter(RawDescriptionHelpFormatter
):
666 """Help message formatter which retains formatting of all help text.
668 Only the name of this class is considered a public API. All the methods
669 provided by the class are considered an implementation detail.
672 def _split_lines(self
, text
, width
):
673 return text
.splitlines()
676 class ArgumentDefaultsHelpFormatter(HelpFormatter
):
677 """Help message formatter which adds default values to argument help.
679 Only the name of this class is considered a public API. All the methods
680 provided by the class are considered an implementation detail.
683 def _get_help_string(self
, action
):
685 if '%(default)' not in action
.help:
686 if action
.default
is not SUPPRESS
:
687 defaulting_nargs
= [OPTIONAL
, ZERO_OR_MORE
]
688 if action
.option_strings
or action
.nargs
in defaulting_nargs
:
689 help += ' (default: %(default)s)'
693 # =====================
694 # Options and Arguments
695 # =====================
697 def _get_action_name(argument
):
700 elif argument
.option_strings
:
701 return '/'.join(argument
.option_strings
)
702 elif argument
.metavar
not in (None, SUPPRESS
):
703 return argument
.metavar
704 elif argument
.dest
not in (None, SUPPRESS
):
710 class ArgumentError(Exception):
711 """An error from creating or using an argument (optional or positional).
713 The string value of this exception is the message, augmented with
714 information about the argument that caused it.
717 def __init__(self
, argument
, message
):
718 self
.argument_name
= _get_action_name(argument
)
719 self
.message
= message
722 if self
.argument_name
is None:
723 format
= '%(message)s'
725 format
= 'argument %(argument_name)s: %(message)s'
726 return format
% dict(message
=self
.message
,
727 argument_name
=self
.argument_name
)
730 class ArgumentTypeError(Exception):
731 """An error from trying to convert a command line string to a type."""
739 class Action(_AttributeHolder
):
740 """Information about how to convert command line strings to Python objects.
742 Action objects are used by an ArgumentParser to represent the information
743 needed to parse a single argument from one or more strings from the
744 command line. The keyword arguments to the Action constructor are also
745 all attributes of Action instances.
749 - option_strings -- A list of command-line option strings which
750 should be associated with this action.
752 - dest -- The name of the attribute to hold the created object(s)
754 - nargs -- The number of command-line arguments that should be
755 consumed. By default, one argument will be consumed and a single
756 value will be produced. Other values include:
757 - N (an integer) consumes N arguments (and produces a list)
758 - '?' consumes zero or one arguments
759 - '*' consumes zero or more arguments (and produces a list)
760 - '+' consumes one or more arguments (and produces a list)
761 Note that the difference between the default and nargs=1 is that
762 with the default, a single value will be produced, while with
763 nargs=1, a list containing a single value will be produced.
765 - const -- The value to be produced if the option is specified and the
766 option uses an action that takes no values.
768 - default -- The value to be produced if the option is not specified.
770 - type -- The type which the command-line arguments should be converted
771 to, should be one of 'string', 'int', 'float', 'complex' or a
772 callable object that accepts a single string argument. If None,
775 - choices -- A container of values that should be allowed. If not None,
776 after a command-line argument has been converted to the appropriate
777 type, an exception will be raised if it is not a member of this
780 - required -- True if the action must always be specified at the
781 command line. This is only meaningful for optional command-line
784 - help -- The help string describing the argument.
786 - metavar -- The name to be used for the option's argument with the
787 help string. If None, the 'dest' value will be used as the name.
801 self
.option_strings
= option_strings
805 self
.default
= default
807 self
.choices
= choices
808 self
.required
= required
810 self
.metavar
= metavar
812 def _get_kwargs(self
):
824 return [(name
, getattr(self
, name
)) for name
in names
]
826 def __call__(self
, parser
, namespace
, values
, option_string
=None):
827 raise NotImplementedError(_('.__call__() not defined'))
830 class _StoreAction(Action
):
844 raise ValueError('nargs for store actions must be > 0; if you '
845 'have nothing to store, actions such as store '
846 'true or store const may be more appropriate')
847 if const
is not None and nargs
!= OPTIONAL
:
848 raise ValueError('nargs must be %r to supply const' % OPTIONAL
)
849 super(_StoreAction
, self
).__init
__(
850 option_strings
=option_strings
,
861 def __call__(self
, parser
, namespace
, values
, option_string
=None):
862 setattr(namespace
, self
.dest
, values
)
865 class _StoreConstAction(Action
):
875 super(_StoreConstAction
, self
).__init
__(
876 option_strings
=option_strings
,
884 def __call__(self
, parser
, namespace
, values
, option_string
=None):
885 setattr(namespace
, self
.dest
, self
.const
)
888 class _StoreTrueAction(_StoreConstAction
):
896 super(_StoreTrueAction
, self
).__init
__(
897 option_strings
=option_strings
,
905 class _StoreFalseAction(_StoreConstAction
):
913 super(_StoreFalseAction
, self
).__init
__(
914 option_strings
=option_strings
,
922 class _AppendAction(Action
):
936 raise ValueError('nargs for append actions must be > 0; if arg '
937 'strings are not supplying the value to append, '
938 'the append const action may be more appropriate')
939 if const
is not None and nargs
!= OPTIONAL
:
940 raise ValueError('nargs must be %r to supply const' % OPTIONAL
)
941 super(_AppendAction
, self
).__init
__(
942 option_strings
=option_strings
,
953 def __call__(self
, parser
, namespace
, values
, option_string
=None):
954 items
= _copy
.copy(_ensure_value(namespace
, self
.dest
, []))
956 setattr(namespace
, self
.dest
, items
)
959 class _AppendConstAction(Action
):
969 super(_AppendConstAction
, self
).__init
__(
970 option_strings
=option_strings
,
979 def __call__(self
, parser
, namespace
, values
, option_string
=None):
980 items
= _copy
.copy(_ensure_value(namespace
, self
.dest
, []))
981 items
.append(self
.const
)
982 setattr(namespace
, self
.dest
, items
)
985 class _CountAction(Action
):
993 super(_CountAction
, self
).__init
__(
994 option_strings
=option_strings
,
1001 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1002 new_count
= _ensure_value(namespace
, self
.dest
, 0) + 1
1003 setattr(namespace
, self
.dest
, new_count
)
1006 class _HelpAction(Action
):
1013 super(_HelpAction
, self
).__init
__(
1014 option_strings
=option_strings
,
1020 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1025 class _VersionAction(Action
):
1032 help="show program's version number and exit"):
1033 super(_VersionAction
, self
).__init
__(
1034 option_strings
=option_strings
,
1039 self
.version
= version
1041 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1042 version
= self
.version
1044 version
= parser
.version
1045 formatter
= parser
._get
_formatter
()
1046 formatter
.add_text(version
)
1047 parser
.exit(message
=formatter
.format_help())
1050 class _SubParsersAction(Action
):
1052 class _ChoicesPseudoAction(Action
):
1054 def __init__(self
, name
, aliases
, help):
1055 metavar
= dest
= name
1057 metavar
+= ' (%s)' % ', '.join(aliases
)
1058 sup
= super(_SubParsersAction
._ChoicesPseudoAction
, self
)
1059 sup
.__init
__(option_strings
=[], dest
=dest
, help=help,
1070 self
._prog
_prefix
= prog
1071 self
._parser
_class
= parser_class
1072 self
._name
_parser
_map
= {}
1073 self
._choices
_actions
= []
1075 super(_SubParsersAction
, self
).__init
__(
1076 option_strings
=option_strings
,
1079 choices
=self
._name
_parser
_map
,
1083 def add_parser(self
, name
, **kwargs
):
1084 # set prog from the existing prefix
1085 if kwargs
.get('prog') is None:
1086 kwargs
['prog'] = '%s %s' % (self
._prog
_prefix
, name
)
1088 aliases
= kwargs
.pop('aliases', ())
1090 # create a pseudo-action to hold the choice help
1091 if 'help' in kwargs
:
1092 help = kwargs
.pop('help')
1093 choice_action
= self
._ChoicesPseudoAction
(name
, aliases
, help)
1094 self
._choices
_actions
.append(choice_action
)
1096 # create the parser and add it to the map
1097 parser
= self
._parser
_class
(**kwargs
)
1098 self
._name
_parser
_map
[name
] = parser
1100 # make parser available under aliases also
1101 for alias
in aliases
:
1102 self
._name
_parser
_map
[alias
] = parser
1106 def _get_subactions(self
):
1107 return self
._choices
_actions
1109 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1110 parser_name
= values
[0]
1111 arg_strings
= values
[1:]
1113 # set the parser name if requested
1114 if self
.dest
is not SUPPRESS
:
1115 setattr(namespace
, self
.dest
, parser_name
)
1119 parser
= self
._name
_parser
_map
[parser_name
]
1121 tup
= parser_name
, ', '.join(self
._name
_parser
_map
)
1122 msg
= _('unknown parser %r (choices: %s)' % tup
)
1123 raise ArgumentError(self
, msg
)
1125 # parse all the remaining options into the namespace
1126 # store any unrecognized options on the object, so that the top
1127 # level parser can decide what to do with them
1128 namespace
, arg_strings
= parser
.parse_known_args(arg_strings
, namespace
)
1130 vars(namespace
).setdefault(_UNRECOGNIZED_ARGS_ATTR
, [])
1131 getattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
).extend(arg_strings
)
1138 class FileType(object):
1139 """Factory for creating file object types
1141 Instances of FileType are typically passed as type= arguments to the
1142 ArgumentParser add_argument() method.
1145 - mode -- A string indicating how the file is to be opened. Accepts the
1146 same values as the builtin open() function.
1147 - bufsize -- The file's desired buffer size. Accepts the same values as
1148 the builtin open() function.
1151 def __init__(self
, mode
='r', bufsize
=None):
1153 self
._bufsize
= bufsize
1155 def __call__(self
, string
):
1156 # the special argument "-" means sys.std{in,out}
1158 if 'r' in self
._mode
:
1160 elif 'w' in self
._mode
:
1163 msg
= _('argument "-" with mode %r' % self
._mode
)
1164 raise ValueError(msg
)
1167 # all other arguments are used as file names
1169 return open(string
, self
._mode
, self
._bufsize
)
1171 return open(string
, self
._mode
)
1173 err
= _sys
.exc_info()[1]
1174 message
= _("can't open '%s': %s")
1175 raise ArgumentTypeError(message
% (string
, err
))
1178 args
= [self
._mode
, self
._bufsize
]
1179 args_str
= ', '.join([repr(arg
) for arg
in args
if arg
is not None])
1180 return '%s(%s)' % (type(self
).__name
__, args_str
)
1182 # ===========================
1183 # Optional and Positional Parsing
1184 # ===========================
1186 class Namespace(_AttributeHolder
):
1187 """Simple object for storing attributes.
1189 Implements equality by attribute names and values, and provides a simple
1190 string representation.
1193 def __init__(self
, **kwargs
):
1195 setattr(self
, name
, kwargs
[name
])
1199 def __eq__(self
, other
):
1200 return vars(self
) == vars(other
)
1202 def __ne__(self
, other
):
1203 return not (self
== other
)
1205 def __contains__(self
, key
):
1206 return key
in self
.__dict
__
1209 class _ActionsContainer(object):
1216 super(_ActionsContainer
, self
).__init
__()
1218 self
.description
= description
1219 self
.argument_default
= argument_default
1220 self
.prefix_chars
= prefix_chars
1221 self
.conflict_handler
= conflict_handler
1224 self
._registries
= {}
1227 self
.register('action', None, _StoreAction
)
1228 self
.register('action', 'store', _StoreAction
)
1229 self
.register('action', 'store_const', _StoreConstAction
)
1230 self
.register('action', 'store_true', _StoreTrueAction
)
1231 self
.register('action', 'store_false', _StoreFalseAction
)
1232 self
.register('action', 'append', _AppendAction
)
1233 self
.register('action', 'append_const', _AppendConstAction
)
1234 self
.register('action', 'count', _CountAction
)
1235 self
.register('action', 'help', _HelpAction
)
1236 self
.register('action', 'version', _VersionAction
)
1237 self
.register('action', 'parsers', _SubParsersAction
)
1239 # raise an exception if the conflict handler is invalid
1244 self
._option
_string
_actions
= {}
1247 self
._action
_groups
= []
1248 self
._mutually
_exclusive
_groups
= []
1253 # determines whether an "option" looks like a negative number
1254 self
._negative
_number
_matcher
= _re
.compile(r
'^-\d+$|^-\d*\.\d+$')
1256 # whether or not there are any optionals that look like negative
1257 # numbers -- uses a list so it can be shared and edited
1258 self
._has
_negative
_number
_optionals
= []
1260 # ====================
1261 # Registration methods
1262 # ====================
1263 def register(self
, registry_name
, value
, object):
1264 registry
= self
._registries
.setdefault(registry_name
, {})
1265 registry
[value
] = object
1267 def _registry_get(self
, registry_name
, value
, default
=None):
1268 return self
._registries
[registry_name
].get(value
, default
)
1270 # ==================================
1271 # Namespace default accessor methods
1272 # ==================================
1273 def set_defaults(self
, **kwargs
):
1274 self
._defaults
.update(kwargs
)
1276 # if these defaults match any existing arguments, replace
1277 # the previous default on the object with the new one
1278 for action
in self
._actions
:
1279 if action
.dest
in kwargs
:
1280 action
.default
= kwargs
[action
.dest
]
1282 def get_default(self
, dest
):
1283 for action
in self
._actions
:
1284 if action
.dest
== dest
and action
.default
is not None:
1285 return action
.default
1286 return self
._defaults
.get(dest
, None)
1289 # =======================
1290 # Adding argument actions
1291 # =======================
1292 def add_argument(self
, *args
, **kwargs
):
1294 add_argument(dest, ..., name=value, ...)
1295 add_argument(option_string, option_string, ..., name=value, ...)
1298 # if no positional args are supplied or only one is supplied and
1299 # it doesn't look like an option string, parse a positional
1301 chars
= self
.prefix_chars
1302 if not args
or len(args
) == 1 and args
[0][0] not in chars
:
1303 if args
and 'dest' in kwargs
:
1304 raise ValueError('dest supplied twice for positional argument')
1305 kwargs
= self
._get
_positional
_kwargs
(*args
, **kwargs
)
1307 # otherwise, we're adding an optional argument
1309 kwargs
= self
._get
_optional
_kwargs
(*args
, **kwargs
)
1311 # if no default was supplied, use the parser-level default
1312 if 'default' not in kwargs
:
1313 dest
= kwargs
['dest']
1314 if dest
in self
._defaults
:
1315 kwargs
['default'] = self
._defaults
[dest
]
1316 elif self
.argument_default
is not None:
1317 kwargs
['default'] = self
.argument_default
1319 # create the action object, and add it to the parser
1320 action_class
= self
._pop
_action
_class
(kwargs
)
1321 if not _callable(action_class
):
1322 raise ValueError('unknown action "%s"' % action_class
)
1323 action
= action_class(**kwargs
)
1325 # raise an error if the action type is not callable
1326 type_func
= self
._registry
_get
('type', action
.type, action
.type)
1327 if not _callable(type_func
):
1328 raise ValueError('%r is not callable' % type_func
)
1330 return self
._add
_action
(action
)
1332 def add_argument_group(self
, *args
, **kwargs
):
1333 group
= _ArgumentGroup(self
, *args
, **kwargs
)
1334 self
._action
_groups
.append(group
)
1337 def add_mutually_exclusive_group(self
, **kwargs
):
1338 group
= _MutuallyExclusiveGroup(self
, **kwargs
)
1339 self
._mutually
_exclusive
_groups
.append(group
)
1342 def _add_action(self
, action
):
1343 # resolve any conflicts
1344 self
._check
_conflict
(action
)
1346 # add to actions list
1347 self
._actions
.append(action
)
1348 action
.container
= self
1350 # index the action by any option strings it has
1351 for option_string
in action
.option_strings
:
1352 self
._option
_string
_actions
[option_string
] = action
1354 # set the flag if any option strings look like negative numbers
1355 for option_string
in action
.option_strings
:
1356 if self
._negative
_number
_matcher
.match(option_string
):
1357 if not self
._has
_negative
_number
_optionals
:
1358 self
._has
_negative
_number
_optionals
.append(True)
1360 # return the created action
1363 def _remove_action(self
, action
):
1364 self
._actions
.remove(action
)
1366 def _add_container_actions(self
, container
):
1367 # collect groups by titles
1368 title_group_map
= {}
1369 for group
in self
._action
_groups
:
1370 if group
.title
in title_group_map
:
1371 msg
= _('cannot merge actions - two groups are named %r')
1372 raise ValueError(msg
% (group
.title
))
1373 title_group_map
[group
.title
] = group
1375 # map each action to its group
1377 for group
in container
._action
_groups
:
1379 # if a group with the title exists, use that, otherwise
1380 # create a new group matching the container's group
1381 if group
.title
not in title_group_map
:
1382 title_group_map
[group
.title
] = self
.add_argument_group(
1384 description
=group
.description
,
1385 conflict_handler
=group
.conflict_handler
)
1387 # map the actions to their new group
1388 for action
in group
._group
_actions
:
1389 group_map
[action
] = title_group_map
[group
.title
]
1391 # add container's mutually exclusive groups
1392 # NOTE: if add_mutually_exclusive_group ever gains title= and
1393 # description= then this code will need to be expanded as above
1394 for group
in container
._mutually
_exclusive
_groups
:
1395 mutex_group
= self
.add_mutually_exclusive_group(
1396 required
=group
.required
)
1398 # map the actions to their new mutex group
1399 for action
in group
._group
_actions
:
1400 group_map
[action
] = mutex_group
1402 # add all actions to this container or their group
1403 for action
in container
._actions
:
1404 group_map
.get(action
, self
)._add
_action
(action
)
1406 def _get_positional_kwargs(self
, dest
, **kwargs
):
1407 # make sure required is not specified
1408 if 'required' in kwargs
:
1409 msg
= _("'required' is an invalid argument for positionals")
1410 raise TypeError(msg
)
1412 # mark positional arguments as required if at least one is
1414 if kwargs
.get('nargs') not in [OPTIONAL
, ZERO_OR_MORE
]:
1415 kwargs
['required'] = True
1416 if kwargs
.get('nargs') == ZERO_OR_MORE
and 'default' not in kwargs
:
1417 kwargs
['required'] = True
1419 # return the keyword arguments with no option strings
1420 return dict(kwargs
, dest
=dest
, option_strings
=[])
1422 def _get_optional_kwargs(self
, *args
, **kwargs
):
1423 # determine short and long option strings
1425 long_option_strings
= []
1426 for option_string
in args
:
1427 # error on strings that don't start with an appropriate prefix
1428 if not option_string
[0] in self
.prefix_chars
:
1429 msg
= _('invalid option string %r: '
1430 'must start with a character %r')
1431 tup
= option_string
, self
.prefix_chars
1432 raise ValueError(msg
% tup
)
1434 # strings starting with two prefix characters are long options
1435 option_strings
.append(option_string
)
1436 if option_string
[0] in self
.prefix_chars
:
1437 if len(option_string
) > 1:
1438 if option_string
[1] in self
.prefix_chars
:
1439 long_option_strings
.append(option_string
)
1441 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1442 dest
= kwargs
.pop('dest', None)
1444 if long_option_strings
:
1445 dest_option_string
= long_option_strings
[0]
1447 dest_option_string
= option_strings
[0]
1448 dest
= dest_option_string
.lstrip(self
.prefix_chars
)
1450 msg
= _('dest= is required for options like %r')
1451 raise ValueError(msg
% option_string
)
1452 dest
= dest
.replace('-', '_')
1454 # return the updated keyword arguments
1455 return dict(kwargs
, dest
=dest
, option_strings
=option_strings
)
1457 def _pop_action_class(self
, kwargs
, default
=None):
1458 action
= kwargs
.pop('action', default
)
1459 return self
._registry
_get
('action', action
, action
)
1461 def _get_handler(self
):
1462 # determine function from conflict handler string
1463 handler_func_name
= '_handle_conflict_%s' % self
.conflict_handler
1465 return getattr(self
, handler_func_name
)
1466 except AttributeError:
1467 msg
= _('invalid conflict_resolution value: %r')
1468 raise ValueError(msg
% self
.conflict_handler
)
1470 def _check_conflict(self
, action
):
1472 # find all options that conflict with this option
1473 confl_optionals
= []
1474 for option_string
in action
.option_strings
:
1475 if option_string
in self
._option
_string
_actions
:
1476 confl_optional
= self
._option
_string
_actions
[option_string
]
1477 confl_optionals
.append((option_string
, confl_optional
))
1479 # resolve any conflicts
1481 conflict_handler
= self
._get
_handler
()
1482 conflict_handler(action
, confl_optionals
)
1484 def _handle_conflict_error(self
, action
, conflicting_actions
):
1485 message
= _('conflicting option string(s): %s')
1486 conflict_string
= ', '.join([option_string
1487 for option_string
, action
1488 in conflicting_actions
])
1489 raise ArgumentError(action
, message
% conflict_string
)
1491 def _handle_conflict_resolve(self
, action
, conflicting_actions
):
1493 # remove all conflicting options
1494 for option_string
, action
in conflicting_actions
:
1496 # remove the conflicting option
1497 action
.option_strings
.remove(option_string
)
1498 self
._option
_string
_actions
.pop(option_string
, None)
1500 # if the option now has no option string, remove it from the
1501 # container holding it
1502 if not action
.option_strings
:
1503 action
.container
._remove
_action
(action
)
1506 class _ArgumentGroup(_ActionsContainer
):
1508 def __init__(self
, container
, title
=None, description
=None, **kwargs
):
1509 # add any missing keyword arguments by checking the container
1510 update
= kwargs
.setdefault
1511 update('conflict_handler', container
.conflict_handler
)
1512 update('prefix_chars', container
.prefix_chars
)
1513 update('argument_default', container
.argument_default
)
1514 super_init
= super(_ArgumentGroup
, self
).__init
__
1515 super_init(description
=description
, **kwargs
)
1519 self
._group
_actions
= []
1521 # share most attributes with the container
1522 self
._registries
= container
._registries
1523 self
._actions
= container
._actions
1524 self
._option
_string
_actions
= container
._option
_string
_actions
1525 self
._defaults
= container
._defaults
1526 self
._has
_negative
_number
_optionals
= \
1527 container
._has
_negative
_number
_optionals
1529 def _add_action(self
, action
):
1530 action
= super(_ArgumentGroup
, self
)._add
_action
(action
)
1531 self
._group
_actions
.append(action
)
1534 def _remove_action(self
, action
):
1535 super(_ArgumentGroup
, self
)._remove
_action
(action
)
1536 self
._group
_actions
.remove(action
)
1539 class _MutuallyExclusiveGroup(_ArgumentGroup
):
1541 def __init__(self
, container
, required
=False):
1542 super(_MutuallyExclusiveGroup
, self
).__init
__(container
)
1543 self
.required
= required
1544 self
._container
= container
1546 def _add_action(self
, action
):
1548 msg
= _('mutually exclusive arguments must be optional')
1549 raise ValueError(msg
)
1550 action
= self
._container
._add
_action
(action
)
1551 self
._group
_actions
.append(action
)
1554 def _remove_action(self
, action
):
1555 self
._container
._remove
_action
(action
)
1556 self
._group
_actions
.remove(action
)
1559 class ArgumentParser(_AttributeHolder
, _ActionsContainer
):
1560 """Object for parsing command line strings into Python objects.
1563 - prog -- The name of the program (default: sys.argv[0])
1564 - usage -- A usage message (default: auto-generated from arguments)
1565 - description -- A description of what the program does
1566 - epilog -- Text following the argument descriptions
1567 - parents -- Parsers whose arguments should be copied into this one
1568 - formatter_class -- HelpFormatter class for printing help messages
1569 - prefix_chars -- Characters that prefix optional arguments
1570 - fromfile_prefix_chars -- Characters that prefix files containing
1571 additional arguments
1572 - argument_default -- The default value for all arguments
1573 - conflict_handler -- String indicating how to handle conflicts
1574 - add_help -- Add a -h/-help option
1584 formatter_class
=HelpFormatter
,
1586 fromfile_prefix_chars
=None,
1587 argument_default
=None,
1588 conflict_handler
='error',
1591 if version
is not None:
1594 """The "version" argument to ArgumentParser is deprecated. """
1596 """"add_argument(..., action='version', version="N", ...)" """
1597 """instead""", DeprecationWarning)
1599 superinit
= super(ArgumentParser
, self
).__init
__
1600 superinit(description
=description
,
1601 prefix_chars
=prefix_chars
,
1602 argument_default
=argument_default
,
1603 conflict_handler
=conflict_handler
)
1605 # default setting for prog
1607 prog
= _os
.path
.basename(_sys
.argv
[0])
1611 self
.epilog
= epilog
1612 self
.version
= version
1613 self
.formatter_class
= formatter_class
1614 self
.fromfile_prefix_chars
= fromfile_prefix_chars
1615 self
.add_help
= add_help
1617 add_group
= self
.add_argument_group
1618 self
._positionals
= add_group(_('positional arguments'))
1619 self
._optionals
= add_group(_('optional arguments'))
1620 self
._subparsers
= None
1623 def identity(string
):
1625 self
.register('type', None, identity
)
1627 # add help and version arguments if necessary
1628 # (using explicit default to override global argument_default)
1629 if '-' in prefix_chars
:
1630 default_prefix
= '-'
1632 default_prefix
= prefix_chars
[0]
1635 default_prefix
+'h', default_prefix
*2+'help',
1636 action
='help', default
=SUPPRESS
,
1637 help=_('show this help message and exit'))
1640 default_prefix
+'v', default_prefix
*2+'version',
1641 action
='version', default
=SUPPRESS
,
1642 version
=self
.version
,
1643 help=_("show program's version number and exit"))
1645 # add parent arguments and defaults
1646 for parent
in parents
:
1647 self
._add
_container
_actions
(parent
)
1649 defaults
= parent
._defaults
1650 except AttributeError:
1653 self
._defaults
.update(defaults
)
1655 # =======================
1656 # Pretty __repr__ methods
1657 # =======================
1658 def _get_kwargs(self
):
1668 return [(name
, getattr(self
, name
)) for name
in names
]
1670 # ==================================
1671 # Optional/Positional adding methods
1672 # ==================================
1673 def add_subparsers(self
, **kwargs
):
1674 if self
._subparsers
is not None:
1675 self
.error(_('cannot have multiple subparser arguments'))
1677 # add the parser class to the arguments if it's not present
1678 kwargs
.setdefault('parser_class', type(self
))
1680 if 'title' in kwargs
or 'description' in kwargs
:
1681 title
= _(kwargs
.pop('title', 'subcommands'))
1682 description
= _(kwargs
.pop('description', None))
1683 self
._subparsers
= self
.add_argument_group(title
, description
)
1685 self
._subparsers
= self
._positionals
1687 # prog defaults to the usage message of this parser, skipping
1688 # optional arguments and with no "usage:" prefix
1689 if kwargs
.get('prog') is None:
1690 formatter
= self
._get
_formatter
()
1691 positionals
= self
._get
_positional
_actions
()
1692 groups
= self
._mutually
_exclusive
_groups
1693 formatter
.add_usage(self
.usage
, positionals
, groups
, '')
1694 kwargs
['prog'] = formatter
.format_help().strip()
1696 # create the parsers action and add it to the positionals list
1697 parsers_class
= self
._pop
_action
_class
(kwargs
, 'parsers')
1698 action
= parsers_class(option_strings
=[], **kwargs
)
1699 self
._subparsers
._add
_action
(action
)
1701 # return the created parsers action
1704 def _add_action(self
, action
):
1705 if action
.option_strings
:
1706 self
._optionals
._add
_action
(action
)
1708 self
._positionals
._add
_action
(action
)
1711 def _get_optional_actions(self
):
1713 for action
in self
._actions
1714 if action
.option_strings
]
1716 def _get_positional_actions(self
):
1718 for action
in self
._actions
1719 if not action
.option_strings
]
1721 # =====================================
1722 # Command line argument parsing methods
1723 # =====================================
1724 def parse_args(self
, args
=None, namespace
=None):
1725 args
, argv
= self
.parse_known_args(args
, namespace
)
1727 msg
= _('unrecognized arguments: %s')
1728 self
.error(msg
% ' '.join(argv
))
1731 def parse_known_args(self
, args
=None, namespace
=None):
1732 # args default to the system args
1734 args
= _sys
.argv
[1:]
1736 # default Namespace built from parser defaults
1737 if namespace
is None:
1738 namespace
= Namespace()
1740 # add any action defaults that aren't present
1741 for action
in self
._actions
:
1742 if action
.dest
is not SUPPRESS
:
1743 if not hasattr(namespace
, action
.dest
):
1744 if action
.default
is not SUPPRESS
:
1745 setattr(namespace
, action
.dest
, action
.default
)
1747 # add any parser defaults that aren't present
1748 for dest
in self
._defaults
:
1749 if not hasattr(namespace
, dest
):
1750 setattr(namespace
, dest
, self
._defaults
[dest
])
1752 # parse the arguments and exit if there are any errors
1754 namespace
, args
= self
._parse
_known
_args
(args
, namespace
)
1755 if hasattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
):
1756 args
.extend(getattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
))
1757 delattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
)
1758 return namespace
, args
1759 except ArgumentError
:
1760 err
= _sys
.exc_info()[1]
1761 self
.error(str(err
))
1763 def _parse_known_args(self
, arg_strings
, namespace
):
1764 # replace arg strings that are file references
1765 if self
.fromfile_prefix_chars
is not None:
1766 arg_strings
= self
._read
_args
_from
_files
(arg_strings
)
1768 # map all mutually exclusive arguments to the other arguments
1769 # they can't occur with
1770 action_conflicts
= {}
1771 for mutex_group
in self
._mutually
_exclusive
_groups
:
1772 group_actions
= mutex_group
._group
_actions
1773 for i
, mutex_action
in enumerate(mutex_group
._group
_actions
):
1774 conflicts
= action_conflicts
.setdefault(mutex_action
, [])
1775 conflicts
.extend(group_actions
[:i
])
1776 conflicts
.extend(group_actions
[i
+ 1:])
1778 # find all option indices, and determine the arg_string_pattern
1779 # which has an 'O' if there is an option at an index,
1780 # an 'A' if there is an argument, or a '-' if there is a '--'
1781 option_string_indices
= {}
1782 arg_string_pattern_parts
= []
1783 arg_strings_iter
= iter(arg_strings
)
1784 for i
, arg_string
in enumerate(arg_strings_iter
):
1786 # all args after -- are non-options
1787 if arg_string
== '--':
1788 arg_string_pattern_parts
.append('-')
1789 for arg_string
in arg_strings_iter
:
1790 arg_string_pattern_parts
.append('A')
1792 # otherwise, add the arg to the arg strings
1793 # and note the index if it was an option
1795 option_tuple
= self
._parse
_optional
(arg_string
)
1796 if option_tuple
is None:
1799 option_string_indices
[i
] = option_tuple
1801 arg_string_pattern_parts
.append(pattern
)
1803 # join the pieces together to form the pattern
1804 arg_strings_pattern
= ''.join(arg_string_pattern_parts
)
1806 # converts arg strings to the appropriate and then takes the action
1807 seen_actions
= set()
1808 seen_non_default_actions
= set()
1810 def take_action(action
, argument_strings
, option_string
=None):
1811 seen_actions
.add(action
)
1812 argument_values
= self
._get
_values
(action
, argument_strings
)
1814 # error if this argument is not allowed with other previously
1815 # seen arguments, assuming that actions that use the default
1816 # value don't really count as "present"
1817 if argument_values
is not action
.default
:
1818 seen_non_default_actions
.add(action
)
1819 for conflict_action
in action_conflicts
.get(action
, []):
1820 if conflict_action
in seen_non_default_actions
:
1821 msg
= _('not allowed with argument %s')
1822 action_name
= _get_action_name(conflict_action
)
1823 raise ArgumentError(action
, msg
% action_name
)
1825 # take the action if we didn't receive a SUPPRESS value
1826 # (e.g. from a default)
1827 if argument_values
is not SUPPRESS
:
1828 action(self
, namespace
, argument_values
, option_string
)
1830 # function to convert arg_strings into an optional action
1831 def consume_optional(start_index
):
1833 # get the optional identified at this index
1834 option_tuple
= option_string_indices
[start_index
]
1835 action
, option_string
, explicit_arg
= option_tuple
1837 # identify additional optionals in the same arg string
1838 # (e.g. -xyz is the same as -x -y -z if no args are required)
1839 match_argument
= self
._match
_argument
1843 # if we found no optional action, skip it
1845 extras
.append(arg_strings
[start_index
])
1846 return start_index
+ 1
1848 # if there is an explicit argument, try to match the
1849 # optional's string arguments to only this
1850 if explicit_arg
is not None:
1851 arg_count
= match_argument(action
, 'A')
1853 # if the action is a single-dash option and takes no
1854 # arguments, try to parse more single-dash options out
1855 # of the tail of the option string
1856 chars
= self
.prefix_chars
1857 if arg_count
== 0 and option_string
[1] not in chars
:
1858 action_tuples
.append((action
, [], option_string
))
1859 char
= option_string
[0]
1860 option_string
= char
+ explicit_arg
[0]
1861 new_explicit_arg
= explicit_arg
[1:] or None
1862 optionals_map
= self
._option
_string
_actions
1863 if option_string
in optionals_map
:
1864 action
= optionals_map
[option_string
]
1865 explicit_arg
= new_explicit_arg
1867 msg
= _('ignored explicit argument %r')
1868 raise ArgumentError(action
, msg
% explicit_arg
)
1870 # if the action expect exactly one argument, we've
1871 # successfully matched the option; exit the loop
1872 elif arg_count
== 1:
1873 stop
= start_index
+ 1
1874 args
= [explicit_arg
]
1875 action_tuples
.append((action
, args
, option_string
))
1878 # error if a double-dash option did not use the
1881 msg
= _('ignored explicit argument %r')
1882 raise ArgumentError(action
, msg
% explicit_arg
)
1884 # if there is no explicit argument, try to match the
1885 # optional's string arguments with the following strings
1886 # if successful, exit the loop
1888 start
= start_index
+ 1
1889 selected_patterns
= arg_strings_pattern
[start
:]
1890 arg_count
= match_argument(action
, selected_patterns
)
1891 stop
= start
+ arg_count
1892 args
= arg_strings
[start
:stop
]
1893 action_tuples
.append((action
, args
, option_string
))
1896 # add the Optional to the list and return the index at which
1897 # the Optional's string args stopped
1898 assert action_tuples
1899 for action
, args
, option_string
in action_tuples
:
1900 take_action(action
, args
, option_string
)
1903 # the list of Positionals left to be parsed; this is modified
1904 # by consume_positionals()
1905 positionals
= self
._get
_positional
_actions
()
1907 # function to convert arg_strings into positional actions
1908 def consume_positionals(start_index
):
1909 # match as many Positionals as possible
1910 match_partial
= self
._match
_arguments
_partial
1911 selected_pattern
= arg_strings_pattern
[start_index
:]
1912 arg_counts
= match_partial(positionals
, selected_pattern
)
1914 # slice off the appropriate arg strings for each Positional
1915 # and add the Positional and its args to the list
1916 for action
, arg_count
in zip(positionals
, arg_counts
):
1917 args
= arg_strings
[start_index
: start_index
+ arg_count
]
1918 start_index
+= arg_count
1919 take_action(action
, args
)
1921 # slice off the Positionals that we just parsed and return the
1922 # index at which the Positionals' string args stopped
1923 positionals
[:] = positionals
[len(arg_counts
):]
1926 # consume Positionals and Optionals alternately, until we have
1927 # passed the last option string
1930 if option_string_indices
:
1931 max_option_string_index
= max(option_string_indices
)
1933 max_option_string_index
= -1
1934 while start_index
<= max_option_string_index
:
1936 # consume any Positionals preceding the next option
1937 next_option_string_index
= min([
1939 for index
in option_string_indices
1940 if index
>= start_index
])
1941 if start_index
!= next_option_string_index
:
1942 positionals_end_index
= consume_positionals(start_index
)
1944 # only try to parse the next optional if we didn't consume
1945 # the option string during the positionals parsing
1946 if positionals_end_index
> start_index
:
1947 start_index
= positionals_end_index
1950 start_index
= positionals_end_index
1952 # if we consumed all the positionals we could and we're not
1953 # at the index of an option string, there were extra arguments
1954 if start_index
not in option_string_indices
:
1955 strings
= arg_strings
[start_index
:next_option_string_index
]
1956 extras
.extend(strings
)
1957 start_index
= next_option_string_index
1959 # consume the next optional and any arguments for it
1960 start_index
= consume_optional(start_index
)
1962 # consume any positionals following the last Optional
1963 stop_index
= consume_positionals(start_index
)
1965 # if we didn't consume all the argument strings, there were extras
1966 extras
.extend(arg_strings
[stop_index
:])
1968 # if we didn't use all the Positional objects, there were too few
1969 # arg strings supplied.
1971 self
.error(_('too few arguments'))
1973 # make sure all required actions were present, and convert defaults.
1974 for action
in self
._actions
:
1975 if action
not in seen_actions
:
1977 name
= _get_action_name(action
)
1978 self
.error(_('argument %s is required') % name
)
1980 # Convert action default now instead of doing it before
1981 # parsing arguments to avoid calling convert functions
1982 # twice (which may fail) if the argument was given, but
1983 # only if it was defined already in the namespace
1984 if (action
.default
is not None and
1985 isinstance(action
.default
, basestring
) and
1986 hasattr(namespace
, action
.dest
) and
1987 action
.default
is getattr(namespace
, action
.dest
)):
1988 setattr(namespace
, action
.dest
,
1989 self
._get
_value
(action
, action
.default
))
1991 # make sure all required groups had one option present
1992 for group
in self
._mutually
_exclusive
_groups
:
1994 for action
in group
._group
_actions
:
1995 if action
in seen_non_default_actions
:
1998 # if no actions were used, report the error
2000 names
= [_get_action_name(action
)
2001 for action
in group
._group
_actions
2002 if action
.help is not SUPPRESS
]
2003 msg
= _('one of the arguments %s is required')
2004 self
.error(msg
% ' '.join(names
))
2006 # return the updated namespace and the extra arguments
2007 return namespace
, extras
2009 def _read_args_from_files(self
, arg_strings
):
2010 # expand arguments referencing files
2011 new_arg_strings
= []
2012 for arg_string
in arg_strings
:
2014 # for regular arguments, just add them back into the list
2015 if arg_string
[0] not in self
.fromfile_prefix_chars
:
2016 new_arg_strings
.append(arg_string
)
2018 # replace arguments referencing files with the file content
2021 args_file
= open(arg_string
[1:])
2024 for arg_line
in args_file
.read().splitlines():
2025 for arg
in self
.convert_arg_line_to_args(arg_line
):
2026 arg_strings
.append(arg
)
2027 arg_strings
= self
._read
_args
_from
_files
(arg_strings
)
2028 new_arg_strings
.extend(arg_strings
)
2032 err
= _sys
.exc_info()[1]
2033 self
.error(str(err
))
2035 # return the modified argument list
2036 return new_arg_strings
2038 def convert_arg_line_to_args(self
, arg_line
):
2041 def _match_argument(self
, action
, arg_strings_pattern
):
2042 # match the pattern for this action to the arg strings
2043 nargs_pattern
= self
._get
_nargs
_pattern
(action
)
2044 match
= _re
.match(nargs_pattern
, arg_strings_pattern
)
2046 # raise an exception if we weren't able to find a match
2049 None: _('expected one argument'),
2050 OPTIONAL
: _('expected at most one argument'),
2051 ONE_OR_MORE
: _('expected at least one argument'),
2053 default
= _('expected %s argument(s)') % action
.nargs
2054 msg
= nargs_errors
.get(action
.nargs
, default
)
2055 raise ArgumentError(action
, msg
)
2057 # return the number of arguments matched
2058 return len(match
.group(1))
2060 def _match_arguments_partial(self
, actions
, arg_strings_pattern
):
2061 # progressively shorten the actions list by slicing off the
2062 # final actions until we find a match
2064 for i
in range(len(actions
), 0, -1):
2065 actions_slice
= actions
[:i
]
2066 pattern
= ''.join([self
._get
_nargs
_pattern
(action
)
2067 for action
in actions_slice
])
2068 match
= _re
.match(pattern
, arg_strings_pattern
)
2069 if match
is not None:
2070 result
.extend([len(string
) for string
in match
.groups()])
2073 # return the list of arg string counts
2076 def _parse_optional(self
, arg_string
):
2077 # if it's an empty string, it was meant to be a positional
2081 # if it doesn't start with a prefix, it was meant to be positional
2082 if not arg_string
[0] in self
.prefix_chars
:
2085 # if the option string is present in the parser, return the action
2086 if arg_string
in self
._option
_string
_actions
:
2087 action
= self
._option
_string
_actions
[arg_string
]
2088 return action
, arg_string
, None
2090 # if it's just a single character, it was meant to be positional
2091 if len(arg_string
) == 1:
2094 # if the option string before the "=" is present, return the action
2095 if '=' in arg_string
:
2096 option_string
, explicit_arg
= arg_string
.split('=', 1)
2097 if option_string
in self
._option
_string
_actions
:
2098 action
= self
._option
_string
_actions
[option_string
]
2099 return action
, option_string
, explicit_arg
2101 # search through all possible prefixes of the option string
2102 # and all actions in the parser for possible interpretations
2103 option_tuples
= self
._get
_option
_tuples
(arg_string
)
2105 # if multiple actions match, the option string was ambiguous
2106 if len(option_tuples
) > 1:
2107 options
= ', '.join([option_string
2108 for action
, option_string
, explicit_arg
in option_tuples
])
2109 tup
= arg_string
, options
2110 self
.error(_('ambiguous option: %s could match %s') % tup
)
2112 # if exactly one action matched, this segmentation is good,
2113 # so return the parsed action
2114 elif len(option_tuples
) == 1:
2115 option_tuple
, = option_tuples
2118 # if it was not found as an option, but it looks like a negative
2119 # number, it was meant to be positional
2120 # unless there are negative-number-like options
2121 if self
._negative
_number
_matcher
.match(arg_string
):
2122 if not self
._has
_negative
_number
_optionals
:
2125 # if it contains a space, it was meant to be a positional
2126 if ' ' in arg_string
:
2129 # it was meant to be an optional but there is no such option
2130 # in this parser (though it might be a valid option in a subparser)
2131 return None, arg_string
, None
2133 def _get_option_tuples(self
, option_string
):
2136 # option strings starting with two prefix characters are only
2138 chars
= self
.prefix_chars
2139 if option_string
[0] in chars
and option_string
[1] in chars
:
2140 if '=' in option_string
:
2141 option_prefix
, explicit_arg
= option_string
.split('=', 1)
2143 option_prefix
= option_string
2145 for option_string
in self
._option
_string
_actions
:
2146 if option_string
.startswith(option_prefix
):
2147 action
= self
._option
_string
_actions
[option_string
]
2148 tup
= action
, option_string
, explicit_arg
2151 # single character options can be concatenated with their arguments
2152 # but multiple character options always have to have their argument
2154 elif option_string
[0] in chars
and option_string
[1] not in chars
:
2155 option_prefix
= option_string
2157 short_option_prefix
= option_string
[:2]
2158 short_explicit_arg
= option_string
[2:]
2160 for option_string
in self
._option
_string
_actions
:
2161 if option_string
== short_option_prefix
:
2162 action
= self
._option
_string
_actions
[option_string
]
2163 tup
= action
, option_string
, short_explicit_arg
2165 elif option_string
.startswith(option_prefix
):
2166 action
= self
._option
_string
_actions
[option_string
]
2167 tup
= action
, option_string
, explicit_arg
2170 # shouldn't ever get here
2172 self
.error(_('unexpected option string: %s') % option_string
)
2174 # return the collected option tuples
2177 def _get_nargs_pattern(self
, action
):
2178 # in all examples below, we have to allow for '--' args
2179 # which are represented as '-' in the pattern
2180 nargs
= action
.nargs
2182 # the default (None) is assumed to be a single argument
2184 nargs_pattern
= '(-*A-*)'
2186 # allow zero or one arguments
2187 elif nargs
== OPTIONAL
:
2188 nargs_pattern
= '(-*A?-*)'
2190 # allow zero or more arguments
2191 elif nargs
== ZERO_OR_MORE
:
2192 nargs_pattern
= '(-*[A-]*)'
2194 # allow one or more arguments
2195 elif nargs
== ONE_OR_MORE
:
2196 nargs_pattern
= '(-*A[A-]*)'
2198 # allow any number of options or arguments
2199 elif nargs
== REMAINDER
:
2200 nargs_pattern
= '([-AO]*)'
2202 # allow one argument followed by any number of options or arguments
2203 elif nargs
== PARSER
:
2204 nargs_pattern
= '(-*A[-AO]*)'
2206 # all others should be integers
2208 nargs_pattern
= '(-*%s-*)' % '-*'.join('A' * nargs
)
2210 # if this is an optional action, -- is not allowed
2211 if action
.option_strings
:
2212 nargs_pattern
= nargs_pattern
.replace('-*', '')
2213 nargs_pattern
= nargs_pattern
.replace('-', '')
2215 # return the pattern
2216 return nargs_pattern
2218 # ========================
2219 # Value conversion methods
2220 # ========================
2221 def _get_values(self
, action
, arg_strings
):
2222 # for everything but PARSER args, strip out '--'
2223 if action
.nargs
not in [PARSER
, REMAINDER
]:
2224 arg_strings
= [s
for s
in arg_strings
if s
!= '--']
2226 # optional argument produces a default when not present
2227 if not arg_strings
and action
.nargs
== OPTIONAL
:
2228 if action
.option_strings
:
2229 value
= action
.const
2231 value
= action
.default
2232 if isinstance(value
, basestring
):
2233 value
= self
._get
_value
(action
, value
)
2234 self
._check
_value
(action
, value
)
2236 # when nargs='*' on a positional, if there were no command-line
2237 # args, use the default if it is anything other than None
2238 elif (not arg_strings
and action
.nargs
== ZERO_OR_MORE
and
2239 not action
.option_strings
):
2240 if action
.default
is not None:
2241 value
= action
.default
2244 self
._check
_value
(action
, value
)
2246 # single argument or optional argument produces a single value
2247 elif len(arg_strings
) == 1 and action
.nargs
in [None, OPTIONAL
]:
2248 arg_string
, = arg_strings
2249 value
= self
._get
_value
(action
, arg_string
)
2250 self
._check
_value
(action
, value
)
2252 # REMAINDER arguments convert all values, checking none
2253 elif action
.nargs
== REMAINDER
:
2254 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2256 # PARSER arguments convert all values, but check only the first
2257 elif action
.nargs
== PARSER
:
2258 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2259 self
._check
_value
(action
, value
[0])
2261 # all other types of nargs produce a list
2263 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2265 self
._check
_value
(action
, v
)
2267 # return the converted value
2270 def _get_value(self
, action
, arg_string
):
2271 type_func
= self
._registry
_get
('type', action
.type, action
.type)
2272 if not _callable(type_func
):
2273 msg
= _('%r is not callable')
2274 raise ArgumentError(action
, msg
% type_func
)
2276 # convert the value to the appropriate type
2278 result
= type_func(arg_string
)
2280 # ArgumentTypeErrors indicate errors
2281 except ArgumentTypeError
:
2282 name
= getattr(action
.type, '__name__', repr(action
.type))
2283 msg
= str(_sys
.exc_info()[1])
2284 raise ArgumentError(action
, msg
)
2286 # TypeErrors or ValueErrors also indicate errors
2287 except (TypeError, ValueError):
2288 name
= getattr(action
.type, '__name__', repr(action
.type))
2289 msg
= _('invalid %s value: %r')
2290 raise ArgumentError(action
, msg
% (name
, arg_string
))
2292 # return the converted value
2295 def _check_value(self
, action
, value
):
2296 # converted value must be one of the choices (if specified)
2297 if action
.choices
is not None and value
not in action
.choices
:
2298 tup
= value
, ', '.join(map(repr, action
.choices
))
2299 msg
= _('invalid choice: %r (choose from %s)') % tup
2300 raise ArgumentError(action
, msg
)
2302 # =======================
2303 # Help-formatting methods
2304 # =======================
2305 def format_usage(self
):
2306 formatter
= self
._get
_formatter
()
2307 formatter
.add_usage(self
.usage
, self
._actions
,
2308 self
._mutually
_exclusive
_groups
)
2309 return formatter
.format_help()
2311 def format_help(self
):
2312 formatter
= self
._get
_formatter
()
2315 formatter
.add_usage(self
.usage
, self
._actions
,
2316 self
._mutually
_exclusive
_groups
)
2319 formatter
.add_text(self
.description
)
2321 # positionals, optionals and user-defined groups
2322 for action_group
in self
._action
_groups
:
2323 formatter
.start_section(action_group
.title
)
2324 formatter
.add_text(action_group
.description
)
2325 formatter
.add_arguments(action_group
._group
_actions
)
2326 formatter
.end_section()
2329 formatter
.add_text(self
.epilog
)
2331 # determine help from format above
2332 return formatter
.format_help()
2334 def format_version(self
):
2337 'The format_version method is deprecated -- the "version" '
2338 'argument to ArgumentParser is no longer supported.',
2340 formatter
= self
._get
_formatter
()
2341 formatter
.add_text(self
.version
)
2342 return formatter
.format_help()
2344 def _get_formatter(self
):
2345 return self
.formatter_class(prog
=self
.prog
)
2347 # =====================
2348 # Help-printing methods
2349 # =====================
2350 def print_usage(self
, file=None):
2353 self
._print
_message
(self
.format_usage(), file)
2355 def print_help(self
, file=None):
2358 self
._print
_message
(self
.format_help(), file)
2360 def print_version(self
, file=None):
2363 'The print_version method is deprecated -- the "version" '
2364 'argument to ArgumentParser is no longer supported.',
2366 self
._print
_message
(self
.format_version(), file)
2368 def _print_message(self
, message
, file=None):
2377 def exit(self
, status
=0, message
=None):
2379 self
._print
_message
(message
, _sys
.stderr
)
2382 def error(self
, message
):
2383 """error(message: string)
2385 Prints a usage message incorporating the message to stderr and
2388 If you override this in a subclass, it should not return -- it
2389 should either exit or raise an exception.
2391 self
.print_usage(_sys
.stderr
)
2392 self
.exit(2, _('%s: error: %s\n') % (self
.prog
, message
))