1 # Author: Steven J. Bethard <steven.bethard@gmail.com>.
3 """Command-line parsing library
5 This module is an optparse-inspired command-line parsing library that:
7 - handles both optional and positional arguments
8 - produces highly informative usage messages
9 - supports parsers that dispatch to sub-parsers
11 The following is a simple usage example that sums integers from the
12 command-line and writes the result to a file::
14 parser = argparse.ArgumentParser(
15 description='sum the integers at the command line')
17 'integers', metavar='int', nargs='+', type=int,
18 help='an integer to be summed')
20 '--log', default=sys.stdout, type=argparse.FileType('w'),
21 help='the file where the sum should be written')
22 args = parser.parse_args()
23 args.log.write('%s' % sum(args.integers))
26 The module contains the following public classes:
28 - ArgumentParser -- The main entry point for command-line parsing. As the
29 example above shows, the add_argument() method is used to populate
30 the parser with actions for optional and positional arguments. Then
31 the parse_args() method is invoked to convert the args at the
32 command-line into an object with attributes.
34 - ArgumentError -- The exception raised by ArgumentParser objects when
35 there are errors with the parser's actions. Errors raised while
36 parsing the command-line are caught by ArgumentParser and emitted
37 as command-line messages.
39 - FileType -- A factory for defining types of files to be created. As the
40 example above shows, instances of FileType are typically passed as
41 the type= argument of add_argument() calls.
43 - Action -- The base class for parser actions. Typically actions are
44 selected by passing strings like 'store_true' or 'append_const' to
45 the action= argument of add_argument(). However, for greater
46 customization of ArgumentParser actions, subclasses of Action may
47 be defined and passed as the action= argument.
49 - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
50 ArgumentDefaultsHelpFormatter -- Formatter classes which
51 may be passed as the formatter_class= argument to the
52 ArgumentParser constructor. HelpFormatter is the default,
53 RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
54 not to change the formatting for help text, and
55 ArgumentDefaultsHelpFormatter adds information about argument defaults
58 All other classes in this module are considered implementation details.
59 (Also note that HelpFormatter and RawDescriptionHelpFormatter are only
60 considered public as object names -- the API of the formatter objects is
61 still considered an implementation detail.)
71 'ArgumentDefaultsHelpFormatter',
72 'RawDescriptionHelpFormatter',
73 'RawTextHelpFormatter',
85 import collections
as _collections
90 import textwrap
as _textwrap
92 from gettext
import gettext
as _
96 return hasattr(obj
, '__call__') or hasattr(obj
, '__bases__')
99 SUPPRESS
= '==SUPPRESS=='
106 _UNRECOGNIZED_ARGS_ATTR
= '_unrecognized_args'
108 # =============================
109 # Utility functions and classes
110 # =============================
112 class _AttributeHolder(object):
113 """Abstract base class that provides __repr__.
115 The __repr__ method returns a string in the format::
116 ClassName(attr=name, attr=name, ...)
117 The attributes are determined either by a class-level attribute,
118 '_kwarg_names', or by inspecting the instance __dict__.
122 type_name
= type(self
).__name
__
124 for arg
in self
._get
_args
():
125 arg_strings
.append(repr(arg
))
126 for name
, value
in self
._get
_kwargs
():
127 arg_strings
.append('%s=%r' % (name
, value
))
128 return '%s(%s)' % (type_name
, ', '.join(arg_strings
))
130 def _get_kwargs(self
):
131 return sorted(self
.__dict
__.items())
137 def _ensure_value(namespace
, name
, value
):
138 if getattr(namespace
, name
, None) is None:
139 setattr(namespace
, name
, value
)
140 return getattr(namespace
, name
)
147 class HelpFormatter(object):
148 """Formatter for generating usage messages and argument help strings.
150 Only the name of this class is considered a public API. All the methods
151 provided by the class are considered an implementation detail.
157 max_help_position
=24,
160 # default setting for width
163 width
= int(_os
.environ
['COLUMNS'])
164 except (KeyError, ValueError):
169 self
._indent
_increment
= indent_increment
170 self
._max
_help
_position
= max_help_position
171 self
._max
_help
_position
= min(max_help_position
,
172 max(width
- 20, indent_increment
* 2))
175 self
._current
_indent
= 0
177 self
._action
_max
_length
= 0
179 self
._root
_section
= self
._Section
(self
, None)
180 self
._current
_section
= self
._root
_section
182 self
._whitespace
_matcher
= _re
.compile(r
'\s+')
183 self
._long
_break
_matcher
= _re
.compile(r
'\n\n\n+')
185 # ===============================
186 # Section and indentation methods
187 # ===============================
189 self
._current
_indent
+= self
._indent
_increment
193 self
._current
_indent
-= self
._indent
_increment
194 assert self
._current
_indent
>= 0, 'Indent decreased below 0.'
197 class _Section(object):
199 def __init__(self
, formatter
, parent
, heading
=None):
200 self
.formatter
= formatter
202 self
.heading
= heading
205 def format_help(self
):
206 # format the indented section
207 if self
.parent
is not None:
208 self
.formatter
._indent
()
209 join
= self
.formatter
._join
_parts
210 for func
, args
in self
.items
:
212 item_help
= join([func(*args
) for func
, args
in self
.items
])
213 if self
.parent
is not None:
214 self
.formatter
._dedent
()
216 # return nothing if the section was empty
220 # add the heading if the section was non-empty
221 if self
.heading
is not SUPPRESS
and self
.heading
is not None:
222 current_indent
= self
.formatter
._current
_indent
223 heading
= '%*s%s:\n' % (current_indent
, '', self
.heading
)
227 # join the section-initial newline, the heading and the help
228 return join(['\n', heading
, item_help
, '\n'])
230 def _add_item(self
, func
, args
):
231 self
._current
_section
.items
.append((func
, args
))
233 # ========================
234 # Message building methods
235 # ========================
236 def start_section(self
, heading
):
238 section
= self
._Section
(self
, self
._current
_section
, heading
)
239 self
._add
_item
(section
.format_help
, [])
240 self
._current
_section
= section
242 def end_section(self
):
243 self
._current
_section
= self
._current
_section
.parent
246 def add_text(self
, text
):
247 if text
is not SUPPRESS
and text
is not None:
248 self
._add
_item
(self
._format
_text
, [text
])
250 def add_usage(self
, usage
, actions
, groups
, prefix
=None):
251 if usage
is not SUPPRESS
:
252 args
= usage
, actions
, groups
, prefix
253 self
._add
_item
(self
._format
_usage
, args
)
255 def add_argument(self
, action
):
256 if action
.help is not SUPPRESS
:
258 # find all invocations
259 get_invocation
= self
._format
_action
_invocation
260 invocations
= [get_invocation(action
)]
261 for subaction
in self
._iter
_indented
_subactions
(action
):
262 invocations
.append(get_invocation(subaction
))
264 # update the maximum item length
265 invocation_length
= max([len(s
) for s
in invocations
])
266 action_length
= invocation_length
+ self
._current
_indent
267 self
._action
_max
_length
= max(self
._action
_max
_length
,
270 # add the item to the list
271 self
._add
_item
(self
._format
_action
, [action
])
273 def add_arguments(self
, actions
):
274 for action
in actions
:
275 self
.add_argument(action
)
277 # =======================
278 # Help-formatting methods
279 # =======================
280 def format_help(self
):
281 help = self
._root
_section
.format_help()
283 help = self
._long
_break
_matcher
.sub('\n\n', help)
284 help = help.strip('\n') + '\n'
287 def _join_parts(self
, part_strings
):
289 for part
in part_strings
290 if part
and part
is not SUPPRESS
])
292 def _format_usage(self
, usage
, actions
, groups
, prefix
):
294 prefix
= _('usage: ')
296 # if usage is specified, use that
297 if usage
is not None:
298 usage
= usage
% dict(prog
=self
._prog
)
300 # if no optionals or positionals are available, usage is just prog
301 elif usage
is None and not actions
:
302 usage
= '%(prog)s' % dict(prog
=self
._prog
)
304 # if optionals and positionals are available, calculate usage
306 prog
= '%(prog)s' % dict(prog
=self
._prog
)
308 # split optionals from positionals
311 for action
in actions
:
312 if action
.option_strings
:
313 optionals
.append(action
)
315 positionals
.append(action
)
317 # build full usage string
318 format
= self
._format
_actions
_usage
319 action_usage
= format(optionals
+ positionals
, groups
)
320 usage
= ' '.join([s
for s
in [prog
, action_usage
] if s
])
322 # wrap the usage parts if it's too long
323 text_width
= self
._width
- self
._current
_indent
324 if len(prefix
) + len(usage
) > text_width
:
326 # break usage into wrappable parts
327 part_regexp
= r
'\(.*?\)+|\[.*?\]+|\S+'
328 opt_usage
= format(optionals
, groups
)
329 pos_usage
= format(positionals
, groups
)
330 opt_parts
= _re
.findall(part_regexp
, opt_usage
)
331 pos_parts
= _re
.findall(part_regexp
, pos_usage
)
332 assert ' '.join(opt_parts
) == opt_usage
333 assert ' '.join(pos_parts
) == pos_usage
335 # helper for wrapping lines
336 def get_lines(parts
, indent
, prefix
=None):
339 if prefix
is not None:
340 line_len
= len(prefix
) - 1
342 line_len
= len(indent
) - 1
344 if line_len
+ 1 + len(part
) > text_width
and line
:
345 lines
.append(indent
+ ' '.join(line
))
347 line_len
= len(indent
) - 1
349 line_len
+= len(part
) + 1
351 lines
.append(indent
+ ' '.join(line
))
352 if prefix
is not None:
353 lines
[0] = lines
[0][len(indent
):]
356 # if prog is short, follow it with optionals or positionals
357 if len(prefix
) + len(prog
) <= 0.75 * text_width
:
358 indent
= ' ' * (len(prefix
) + len(prog
) + 1)
360 lines
= get_lines([prog
] + opt_parts
, indent
, prefix
)
361 lines
.extend(get_lines(pos_parts
, indent
))
363 lines
= get_lines([prog
] + pos_parts
, indent
, prefix
)
367 # if prog is long, put it on its own line
369 indent
= ' ' * len(prefix
)
370 parts
= opt_parts
+ pos_parts
371 lines
= get_lines(parts
, indent
)
374 lines
.extend(get_lines(opt_parts
, indent
))
375 lines
.extend(get_lines(pos_parts
, indent
))
376 lines
= [prog
] + lines
378 # join lines into usage
379 usage
= '\n'.join(lines
)
381 # prefix with 'usage:'
382 return '%s%s\n\n' % (prefix
, usage
)
384 def _format_actions_usage(self
, actions
, groups
):
385 # find group indices and identify actions in groups
386 group_actions
= set()
390 start
= actions
.index(group
._group
_actions
[0])
394 end
= start
+ len(group
._group
_actions
)
395 if actions
[start
:end
] == group
._group
_actions
:
396 for action
in group
._group
_actions
:
397 group_actions
.add(action
)
398 if not group
.required
:
400 inserts
[start
] += ' ['
406 inserts
[start
] += ' ('
410 for i
in range(start
+ 1, end
):
413 # collect all actions format strings
415 for i
, action
in enumerate(actions
):
417 # suppressed arguments are marked with None
418 # remove | separators for suppressed arguments
419 if action
.help is SUPPRESS
:
421 if inserts
.get(i
) == '|':
423 elif inserts
.get(i
+ 1) == '|':
426 # produce all arg strings
427 elif not action
.option_strings
:
428 part
= self
._format
_args
(action
, action
.dest
)
430 # if it's in a group, strip the outer []
431 if action
in group_actions
:
432 if part
[0] == '[' and part
[-1] == ']':
435 # add the action string to the list
438 # produce the first way to invoke the option in brackets
440 option_string
= action
.option_strings
[0]
442 # if the Optional doesn't take a value, format is:
444 if action
.nargs
== 0:
445 part
= '%s' % option_string
447 # if the Optional takes a value, format is:
448 # -s ARGS or --long ARGS
450 default
= action
.dest
.upper()
451 args_string
= self
._format
_args
(action
, default
)
452 part
= '%s %s' % (option_string
, args_string
)
454 # make it look optional if it's not required or in a group
455 if not action
.required
and action
not in group_actions
:
458 # add the action string to the list
461 # insert things at the necessary indices
462 for i
in sorted(inserts
, reverse
=True):
463 parts
[i
:i
] = [inserts
[i
]]
465 # join all the action items with spaces
466 text
= ' '.join([item
for item
in parts
if item
is not None])
468 # clean up separators for mutually exclusive groups
471 text
= _re
.sub(r
'(%s) ' % open, r
'\1', text
)
472 text
= _re
.sub(r
' (%s)' % close
, r
'\1', text
)
473 text
= _re
.sub(r
'%s *%s' % (open, close
), r
'', text
)
474 text
= _re
.sub(r
'\(([^|]*)\)', r
'\1', text
)
480 def _format_text(self
, text
):
481 if '%(prog)' in text
:
482 text
= text
% dict(prog
=self
._prog
)
483 text_width
= max(self
._width
- self
._current
_indent
, 11)
484 indent
= ' ' * self
._current
_indent
485 return self
._fill
_text
(text
, text_width
, indent
) + '\n\n'
487 def _format_action(self
, action
):
488 # determine the required width and the entry label
489 help_position
= min(self
._action
_max
_length
+ 2,
490 self
._max
_help
_position
)
491 help_width
= max(self
._width
- help_position
, 11)
492 action_width
= help_position
- self
._current
_indent
- 2
493 action_header
= self
._format
_action
_invocation
(action
)
495 # ho nelp; start on same line and add a final newline
497 tup
= self
._current
_indent
, '', action_header
498 action_header
= '%*s%s\n' % tup
500 # short action name; start on the same line and pad two spaces
501 elif len(action_header
) <= action_width
:
502 tup
= self
._current
_indent
, '', action_width
, action_header
503 action_header
= '%*s%-*s ' % tup
506 # long action name; start on the next line
508 tup
= self
._current
_indent
, '', action_header
509 action_header
= '%*s%s\n' % tup
510 indent_first
= help_position
512 # collect the pieces of the action help
513 parts
= [action_header
]
515 # if there was help for the action, add lines of help text
517 help_text
= self
._expand
_help
(action
)
518 help_lines
= self
._split
_lines
(help_text
, help_width
)
519 parts
.append('%*s%s\n' % (indent_first
, '', help_lines
[0]))
520 for line
in help_lines
[1:]:
521 parts
.append('%*s%s\n' % (help_position
, '', line
))
523 # or add a newline if the description doesn't end with one
524 elif not action_header
.endswith('\n'):
527 # if there are any sub-actions, add their help as well
528 for subaction
in self
._iter
_indented
_subactions
(action
):
529 parts
.append(self
._format
_action
(subaction
))
531 # return a single string
532 return self
._join
_parts
(parts
)
534 def _format_action_invocation(self
, action
):
535 if not action
.option_strings
:
536 metavar
, = self
._metavar
_formatter
(action
, action
.dest
)(1)
542 # if the Optional doesn't take a value, format is:
544 if action
.nargs
== 0:
545 parts
.extend(action
.option_strings
)
547 # if the Optional takes a value, format is:
548 # -s ARGS, --long ARGS
550 default
= action
.dest
.upper()
551 args_string
= self
._format
_args
(action
, default
)
552 for option_string
in action
.option_strings
:
553 parts
.append('%s %s' % (option_string
, args_string
))
555 return ', '.join(parts
)
557 def _metavar_formatter(self
, action
, default_metavar
):
558 if action
.metavar
is not None:
559 result
= action
.metavar
560 elif action
.choices
is not None:
561 choice_strs
= [str(choice
) for choice
in action
.choices
]
562 result
= '{%s}' % ','.join(choice_strs
)
564 result
= default_metavar
566 def format(tuple_size
):
567 if isinstance(result
, tuple):
570 return (result
, ) * tuple_size
573 def _format_args(self
, action
, default_metavar
):
574 get_metavar
= self
._metavar
_formatter
(action
, default_metavar
)
575 if action
.nargs
is None:
576 result
= '%s' % get_metavar(1)
577 elif action
.nargs
== OPTIONAL
:
578 result
= '[%s]' % get_metavar(1)
579 elif action
.nargs
== ZERO_OR_MORE
:
580 result
= '[%s [%s ...]]' % get_metavar(2)
581 elif action
.nargs
== ONE_OR_MORE
:
582 result
= '%s [%s ...]' % get_metavar(2)
583 elif action
.nargs
== REMAINDER
:
585 elif action
.nargs
== PARSER
:
586 result
= '%s ...' % get_metavar(1)
588 formats
= ['%s' for _
in range(action
.nargs
)]
589 result
= ' '.join(formats
) % get_metavar(action
.nargs
)
592 def _expand_help(self
, action
):
593 params
= dict(vars(action
), prog
=self
._prog
)
594 for name
in list(params
):
595 if params
[name
] is SUPPRESS
:
597 for name
in list(params
):
598 if hasattr(params
[name
], '__name__'):
599 params
[name
] = params
[name
].__name
__
600 if params
.get('choices') is not None:
601 choices_str
= ', '.join([str(c
) for c
in params
['choices']])
602 params
['choices'] = choices_str
603 return self
._get
_help
_string
(action
) % params
605 def _iter_indented_subactions(self
, action
):
607 get_subactions
= action
._get
_subactions
608 except AttributeError:
612 for subaction
in get_subactions():
616 def _split_lines(self
, text
, width
):
617 text
= self
._whitespace
_matcher
.sub(' ', text
).strip()
618 return _textwrap
.wrap(text
, width
)
620 def _fill_text(self
, text
, width
, indent
):
621 text
= self
._whitespace
_matcher
.sub(' ', text
).strip()
622 return _textwrap
.fill(text
, width
, initial_indent
=indent
,
623 subsequent_indent
=indent
)
625 def _get_help_string(self
, action
):
629 class RawDescriptionHelpFormatter(HelpFormatter
):
630 """Help message formatter which retains any formatting in descriptions.
632 Only the name of this class is considered a public API. All the methods
633 provided by the class are considered an implementation detail.
636 def _fill_text(self
, text
, width
, indent
):
637 return ''.join([indent
+ line
for line
in text
.splitlines(True)])
640 class RawTextHelpFormatter(RawDescriptionHelpFormatter
):
641 """Help message formatter which retains formatting of all help text.
643 Only the name of this class is considered a public API. All the methods
644 provided by the class are considered an implementation detail.
647 def _split_lines(self
, text
, width
):
648 return text
.splitlines()
651 class ArgumentDefaultsHelpFormatter(HelpFormatter
):
652 """Help message formatter which adds default values to argument help.
654 Only the name of this class is considered a public API. All the methods
655 provided by the class are considered an implementation detail.
658 def _get_help_string(self
, action
):
660 if '%(default)' not in action
.help:
661 if action
.default
is not SUPPRESS
:
662 defaulting_nargs
= [OPTIONAL
, ZERO_OR_MORE
]
663 if action
.option_strings
or action
.nargs
in defaulting_nargs
:
664 help += ' (default: %(default)s)'
668 # =====================
669 # Options and Arguments
670 # =====================
672 def _get_action_name(argument
):
675 elif argument
.option_strings
:
676 return '/'.join(argument
.option_strings
)
677 elif argument
.metavar
not in (None, SUPPRESS
):
678 return argument
.metavar
679 elif argument
.dest
not in (None, SUPPRESS
):
685 class ArgumentError(Exception):
686 """An error from creating or using an argument (optional or positional).
688 The string value of this exception is the message, augmented with
689 information about the argument that caused it.
692 def __init__(self
, argument
, message
):
693 self
.argument_name
= _get_action_name(argument
)
694 self
.message
= message
697 if self
.argument_name
is None:
698 format
= '%(message)s'
700 format
= 'argument %(argument_name)s: %(message)s'
701 return format
% dict(message
=self
.message
,
702 argument_name
=self
.argument_name
)
705 class ArgumentTypeError(Exception):
706 """An error from trying to convert a command line string to a type."""
714 class Action(_AttributeHolder
):
715 """Information about how to convert command line strings to Python objects.
717 Action objects are used by an ArgumentParser to represent the information
718 needed to parse a single argument from one or more strings from the
719 command line. The keyword arguments to the Action constructor are also
720 all attributes of Action instances.
724 - option_strings -- A list of command-line option strings which
725 should be associated with this action.
727 - dest -- The name of the attribute to hold the created object(s)
729 - nargs -- The number of command-line arguments that should be
730 consumed. By default, one argument will be consumed and a single
731 value will be produced. Other values include:
732 - N (an integer) consumes N arguments (and produces a list)
733 - '?' consumes zero or one arguments
734 - '*' consumes zero or more arguments (and produces a list)
735 - '+' consumes one or more arguments (and produces a list)
736 Note that the difference between the default and nargs=1 is that
737 with the default, a single value will be produced, while with
738 nargs=1, a list containing a single value will be produced.
740 - const -- The value to be produced if the option is specified and the
741 option uses an action that takes no values.
743 - default -- The value to be produced if the option is not specified.
745 - type -- A callable that accepts a single string argument, and
746 returns the converted value. The standard Python types str, int,
747 float, and complex are useful examples of such callables. If None,
750 - choices -- A container of values that should be allowed. If not None,
751 after a command-line argument has been converted to the appropriate
752 type, an exception will be raised if it is not a member of this
755 - required -- True if the action must always be specified at the
756 command line. This is only meaningful for optional command-line
759 - help -- The help string describing the argument.
761 - metavar -- The name to be used for the option's argument with the
762 help string. If None, the 'dest' value will be used as the name.
776 self
.option_strings
= option_strings
780 self
.default
= default
782 self
.choices
= choices
783 self
.required
= required
785 self
.metavar
= metavar
787 def _get_kwargs(self
):
799 return [(name
, getattr(self
, name
)) for name
in names
]
801 def __call__(self
, parser
, namespace
, values
, option_string
=None):
802 raise NotImplementedError(_('.__call__() not defined'))
805 class _StoreAction(Action
):
819 raise ValueError('nargs for store actions must be > 0; if you '
820 'have nothing to store, actions such as store '
821 'true or store const may be more appropriate')
822 if const
is not None and nargs
!= OPTIONAL
:
823 raise ValueError('nargs must be %r to supply const' % OPTIONAL
)
824 super(_StoreAction
, self
).__init
__(
825 option_strings
=option_strings
,
836 def __call__(self
, parser
, namespace
, values
, option_string
=None):
837 setattr(namespace
, self
.dest
, values
)
840 class _StoreConstAction(Action
):
850 super(_StoreConstAction
, self
).__init
__(
851 option_strings
=option_strings
,
859 def __call__(self
, parser
, namespace
, values
, option_string
=None):
860 setattr(namespace
, self
.dest
, self
.const
)
863 class _StoreTrueAction(_StoreConstAction
):
871 super(_StoreTrueAction
, self
).__init
__(
872 option_strings
=option_strings
,
880 class _StoreFalseAction(_StoreConstAction
):
888 super(_StoreFalseAction
, self
).__init
__(
889 option_strings
=option_strings
,
897 class _AppendAction(Action
):
911 raise ValueError('nargs for append actions must be > 0; if arg '
912 'strings are not supplying the value to append, '
913 'the append const action may be more appropriate')
914 if const
is not None and nargs
!= OPTIONAL
:
915 raise ValueError('nargs must be %r to supply const' % OPTIONAL
)
916 super(_AppendAction
, self
).__init
__(
917 option_strings
=option_strings
,
928 def __call__(self
, parser
, namespace
, values
, option_string
=None):
929 items
= _copy
.copy(_ensure_value(namespace
, self
.dest
, []))
931 setattr(namespace
, self
.dest
, items
)
934 class _AppendConstAction(Action
):
944 super(_AppendConstAction
, self
).__init
__(
945 option_strings
=option_strings
,
954 def __call__(self
, parser
, namespace
, values
, option_string
=None):
955 items
= _copy
.copy(_ensure_value(namespace
, self
.dest
, []))
956 items
.append(self
.const
)
957 setattr(namespace
, self
.dest
, items
)
960 class _CountAction(Action
):
968 super(_CountAction
, self
).__init
__(
969 option_strings
=option_strings
,
976 def __call__(self
, parser
, namespace
, values
, option_string
=None):
977 new_count
= _ensure_value(namespace
, self
.dest
, 0) + 1
978 setattr(namespace
, self
.dest
, new_count
)
981 class _HelpAction(Action
):
988 super(_HelpAction
, self
).__init
__(
989 option_strings
=option_strings
,
995 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1000 class _VersionAction(Action
):
1007 help="show program's version number and exit"):
1008 super(_VersionAction
, self
).__init
__(
1009 option_strings
=option_strings
,
1014 self
.version
= version
1016 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1017 version
= self
.version
1019 version
= parser
.version
1020 formatter
= parser
._get
_formatter
()
1021 formatter
.add_text(version
)
1022 parser
.exit(message
=formatter
.format_help())
1025 class _SubParsersAction(Action
):
1027 class _ChoicesPseudoAction(Action
):
1029 def __init__(self
, name
, help):
1030 sup
= super(_SubParsersAction
._ChoicesPseudoAction
, self
)
1031 sup
.__init
__(option_strings
=[], dest
=name
, help=help)
1041 self
._prog
_prefix
= prog
1042 self
._parser
_class
= parser_class
1043 self
._name
_parser
_map
= _collections
.OrderedDict()
1044 self
._choices
_actions
= []
1046 super(_SubParsersAction
, self
).__init
__(
1047 option_strings
=option_strings
,
1050 choices
=self
._name
_parser
_map
,
1054 def add_parser(self
, name
, **kwargs
):
1055 # set prog from the existing prefix
1056 if kwargs
.get('prog') is None:
1057 kwargs
['prog'] = '%s %s' % (self
._prog
_prefix
, name
)
1059 # create a pseudo-action to hold the choice help
1060 if 'help' in kwargs
:
1061 help = kwargs
.pop('help')
1062 choice_action
= self
._ChoicesPseudoAction
(name
, help)
1063 self
._choices
_actions
.append(choice_action
)
1065 # create the parser and add it to the map
1066 parser
= self
._parser
_class
(**kwargs
)
1067 self
._name
_parser
_map
[name
] = parser
1070 def _get_subactions(self
):
1071 return self
._choices
_actions
1073 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1074 parser_name
= values
[0]
1075 arg_strings
= values
[1:]
1077 # set the parser name if requested
1078 if self
.dest
is not SUPPRESS
:
1079 setattr(namespace
, self
.dest
, parser_name
)
1083 parser
= self
._name
_parser
_map
[parser_name
]
1085 tup
= parser_name
, ', '.join(self
._name
_parser
_map
)
1086 msg
= _('unknown parser %r (choices: %s)') % tup
1087 raise ArgumentError(self
, msg
)
1089 # parse all the remaining options into the namespace
1090 # store any unrecognized options on the object, so that the top
1091 # level parser can decide what to do with them
1093 # In case this subparser defines new defaults, we parse them
1094 # in a new namespace object and then update the original
1095 # namespace for the relevant parts.
1096 subnamespace
, arg_strings
= parser
.parse_known_args(arg_strings
, None)
1097 for key
, value
in vars(subnamespace
).items():
1098 setattr(namespace
, key
, value
)
1101 vars(namespace
).setdefault(_UNRECOGNIZED_ARGS_ATTR
, [])
1102 getattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
).extend(arg_strings
)
1109 class FileType(object):
1110 """Factory for creating file object types
1112 Instances of FileType are typically passed as type= arguments to the
1113 ArgumentParser add_argument() method.
1116 - mode -- A string indicating how the file is to be opened. Accepts the
1117 same values as the builtin open() function.
1118 - bufsize -- The file's desired buffer size. Accepts the same values as
1119 the builtin open() function.
1122 def __init__(self
, mode
='r', bufsize
=-1):
1124 self
._bufsize
= bufsize
1126 def __call__(self
, string
):
1127 # the special argument "-" means sys.std{in,out}
1129 if 'r' in self
._mode
:
1131 elif 'w' in self
._mode
:
1134 msg
= _('argument "-" with mode %r') % self
._mode
1135 raise ValueError(msg
)
1137 # all other arguments are used as file names
1139 return open(string
, self
._mode
, self
._bufsize
)
1140 except IOError as e
:
1141 message
= _("can't open '%s': %s")
1142 raise ArgumentTypeError(message
% (string
, e
))
1145 args
= self
._mode
, self
._bufsize
1146 args_str
= ', '.join(repr(arg
) for arg
in args
if arg
!= -1)
1147 return '%s(%s)' % (type(self
).__name
__, args_str
)
1149 # ===========================
1150 # Optional and Positional Parsing
1151 # ===========================
1153 class Namespace(_AttributeHolder
):
1154 """Simple object for storing attributes.
1156 Implements equality by attribute names and values, and provides a simple
1157 string representation.
1160 def __init__(self
, **kwargs
):
1162 setattr(self
, name
, kwargs
[name
])
1166 def __eq__(self
, other
):
1167 if not isinstance(other
, Namespace
):
1168 return NotImplemented
1169 return vars(self
) == vars(other
)
1171 def __ne__(self
, other
):
1172 if not isinstance(other
, Namespace
):
1173 return NotImplemented
1174 return not (self
== other
)
1176 def __contains__(self
, key
):
1177 return key
in self
.__dict
__
1180 class _ActionsContainer(object):
1187 super(_ActionsContainer
, self
).__init
__()
1189 self
.description
= description
1190 self
.argument_default
= argument_default
1191 self
.prefix_chars
= prefix_chars
1192 self
.conflict_handler
= conflict_handler
1195 self
._registries
= {}
1198 self
.register('action', None, _StoreAction
)
1199 self
.register('action', 'store', _StoreAction
)
1200 self
.register('action', 'store_const', _StoreConstAction
)
1201 self
.register('action', 'store_true', _StoreTrueAction
)
1202 self
.register('action', 'store_false', _StoreFalseAction
)
1203 self
.register('action', 'append', _AppendAction
)
1204 self
.register('action', 'append_const', _AppendConstAction
)
1205 self
.register('action', 'count', _CountAction
)
1206 self
.register('action', 'help', _HelpAction
)
1207 self
.register('action', 'version', _VersionAction
)
1208 self
.register('action', 'parsers', _SubParsersAction
)
1210 # raise an exception if the conflict handler is invalid
1215 self
._option
_string
_actions
= {}
1218 self
._action
_groups
= []
1219 self
._mutually
_exclusive
_groups
= []
1224 # determines whether an "option" looks like a negative number
1225 self
._negative
_number
_matcher
= _re
.compile(r
'^-\d+$|^-\d*\.\d+$')
1227 # whether or not there are any optionals that look like negative
1228 # numbers -- uses a list so it can be shared and edited
1229 self
._has
_negative
_number
_optionals
= []
1231 # ====================
1232 # Registration methods
1233 # ====================
1234 def register(self
, registry_name
, value
, object):
1235 registry
= self
._registries
.setdefault(registry_name
, {})
1236 registry
[value
] = object
1238 def _registry_get(self
, registry_name
, value
, default
=None):
1239 return self
._registries
[registry_name
].get(value
, default
)
1241 # ==================================
1242 # Namespace default accessor methods
1243 # ==================================
1244 def set_defaults(self
, **kwargs
):
1245 self
._defaults
.update(kwargs
)
1247 # if these defaults match any existing arguments, replace
1248 # the previous default on the object with the new one
1249 for action
in self
._actions
:
1250 if action
.dest
in kwargs
:
1251 action
.default
= kwargs
[action
.dest
]
1253 def get_default(self
, dest
):
1254 for action
in self
._actions
:
1255 if action
.dest
== dest
and action
.default
is not None:
1256 return action
.default
1257 return self
._defaults
.get(dest
, None)
1260 # =======================
1261 # Adding argument actions
1262 # =======================
1263 def add_argument(self
, *args
, **kwargs
):
1265 add_argument(dest, ..., name=value, ...)
1266 add_argument(option_string, option_string, ..., name=value, ...)
1269 # if no positional args are supplied or only one is supplied and
1270 # it doesn't look like an option string, parse a positional
1272 chars
= self
.prefix_chars
1273 if not args
or len(args
) == 1 and args
[0][0] not in chars
:
1274 if args
and 'dest' in kwargs
:
1275 raise ValueError('dest supplied twice for positional argument')
1276 kwargs
= self
._get
_positional
_kwargs
(*args
, **kwargs
)
1278 # otherwise, we're adding an optional argument
1280 kwargs
= self
._get
_optional
_kwargs
(*args
, **kwargs
)
1282 # if no default was supplied, use the parser-level default
1283 if 'default' not in kwargs
:
1284 dest
= kwargs
['dest']
1285 if dest
in self
._defaults
:
1286 kwargs
['default'] = self
._defaults
[dest
]
1287 elif self
.argument_default
is not None:
1288 kwargs
['default'] = self
.argument_default
1290 # create the action object, and add it to the parser
1291 action_class
= self
._pop
_action
_class
(kwargs
)
1292 if not _callable(action_class
):
1293 raise ValueError('unknown action "%s"' % (action_class
,))
1294 action
= action_class(**kwargs
)
1296 # raise an error if the action type is not callable
1297 type_func
= self
._registry
_get
('type', action
.type, action
.type)
1298 if not _callable(type_func
):
1299 raise ValueError('%r is not callable' % (type_func
,))
1301 # raise an error if the metavar does not match the type
1302 if hasattr(self
, "_get_formatter"):
1304 self
._get
_formatter
()._format
_args
(action
, None)
1306 raise ValueError("length of metavar tuple does not match nargs")
1308 return self
._add
_action
(action
)
1310 def add_argument_group(self
, *args
, **kwargs
):
1311 group
= _ArgumentGroup(self
, *args
, **kwargs
)
1312 self
._action
_groups
.append(group
)
1315 def add_mutually_exclusive_group(self
, **kwargs
):
1316 group
= _MutuallyExclusiveGroup(self
, **kwargs
)
1317 self
._mutually
_exclusive
_groups
.append(group
)
1320 def _add_action(self
, action
):
1321 # resolve any conflicts
1322 self
._check
_conflict
(action
)
1324 # add to actions list
1325 self
._actions
.append(action
)
1326 action
.container
= self
1328 # index the action by any option strings it has
1329 for option_string
in action
.option_strings
:
1330 self
._option
_string
_actions
[option_string
] = action
1332 # set the flag if any option strings look like negative numbers
1333 for option_string
in action
.option_strings
:
1334 if self
._negative
_number
_matcher
.match(option_string
):
1335 if not self
._has
_negative
_number
_optionals
:
1336 self
._has
_negative
_number
_optionals
.append(True)
1338 # return the created action
1341 def _remove_action(self
, action
):
1342 self
._actions
.remove(action
)
1344 def _add_container_actions(self
, container
):
1345 # collect groups by titles
1346 title_group_map
= {}
1347 for group
in self
._action
_groups
:
1348 if group
.title
in title_group_map
:
1349 msg
= _('cannot merge actions - two groups are named %r')
1350 raise ValueError(msg
% (group
.title
))
1351 title_group_map
[group
.title
] = group
1353 # map each action to its group
1355 for group
in container
._action
_groups
:
1357 # if a group with the title exists, use that, otherwise
1358 # create a new group matching the container's group
1359 if group
.title
not in title_group_map
:
1360 title_group_map
[group
.title
] = self
.add_argument_group(
1362 description
=group
.description
,
1363 conflict_handler
=group
.conflict_handler
)
1365 # map the actions to their new group
1366 for action
in group
._group
_actions
:
1367 group_map
[action
] = title_group_map
[group
.title
]
1369 # add container's mutually exclusive groups
1370 # NOTE: if add_mutually_exclusive_group ever gains title= and
1371 # description= then this code will need to be expanded as above
1372 for group
in container
._mutually
_exclusive
_groups
:
1373 mutex_group
= self
.add_mutually_exclusive_group(
1374 required
=group
.required
)
1376 # map the actions to their new mutex group
1377 for action
in group
._group
_actions
:
1378 group_map
[action
] = mutex_group
1380 # add all actions to this container or their group
1381 for action
in container
._actions
:
1382 group_map
.get(action
, self
)._add
_action
(action
)
1384 def _get_positional_kwargs(self
, dest
, **kwargs
):
1385 # make sure required is not specified
1386 if 'required' in kwargs
:
1387 msg
= _("'required' is an invalid argument for positionals")
1388 raise TypeError(msg
)
1390 # mark positional arguments as required if at least one is
1392 if kwargs
.get('nargs') not in [OPTIONAL
, ZERO_OR_MORE
]:
1393 kwargs
['required'] = True
1394 if kwargs
.get('nargs') == ZERO_OR_MORE
and 'default' not in kwargs
:
1395 kwargs
['required'] = True
1397 # return the keyword arguments with no option strings
1398 return dict(kwargs
, dest
=dest
, option_strings
=[])
1400 def _get_optional_kwargs(self
, *args
, **kwargs
):
1401 # determine short and long option strings
1403 long_option_strings
= []
1404 for option_string
in args
:
1405 # error on strings that don't start with an appropriate prefix
1406 if not option_string
[0] in self
.prefix_chars
:
1407 msg
= _('invalid option string %r: '
1408 'must start with a character %r')
1409 tup
= option_string
, self
.prefix_chars
1410 raise ValueError(msg
% tup
)
1412 # strings starting with two prefix characters are long options
1413 option_strings
.append(option_string
)
1414 if option_string
[0] in self
.prefix_chars
:
1415 if len(option_string
) > 1:
1416 if option_string
[1] in self
.prefix_chars
:
1417 long_option_strings
.append(option_string
)
1419 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1420 dest
= kwargs
.pop('dest', None)
1422 if long_option_strings
:
1423 dest_option_string
= long_option_strings
[0]
1425 dest_option_string
= option_strings
[0]
1426 dest
= dest_option_string
.lstrip(self
.prefix_chars
)
1428 msg
= _('dest= is required for options like %r')
1429 raise ValueError(msg
% option_string
)
1430 dest
= dest
.replace('-', '_')
1432 # return the updated keyword arguments
1433 return dict(kwargs
, dest
=dest
, option_strings
=option_strings
)
1435 def _pop_action_class(self
, kwargs
, default
=None):
1436 action
= kwargs
.pop('action', default
)
1437 return self
._registry
_get
('action', action
, action
)
1439 def _get_handler(self
):
1440 # determine function from conflict handler string
1441 handler_func_name
= '_handle_conflict_%s' % self
.conflict_handler
1443 return getattr(self
, handler_func_name
)
1444 except AttributeError:
1445 msg
= _('invalid conflict_resolution value: %r')
1446 raise ValueError(msg
% self
.conflict_handler
)
1448 def _check_conflict(self
, action
):
1450 # find all options that conflict with this option
1451 confl_optionals
= []
1452 for option_string
in action
.option_strings
:
1453 if option_string
in self
._option
_string
_actions
:
1454 confl_optional
= self
._option
_string
_actions
[option_string
]
1455 confl_optionals
.append((option_string
, confl_optional
))
1457 # resolve any conflicts
1459 conflict_handler
= self
._get
_handler
()
1460 conflict_handler(action
, confl_optionals
)
1462 def _handle_conflict_error(self
, action
, conflicting_actions
):
1463 message
= _('conflicting option string(s): %s')
1464 conflict_string
= ', '.join([option_string
1465 for option_string
, action
1466 in conflicting_actions
])
1467 raise ArgumentError(action
, message
% conflict_string
)
1469 def _handle_conflict_resolve(self
, action
, conflicting_actions
):
1471 # remove all conflicting options
1472 for option_string
, action
in conflicting_actions
:
1474 # remove the conflicting option
1475 action
.option_strings
.remove(option_string
)
1476 self
._option
_string
_actions
.pop(option_string
, None)
1478 # if the option now has no option string, remove it from the
1479 # container holding it
1480 if not action
.option_strings
:
1481 action
.container
._remove
_action
(action
)
1484 class _ArgumentGroup(_ActionsContainer
):
1486 def __init__(self
, container
, title
=None, description
=None, **kwargs
):
1487 # add any missing keyword arguments by checking the container
1488 update
= kwargs
.setdefault
1489 update('conflict_handler', container
.conflict_handler
)
1490 update('prefix_chars', container
.prefix_chars
)
1491 update('argument_default', container
.argument_default
)
1492 super_init
= super(_ArgumentGroup
, self
).__init
__
1493 super_init(description
=description
, **kwargs
)
1497 self
._group
_actions
= []
1499 # share most attributes with the container
1500 self
._registries
= container
._registries
1501 self
._actions
= container
._actions
1502 self
._option
_string
_actions
= container
._option
_string
_actions
1503 self
._defaults
= container
._defaults
1504 self
._has
_negative
_number
_optionals
= \
1505 container
._has
_negative
_number
_optionals
1506 self
._mutually
_exclusive
_groups
= container
._mutually
_exclusive
_groups
1508 def _add_action(self
, action
):
1509 action
= super(_ArgumentGroup
, self
)._add
_action
(action
)
1510 self
._group
_actions
.append(action
)
1513 def _remove_action(self
, action
):
1514 super(_ArgumentGroup
, self
)._remove
_action
(action
)
1515 self
._group
_actions
.remove(action
)
1518 class _MutuallyExclusiveGroup(_ArgumentGroup
):
1520 def __init__(self
, container
, required
=False):
1521 super(_MutuallyExclusiveGroup
, self
).__init
__(container
)
1522 self
.required
= required
1523 self
._container
= container
1525 def _add_action(self
, action
):
1527 msg
= _('mutually exclusive arguments must be optional')
1528 raise ValueError(msg
)
1529 action
= self
._container
._add
_action
(action
)
1530 self
._group
_actions
.append(action
)
1533 def _remove_action(self
, action
):
1534 self
._container
._remove
_action
(action
)
1535 self
._group
_actions
.remove(action
)
1538 class ArgumentParser(_AttributeHolder
, _ActionsContainer
):
1539 """Object for parsing command line strings into Python objects.
1542 - prog -- The name of the program (default: sys.argv[0])
1543 - usage -- A usage message (default: auto-generated from arguments)
1544 - description -- A description of what the program does
1545 - epilog -- Text following the argument descriptions
1546 - parents -- Parsers whose arguments should be copied into this one
1547 - formatter_class -- HelpFormatter class for printing help messages
1548 - prefix_chars -- Characters that prefix optional arguments
1549 - fromfile_prefix_chars -- Characters that prefix files containing
1550 additional arguments
1551 - argument_default -- The default value for all arguments
1552 - conflict_handler -- String indicating how to handle conflicts
1553 - add_help -- Add a -h/-help option
1563 formatter_class
=HelpFormatter
,
1565 fromfile_prefix_chars
=None,
1566 argument_default
=None,
1567 conflict_handler
='error',
1570 if version
is not None:
1573 """The "version" argument to ArgumentParser is deprecated. """
1575 """"add_argument(..., action='version', version="N", ...)" """
1576 """instead""", DeprecationWarning)
1578 superinit
= super(ArgumentParser
, self
).__init
__
1579 superinit(description
=description
,
1580 prefix_chars
=prefix_chars
,
1581 argument_default
=argument_default
,
1582 conflict_handler
=conflict_handler
)
1584 # default setting for prog
1586 prog
= _os
.path
.basename(_sys
.argv
[0])
1590 self
.epilog
= epilog
1591 self
.version
= version
1592 self
.formatter_class
= formatter_class
1593 self
.fromfile_prefix_chars
= fromfile_prefix_chars
1594 self
.add_help
= add_help
1596 add_group
= self
.add_argument_group
1597 self
._positionals
= add_group(_('positional arguments'))
1598 self
._optionals
= add_group(_('optional arguments'))
1599 self
._subparsers
= None
1602 def identity(string
):
1604 self
.register('type', None, identity
)
1606 # add help and version arguments if necessary
1607 # (using explicit default to override global argument_default)
1608 default_prefix
= '-' if '-' in prefix_chars
else prefix_chars
[0]
1611 default_prefix
+'h', default_prefix
*2+'help',
1612 action
='help', default
=SUPPRESS
,
1613 help=_('show this help message and exit'))
1616 default_prefix
+'v', default_prefix
*2+'version',
1617 action
='version', default
=SUPPRESS
,
1618 version
=self
.version
,
1619 help=_("show program's version number and exit"))
1621 # add parent arguments and defaults
1622 for parent
in parents
:
1623 self
._add
_container
_actions
(parent
)
1625 defaults
= parent
._defaults
1626 except AttributeError:
1629 self
._defaults
.update(defaults
)
1631 # =======================
1632 # Pretty __repr__ methods
1633 # =======================
1634 def _get_kwargs(self
):
1644 return [(name
, getattr(self
, name
)) for name
in names
]
1646 # ==================================
1647 # Optional/Positional adding methods
1648 # ==================================
1649 def add_subparsers(self
, **kwargs
):
1650 if self
._subparsers
is not None:
1651 self
.error(_('cannot have multiple subparser arguments'))
1653 # add the parser class to the arguments if it's not present
1654 kwargs
.setdefault('parser_class', type(self
))
1656 if 'title' in kwargs
or 'description' in kwargs
:
1657 title
= _(kwargs
.pop('title', 'subcommands'))
1658 description
= _(kwargs
.pop('description', None))
1659 self
._subparsers
= self
.add_argument_group(title
, description
)
1661 self
._subparsers
= self
._positionals
1663 # prog defaults to the usage message of this parser, skipping
1664 # optional arguments and with no "usage:" prefix
1665 if kwargs
.get('prog') is None:
1666 formatter
= self
._get
_formatter
()
1667 positionals
= self
._get
_positional
_actions
()
1668 groups
= self
._mutually
_exclusive
_groups
1669 formatter
.add_usage(self
.usage
, positionals
, groups
, '')
1670 kwargs
['prog'] = formatter
.format_help().strip()
1672 # create the parsers action and add it to the positionals list
1673 parsers_class
= self
._pop
_action
_class
(kwargs
, 'parsers')
1674 action
= parsers_class(option_strings
=[], **kwargs
)
1675 self
._subparsers
._add
_action
(action
)
1677 # return the created parsers action
1680 def _add_action(self
, action
):
1681 if action
.option_strings
:
1682 self
._optionals
._add
_action
(action
)
1684 self
._positionals
._add
_action
(action
)
1687 def _get_optional_actions(self
):
1689 for action
in self
._actions
1690 if action
.option_strings
]
1692 def _get_positional_actions(self
):
1694 for action
in self
._actions
1695 if not action
.option_strings
]
1697 # =====================================
1698 # Command line argument parsing methods
1699 # =====================================
1700 def parse_args(self
, args
=None, namespace
=None):
1701 args
, argv
= self
.parse_known_args(args
, namespace
)
1703 msg
= _('unrecognized arguments: %s')
1704 self
.error(msg
% ' '.join(argv
))
1707 def parse_known_args(self
, args
=None, namespace
=None):
1709 # args default to the system args
1710 args
= _sys
.argv
[1:]
1712 # make sure that args are mutable
1715 # default Namespace built from parser defaults
1716 if namespace
is None:
1717 namespace
= Namespace()
1719 # add any action defaults that aren't present
1720 for action
in self
._actions
:
1721 if action
.dest
is not SUPPRESS
:
1722 if not hasattr(namespace
, action
.dest
):
1723 if action
.default
is not SUPPRESS
:
1724 setattr(namespace
, action
.dest
, action
.default
)
1726 # add any parser defaults that aren't present
1727 for dest
in self
._defaults
:
1728 if not hasattr(namespace
, dest
):
1729 setattr(namespace
, dest
, self
._defaults
[dest
])
1731 # parse the arguments and exit if there are any errors
1733 namespace
, args
= self
._parse
_known
_args
(args
, namespace
)
1734 if hasattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
):
1735 args
.extend(getattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
))
1736 delattr(namespace
, _UNRECOGNIZED_ARGS_ATTR
)
1737 return namespace
, args
1738 except ArgumentError
:
1739 err
= _sys
.exc_info()[1]
1740 self
.error(str(err
))
1742 def _parse_known_args(self
, arg_strings
, namespace
):
1743 # replace arg strings that are file references
1744 if self
.fromfile_prefix_chars
is not None:
1745 arg_strings
= self
._read
_args
_from
_files
(arg_strings
)
1747 # map all mutually exclusive arguments to the other arguments
1748 # they can't occur with
1749 action_conflicts
= {}
1750 for mutex_group
in self
._mutually
_exclusive
_groups
:
1751 group_actions
= mutex_group
._group
_actions
1752 for i
, mutex_action
in enumerate(mutex_group
._group
_actions
):
1753 conflicts
= action_conflicts
.setdefault(mutex_action
, [])
1754 conflicts
.extend(group_actions
[:i
])
1755 conflicts
.extend(group_actions
[i
+ 1:])
1757 # find all option indices, and determine the arg_string_pattern
1758 # which has an 'O' if there is an option at an index,
1759 # an 'A' if there is an argument, or a '-' if there is a '--'
1760 option_string_indices
= {}
1761 arg_string_pattern_parts
= []
1762 arg_strings_iter
= iter(arg_strings
)
1763 for i
, arg_string
in enumerate(arg_strings_iter
):
1765 # all args after -- are non-options
1766 if arg_string
== '--':
1767 arg_string_pattern_parts
.append('-')
1768 for arg_string
in arg_strings_iter
:
1769 arg_string_pattern_parts
.append('A')
1771 # otherwise, add the arg to the arg strings
1772 # and note the index if it was an option
1774 option_tuple
= self
._parse
_optional
(arg_string
)
1775 if option_tuple
is None:
1778 option_string_indices
[i
] = option_tuple
1780 arg_string_pattern_parts
.append(pattern
)
1782 # join the pieces together to form the pattern
1783 arg_strings_pattern
= ''.join(arg_string_pattern_parts
)
1785 # converts arg strings to the appropriate and then takes the action
1786 seen_actions
= set()
1787 seen_non_default_actions
= set()
1789 def take_action(action
, argument_strings
, option_string
=None):
1790 seen_actions
.add(action
)
1791 argument_values
= self
._get
_values
(action
, argument_strings
)
1793 # error if this argument is not allowed with other previously
1794 # seen arguments, assuming that actions that use the default
1795 # value don't really count as "present"
1796 if argument_values
is not action
.default
:
1797 seen_non_default_actions
.add(action
)
1798 for conflict_action
in action_conflicts
.get(action
, []):
1799 if conflict_action
in seen_non_default_actions
:
1800 msg
= _('not allowed with argument %s')
1801 action_name
= _get_action_name(conflict_action
)
1802 raise ArgumentError(action
, msg
% action_name
)
1804 # take the action if we didn't receive a SUPPRESS value
1805 # (e.g. from a default)
1806 if argument_values
is not SUPPRESS
:
1807 action(self
, namespace
, argument_values
, option_string
)
1809 # function to convert arg_strings into an optional action
1810 def consume_optional(start_index
):
1812 # get the optional identified at this index
1813 option_tuple
= option_string_indices
[start_index
]
1814 action
, option_string
, explicit_arg
= option_tuple
1816 # identify additional optionals in the same arg string
1817 # (e.g. -xyz is the same as -x -y -z if no args are required)
1818 match_argument
= self
._match
_argument
1822 # if we found no optional action, skip it
1824 extras
.append(arg_strings
[start_index
])
1825 return start_index
+ 1
1827 # if there is an explicit argument, try to match the
1828 # optional's string arguments to only this
1829 if explicit_arg
is not None:
1830 arg_count
= match_argument(action
, 'A')
1832 # if the action is a single-dash option and takes no
1833 # arguments, try to parse more single-dash options out
1834 # of the tail of the option string
1835 chars
= self
.prefix_chars
1836 if arg_count
== 0 and option_string
[1] not in chars
:
1837 action_tuples
.append((action
, [], option_string
))
1838 char
= option_string
[0]
1839 option_string
= char
+ explicit_arg
[0]
1840 new_explicit_arg
= explicit_arg
[1:] or None
1841 optionals_map
= self
._option
_string
_actions
1842 if option_string
in optionals_map
:
1843 action
= optionals_map
[option_string
]
1844 explicit_arg
= new_explicit_arg
1846 msg
= _('ignored explicit argument %r')
1847 raise ArgumentError(action
, msg
% explicit_arg
)
1849 # if the action expect exactly one argument, we've
1850 # successfully matched the option; exit the loop
1851 elif arg_count
== 1:
1852 stop
= start_index
+ 1
1853 args
= [explicit_arg
]
1854 action_tuples
.append((action
, args
, option_string
))
1857 # error if a double-dash option did not use the
1860 msg
= _('ignored explicit argument %r')
1861 raise ArgumentError(action
, msg
% explicit_arg
)
1863 # if there is no explicit argument, try to match the
1864 # optional's string arguments with the following strings
1865 # if successful, exit the loop
1867 start
= start_index
+ 1
1868 selected_patterns
= arg_strings_pattern
[start
:]
1869 arg_count
= match_argument(action
, selected_patterns
)
1870 stop
= start
+ arg_count
1871 args
= arg_strings
[start
:stop
]
1872 action_tuples
.append((action
, args
, option_string
))
1875 # add the Optional to the list and return the index at which
1876 # the Optional's string args stopped
1877 assert action_tuples
1878 for action
, args
, option_string
in action_tuples
:
1879 take_action(action
, args
, option_string
)
1882 # the list of Positionals left to be parsed; this is modified
1883 # by consume_positionals()
1884 positionals
= self
._get
_positional
_actions
()
1886 # function to convert arg_strings into positional actions
1887 def consume_positionals(start_index
):
1888 # match as many Positionals as possible
1889 match_partial
= self
._match
_arguments
_partial
1890 selected_pattern
= arg_strings_pattern
[start_index
:]
1891 arg_counts
= match_partial(positionals
, selected_pattern
)
1893 # slice off the appropriate arg strings for each Positional
1894 # and add the Positional and its args to the list
1895 for action
, arg_count
in zip(positionals
, arg_counts
):
1896 args
= arg_strings
[start_index
: start_index
+ arg_count
]
1897 start_index
+= arg_count
1898 take_action(action
, args
)
1900 # slice off the Positionals that we just parsed and return the
1901 # index at which the Positionals' string args stopped
1902 positionals
[:] = positionals
[len(arg_counts
):]
1905 # consume Positionals and Optionals alternately, until we have
1906 # passed the last option string
1909 if option_string_indices
:
1910 max_option_string_index
= max(option_string_indices
)
1912 max_option_string_index
= -1
1913 while start_index
<= max_option_string_index
:
1915 # consume any Positionals preceding the next option
1916 next_option_string_index
= min([
1918 for index
in option_string_indices
1919 if index
>= start_index
])
1920 if start_index
!= next_option_string_index
:
1921 positionals_end_index
= consume_positionals(start_index
)
1923 # only try to parse the next optional if we didn't consume
1924 # the option string during the positionals parsing
1925 if positionals_end_index
> start_index
:
1926 start_index
= positionals_end_index
1929 start_index
= positionals_end_index
1931 # if we consumed all the positionals we could and we're not
1932 # at the index of an option string, there were extra arguments
1933 if start_index
not in option_string_indices
:
1934 strings
= arg_strings
[start_index
:next_option_string_index
]
1935 extras
.extend(strings
)
1936 start_index
= next_option_string_index
1938 # consume the next optional and any arguments for it
1939 start_index
= consume_optional(start_index
)
1941 # consume any positionals following the last Optional
1942 stop_index
= consume_positionals(start_index
)
1944 # if we didn't consume all the argument strings, there were extras
1945 extras
.extend(arg_strings
[stop_index
:])
1947 # if we didn't use all the Positional objects, there were too few
1948 # arg strings supplied.
1950 self
.error(_('too few arguments'))
1952 # make sure all required actions were present, and convert defaults.
1953 for action
in self
._actions
:
1954 if action
not in seen_actions
:
1956 name
= _get_action_name(action
)
1957 self
.error(_('argument %s is required') % name
)
1959 # Convert action default now instead of doing it before
1960 # parsing arguments to avoid calling convert functions
1961 # twice (which may fail) if the argument was given, but
1962 # only if it was defined already in the namespace
1963 if (action
.default
is not None and
1964 isinstance(action
.default
, basestring
) and
1965 hasattr(namespace
, action
.dest
) and
1966 action
.default
is getattr(namespace
, action
.dest
)):
1967 setattr(namespace
, action
.dest
,
1968 self
._get
_value
(action
, action
.default
))
1970 # make sure all required groups had one option present
1971 for group
in self
._mutually
_exclusive
_groups
:
1973 for action
in group
._group
_actions
:
1974 if action
in seen_non_default_actions
:
1977 # if no actions were used, report the error
1979 names
= [_get_action_name(action
)
1980 for action
in group
._group
_actions
1981 if action
.help is not SUPPRESS
]
1982 msg
= _('one of the arguments %s is required')
1983 self
.error(msg
% ' '.join(names
))
1985 # return the updated namespace and the extra arguments
1986 return namespace
, extras
1988 def _read_args_from_files(self
, arg_strings
):
1989 # expand arguments referencing files
1990 new_arg_strings
= []
1991 for arg_string
in arg_strings
:
1993 # for regular arguments, just add them back into the list
1994 if not arg_string
or arg_string
[0] not in self
.fromfile_prefix_chars
:
1995 new_arg_strings
.append(arg_string
)
1997 # replace arguments referencing files with the file content
2000 args_file
= open(arg_string
[1:])
2003 for arg_line
in args_file
.read().splitlines():
2004 for arg
in self
.convert_arg_line_to_args(arg_line
):
2005 arg_strings
.append(arg
)
2006 arg_strings
= self
._read
_args
_from
_files
(arg_strings
)
2007 new_arg_strings
.extend(arg_strings
)
2011 err
= _sys
.exc_info()[1]
2012 self
.error(str(err
))
2014 # return the modified argument list
2015 return new_arg_strings
2017 def convert_arg_line_to_args(self
, arg_line
):
2020 def _match_argument(self
, action
, arg_strings_pattern
):
2021 # match the pattern for this action to the arg strings
2022 nargs_pattern
= self
._get
_nargs
_pattern
(action
)
2023 match
= _re
.match(nargs_pattern
, arg_strings_pattern
)
2025 # raise an exception if we weren't able to find a match
2028 None: _('expected one argument'),
2029 OPTIONAL
: _('expected at most one argument'),
2030 ONE_OR_MORE
: _('expected at least one argument'),
2032 default
= _('expected %s argument(s)') % action
.nargs
2033 msg
= nargs_errors
.get(action
.nargs
, default
)
2034 raise ArgumentError(action
, msg
)
2036 # return the number of arguments matched
2037 return len(match
.group(1))
2039 def _match_arguments_partial(self
, actions
, arg_strings_pattern
):
2040 # progressively shorten the actions list by slicing off the
2041 # final actions until we find a match
2043 for i
in range(len(actions
), 0, -1):
2044 actions_slice
= actions
[:i
]
2045 pattern
= ''.join([self
._get
_nargs
_pattern
(action
)
2046 for action
in actions_slice
])
2047 match
= _re
.match(pattern
, arg_strings_pattern
)
2048 if match
is not None:
2049 result
.extend([len(string
) for string
in match
.groups()])
2052 # return the list of arg string counts
2055 def _parse_optional(self
, arg_string
):
2056 # if it's an empty string, it was meant to be a positional
2060 # if it doesn't start with a prefix, it was meant to be positional
2061 if not arg_string
[0] in self
.prefix_chars
:
2064 # if the option string is present in the parser, return the action
2065 if arg_string
in self
._option
_string
_actions
:
2066 action
= self
._option
_string
_actions
[arg_string
]
2067 return action
, arg_string
, None
2069 # if it's just a single character, it was meant to be positional
2070 if len(arg_string
) == 1:
2073 # if the option string before the "=" is present, return the action
2074 if '=' in arg_string
:
2075 option_string
, explicit_arg
= arg_string
.split('=', 1)
2076 if option_string
in self
._option
_string
_actions
:
2077 action
= self
._option
_string
_actions
[option_string
]
2078 return action
, option_string
, explicit_arg
2080 # search through all possible prefixes of the option string
2081 # and all actions in the parser for possible interpretations
2082 option_tuples
= self
._get
_option
_tuples
(arg_string
)
2084 # if multiple actions match, the option string was ambiguous
2085 if len(option_tuples
) > 1:
2086 options
= ', '.join([option_string
2087 for action
, option_string
, explicit_arg
in option_tuples
])
2088 tup
= arg_string
, options
2089 self
.error(_('ambiguous option: %s could match %s') % tup
)
2091 # if exactly one action matched, this segmentation is good,
2092 # so return the parsed action
2093 elif len(option_tuples
) == 1:
2094 option_tuple
, = option_tuples
2097 # if it was not found as an option, but it looks like a negative
2098 # number, it was meant to be positional
2099 # unless there are negative-number-like options
2100 if self
._negative
_number
_matcher
.match(arg_string
):
2101 if not self
._has
_negative
_number
_optionals
:
2104 # if it contains a space, it was meant to be a positional
2105 if ' ' in arg_string
:
2108 # it was meant to be an optional but there is no such option
2109 # in this parser (though it might be a valid option in a subparser)
2110 return None, arg_string
, None
2112 def _get_option_tuples(self
, option_string
):
2115 # option strings starting with two prefix characters are only
2117 chars
= self
.prefix_chars
2118 if option_string
[0] in chars
and option_string
[1] in chars
:
2119 if '=' in option_string
:
2120 option_prefix
, explicit_arg
= option_string
.split('=', 1)
2122 option_prefix
= option_string
2124 for option_string
in self
._option
_string
_actions
:
2125 if option_string
.startswith(option_prefix
):
2126 action
= self
._option
_string
_actions
[option_string
]
2127 tup
= action
, option_string
, explicit_arg
2130 # single character options can be concatenated with their arguments
2131 # but multiple character options always have to have their argument
2133 elif option_string
[0] in chars
and option_string
[1] not in chars
:
2134 option_prefix
= option_string
2136 short_option_prefix
= option_string
[:2]
2137 short_explicit_arg
= option_string
[2:]
2139 for option_string
in self
._option
_string
_actions
:
2140 if option_string
== short_option_prefix
:
2141 action
= self
._option
_string
_actions
[option_string
]
2142 tup
= action
, option_string
, short_explicit_arg
2144 elif option_string
.startswith(option_prefix
):
2145 action
= self
._option
_string
_actions
[option_string
]
2146 tup
= action
, option_string
, explicit_arg
2149 # shouldn't ever get here
2151 self
.error(_('unexpected option string: %s') % option_string
)
2153 # return the collected option tuples
2156 def _get_nargs_pattern(self
, action
):
2157 # in all examples below, we have to allow for '--' args
2158 # which are represented as '-' in the pattern
2159 nargs
= action
.nargs
2161 # the default (None) is assumed to be a single argument
2163 nargs_pattern
= '(-*A-*)'
2165 # allow zero or one arguments
2166 elif nargs
== OPTIONAL
:
2167 nargs_pattern
= '(-*A?-*)'
2169 # allow zero or more arguments
2170 elif nargs
== ZERO_OR_MORE
:
2171 nargs_pattern
= '(-*[A-]*)'
2173 # allow one or more arguments
2174 elif nargs
== ONE_OR_MORE
:
2175 nargs_pattern
= '(-*A[A-]*)'
2177 # allow any number of options or arguments
2178 elif nargs
== REMAINDER
:
2179 nargs_pattern
= '([-AO]*)'
2181 # allow one argument followed by any number of options or arguments
2182 elif nargs
== PARSER
:
2183 nargs_pattern
= '(-*A[-AO]*)'
2185 # all others should be integers
2187 nargs_pattern
= '(-*%s-*)' % '-*'.join('A' * nargs
)
2189 # if this is an optional action, -- is not allowed
2190 if action
.option_strings
:
2191 nargs_pattern
= nargs_pattern
.replace('-*', '')
2192 nargs_pattern
= nargs_pattern
.replace('-', '')
2194 # return the pattern
2195 return nargs_pattern
2197 # ========================
2198 # Value conversion methods
2199 # ========================
2200 def _get_values(self
, action
, arg_strings
):
2201 # for everything but PARSER, REMAINDER args, strip out first '--'
2202 if action
.nargs
not in [PARSER
, REMAINDER
]:
2204 arg_strings
.remove('--')
2208 # optional argument produces a default when not present
2209 if not arg_strings
and action
.nargs
== OPTIONAL
:
2210 if action
.option_strings
:
2211 value
= action
.const
2213 value
= action
.default
2214 if isinstance(value
, basestring
):
2215 value
= self
._get
_value
(action
, value
)
2216 self
._check
_value
(action
, value
)
2218 # when nargs='*' on a positional, if there were no command-line
2219 # args, use the default if it is anything other than None
2220 elif (not arg_strings
and action
.nargs
== ZERO_OR_MORE
and
2221 not action
.option_strings
):
2222 if action
.default
is not None:
2223 value
= action
.default
2226 self
._check
_value
(action
, value
)
2228 # single argument or optional argument produces a single value
2229 elif len(arg_strings
) == 1 and action
.nargs
in [None, OPTIONAL
]:
2230 arg_string
, = arg_strings
2231 value
= self
._get
_value
(action
, arg_string
)
2232 self
._check
_value
(action
, value
)
2234 # REMAINDER arguments convert all values, checking none
2235 elif action
.nargs
== REMAINDER
:
2236 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2238 # PARSER arguments convert all values, but check only the first
2239 elif action
.nargs
== PARSER
:
2240 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2241 self
._check
_value
(action
, value
[0])
2243 # all other types of nargs produce a list
2245 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2247 self
._check
_value
(action
, v
)
2249 # return the converted value
2252 def _get_value(self
, action
, arg_string
):
2253 type_func
= self
._registry
_get
('type', action
.type, action
.type)
2254 if not _callable(type_func
):
2255 msg
= _('%r is not callable')
2256 raise ArgumentError(action
, msg
% type_func
)
2258 # convert the value to the appropriate type
2260 result
= type_func(arg_string
)
2262 # ArgumentTypeErrors indicate errors
2263 except ArgumentTypeError
:
2264 name
= getattr(action
.type, '__name__', repr(action
.type))
2265 msg
= str(_sys
.exc_info()[1])
2266 raise ArgumentError(action
, msg
)
2268 # TypeErrors or ValueErrors also indicate errors
2269 except (TypeError, ValueError):
2270 name
= getattr(action
.type, '__name__', repr(action
.type))
2271 msg
= _('invalid %s value: %r')
2272 raise ArgumentError(action
, msg
% (name
, arg_string
))
2274 # return the converted value
2277 def _check_value(self
, action
, value
):
2278 # converted value must be one of the choices (if specified)
2279 if action
.choices
is not None and value
not in action
.choices
:
2280 tup
= value
, ', '.join(map(repr, action
.choices
))
2281 msg
= _('invalid choice: %r (choose from %s)') % tup
2282 raise ArgumentError(action
, msg
)
2284 # =======================
2285 # Help-formatting methods
2286 # =======================
2287 def format_usage(self
):
2288 formatter
= self
._get
_formatter
()
2289 formatter
.add_usage(self
.usage
, self
._actions
,
2290 self
._mutually
_exclusive
_groups
)
2291 return formatter
.format_help()
2293 def format_help(self
):
2294 formatter
= self
._get
_formatter
()
2297 formatter
.add_usage(self
.usage
, self
._actions
,
2298 self
._mutually
_exclusive
_groups
)
2301 formatter
.add_text(self
.description
)
2303 # positionals, optionals and user-defined groups
2304 for action_group
in self
._action
_groups
:
2305 formatter
.start_section(action_group
.title
)
2306 formatter
.add_text(action_group
.description
)
2307 formatter
.add_arguments(action_group
._group
_actions
)
2308 formatter
.end_section()
2311 formatter
.add_text(self
.epilog
)
2313 # determine help from format above
2314 return formatter
.format_help()
2316 def format_version(self
):
2319 'The format_version method is deprecated -- the "version" '
2320 'argument to ArgumentParser is no longer supported.',
2322 formatter
= self
._get
_formatter
()
2323 formatter
.add_text(self
.version
)
2324 return formatter
.format_help()
2326 def _get_formatter(self
):
2327 return self
.formatter_class(prog
=self
.prog
)
2329 # =====================
2330 # Help-printing methods
2331 # =====================
2332 def print_usage(self
, file=None):
2335 self
._print
_message
(self
.format_usage(), file)
2337 def print_help(self
, file=None):
2340 self
._print
_message
(self
.format_help(), file)
2342 def print_version(self
, file=None):
2345 'The print_version method is deprecated -- the "version" '
2346 'argument to ArgumentParser is no longer supported.',
2348 self
._print
_message
(self
.format_version(), file)
2350 def _print_message(self
, message
, file=None):
2359 def exit(self
, status
=0, message
=None):
2361 self
._print
_message
(message
, _sys
.stderr
)
2364 def error(self
, message
):
2365 """error(message: string)
2367 Prints a usage message incorporating the message to stderr and
2370 If you override this in a subclass, it should not return -- it
2371 should either exit or raise an exception.
2373 self
.print_usage(_sys
.stderr
)
2374 self
.exit(2, _('%s: error: %s\n') % (self
.prog
, message
))