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.)
72 'RawDescriptionHelpFormatter',
73 'RawTextHelpFormatter',
74 'ArgumentDefaultsHelpFormatter',
82 import textwrap
as _textwrap
84 from gettext
import gettext
as _
88 return hasattr(obj
, '__call__') or hasattr(obj
, '__bases__')
91 SUPPRESS
= '==SUPPRESS=='
99 # =============================
100 # Utility functions and classes
101 # =============================
103 class _AttributeHolder(object):
104 """Abstract base class that provides __repr__.
106 The __repr__ method returns a string in the format::
107 ClassName(attr=name, attr=name, ...)
108 The attributes are determined either by a class-level attribute,
109 '_kwarg_names', or by inspecting the instance __dict__.
113 type_name
= type(self
).__name
__
115 for arg
in self
._get
_args
():
116 arg_strings
.append(repr(arg
))
117 for name
, value
in self
._get
_kwargs
():
118 arg_strings
.append('%s=%r' % (name
, value
))
119 return '%s(%s)' % (type_name
, ', '.join(arg_strings
))
121 def _get_kwargs(self
):
122 return sorted(self
.__dict
__.items())
128 def _ensure_value(namespace
, name
, value
):
129 if getattr(namespace
, name
, None) is None:
130 setattr(namespace
, name
, value
)
131 return getattr(namespace
, name
)
138 class HelpFormatter(object):
139 """Formatter for generating usage messages and argument help strings.
141 Only the name of this class is considered a public API. All the methods
142 provided by the class are considered an implementation detail.
148 max_help_position
=24,
151 # default setting for width
154 width
= int(_os
.environ
['COLUMNS'])
155 except (KeyError, ValueError):
160 self
._indent
_increment
= indent_increment
161 self
._max
_help
_position
= max_help_position
164 self
._current
_indent
= 0
166 self
._action
_max
_length
= 0
168 self
._root
_section
= self
._Section
(self
, None)
169 self
._current
_section
= self
._root
_section
171 self
._whitespace
_matcher
= _re
.compile(r
'\s+')
172 self
._long
_break
_matcher
= _re
.compile(r
'\n\n\n+')
174 # ===============================
175 # Section and indentation methods
176 # ===============================
178 self
._current
_indent
+= self
._indent
_increment
182 self
._current
_indent
-= self
._indent
_increment
183 assert self
._current
_indent
>= 0, 'Indent decreased below 0.'
186 class _Section(object):
188 def __init__(self
, formatter
, parent
, heading
=None):
189 self
.formatter
= formatter
191 self
.heading
= heading
194 def format_help(self
):
195 # format the indented section
196 if self
.parent
is not None:
197 self
.formatter
._indent
()
198 join
= self
.formatter
._join
_parts
199 for func
, args
in self
.items
:
201 item_help
= join([func(*args
) for func
, args
in self
.items
])
202 if self
.parent
is not None:
203 self
.formatter
._dedent
()
205 # return nothing if the section was empty
209 # add the heading if the section was non-empty
210 if self
.heading
is not SUPPRESS
and self
.heading
is not None:
211 current_indent
= self
.formatter
._current
_indent
212 heading
= '%*s%s:\n' % (current_indent
, '', self
.heading
)
216 # join the section-initial newline, the heading and the help
217 return join(['\n', heading
, item_help
, '\n'])
219 def _add_item(self
, func
, args
):
220 self
._current
_section
.items
.append((func
, args
))
222 # ========================
223 # Message building methods
224 # ========================
225 def start_section(self
, heading
):
227 section
= self
._Section
(self
, self
._current
_section
, heading
)
228 self
._add
_item
(section
.format_help
, [])
229 self
._current
_section
= section
231 def end_section(self
):
232 self
._current
_section
= self
._current
_section
.parent
235 def add_text(self
, text
):
236 if text
is not SUPPRESS
and text
is not None:
237 self
._add
_item
(self
._format
_text
, [text
])
239 def add_usage(self
, usage
, actions
, groups
, prefix
=None):
240 if usage
is not SUPPRESS
:
241 args
= usage
, actions
, groups
, prefix
242 self
._add
_item
(self
._format
_usage
, args
)
244 def add_argument(self
, action
):
245 if action
.help is not SUPPRESS
:
247 # find all invocations
248 get_invocation
= self
._format
_action
_invocation
249 invocations
= [get_invocation(action
)]
250 for subaction
in self
._iter
_indented
_subactions
(action
):
251 invocations
.append(get_invocation(subaction
))
253 # update the maximum item length
254 invocation_length
= max([len(s
) for s
in invocations
])
255 action_length
= invocation_length
+ self
._current
_indent
256 self
._action
_max
_length
= max(self
._action
_max
_length
,
259 # add the item to the list
260 self
._add
_item
(self
._format
_action
, [action
])
262 def add_arguments(self
, actions
):
263 for action
in actions
:
264 self
.add_argument(action
)
266 # =======================
267 # Help-formatting methods
268 # =======================
269 def format_help(self
):
270 help = self
._root
_section
.format_help()
272 help = self
._long
_break
_matcher
.sub('\n\n', help)
273 help = help.strip('\n') + '\n'
276 def _join_parts(self
, part_strings
):
278 for part
in part_strings
279 if part
and part
is not SUPPRESS
])
281 def _format_usage(self
, usage
, actions
, groups
, prefix
):
283 prefix
= _('usage: ')
285 # if usage is specified, use that
286 if usage
is not None:
287 usage
= usage
% dict(prog
=self
._prog
)
289 # if no optionals or positionals are available, usage is just prog
290 elif usage
is None and not actions
:
291 usage
= '%(prog)s' % dict(prog
=self
._prog
)
293 # if optionals and positionals are available, calculate usage
295 prog
= '%(prog)s' % dict(prog
=self
._prog
)
297 # split optionals from positionals
300 for action
in actions
:
301 if action
.option_strings
:
302 optionals
.append(action
)
304 positionals
.append(action
)
306 # build full usage string
307 format
= self
._format
_actions
_usage
308 action_usage
= format(optionals
+ positionals
, groups
)
309 usage
= ' '.join([s
for s
in [prog
, action_usage
] if s
])
311 # wrap the usage parts if it's too long
312 text_width
= self
._width
- self
._current
_indent
313 if len(prefix
) + len(usage
) > text_width
:
315 # break usage into wrappable parts
316 part_regexp
= r
'\(.*?\)+|\[.*?\]+|\S+'
317 opt_usage
= format(optionals
, groups
)
318 pos_usage
= format(positionals
, groups
)
319 opt_parts
= _re
.findall(part_regexp
, opt_usage
)
320 pos_parts
= _re
.findall(part_regexp
, pos_usage
)
321 assert ' '.join(opt_parts
) == opt_usage
322 assert ' '.join(pos_parts
) == pos_usage
324 # helper for wrapping lines
325 def get_lines(parts
, indent
, prefix
=None):
328 if prefix
is not None:
329 line_len
= len(prefix
) - 1
331 line_len
= len(indent
) - 1
333 if line_len
+ 1 + len(part
) > text_width
:
334 lines
.append(indent
+ ' '.join(line
))
336 line_len
= len(indent
) - 1
338 line_len
+= len(part
) + 1
340 lines
.append(indent
+ ' '.join(line
))
341 if prefix
is not None:
342 lines
[0] = lines
[0][len(indent
):]
345 # if prog is short, follow it with optionals or positionals
346 if len(prefix
) + len(prog
) <= 0.75 * text_width
:
347 indent
= ' ' * (len(prefix
) + len(prog
) + 1)
349 lines
= get_lines([prog
] + opt_parts
, indent
, prefix
)
350 lines
.extend(get_lines(pos_parts
, indent
))
352 lines
= get_lines([prog
] + pos_parts
, indent
, prefix
)
356 # if prog is long, put it on its own line
358 indent
= ' ' * len(prefix
)
359 parts
= opt_parts
+ pos_parts
360 lines
= get_lines(parts
, indent
)
363 lines
.extend(get_lines(opt_parts
, indent
))
364 lines
.extend(get_lines(pos_parts
, indent
))
365 lines
= [prog
] + lines
367 # join lines into usage
368 usage
= '\n'.join(lines
)
370 # prefix with 'usage:'
371 return '%s%s\n\n' % (prefix
, usage
)
373 def _format_actions_usage(self
, actions
, groups
):
374 # find group indices and identify actions in groups
375 group_actions
= set()
379 start
= actions
.index(group
._group
_actions
[0])
383 end
= start
+ len(group
._group
_actions
)
384 if actions
[start
:end
] == group
._group
_actions
:
385 for action
in group
._group
_actions
:
386 group_actions
.add(action
)
387 if not group
.required
:
393 for i
in range(start
+ 1, end
):
396 # collect all actions format strings
398 for i
, action
in enumerate(actions
):
400 # suppressed arguments are marked with None
401 # remove | separators for suppressed arguments
402 if action
.help is SUPPRESS
:
404 if inserts
.get(i
) == '|':
406 elif inserts
.get(i
+ 1) == '|':
409 # produce all arg strings
410 elif not action
.option_strings
:
411 part
= self
._format
_args
(action
, action
.dest
)
413 # if it's in a group, strip the outer []
414 if action
in group_actions
:
415 if part
[0] == '[' and part
[-1] == ']':
418 # add the action string to the list
421 # produce the first way to invoke the option in brackets
423 option_string
= action
.option_strings
[0]
425 # if the Optional doesn't take a value, format is:
427 if action
.nargs
== 0:
428 part
= '%s' % option_string
430 # if the Optional takes a value, format is:
431 # -s ARGS or --long ARGS
433 default
= action
.dest
.upper()
434 args_string
= self
._format
_args
(action
, default
)
435 part
= '%s %s' % (option_string
, args_string
)
437 # make it look optional if it's not required or in a group
438 if not action
.required
and action
not in group_actions
:
441 # add the action string to the list
444 # insert things at the necessary indices
445 for i
in sorted(inserts
, reverse
=True):
446 parts
[i
:i
] = [inserts
[i
]]
448 # join all the action items with spaces
449 text
= ' '.join([item
for item
in parts
if item
is not None])
451 # clean up separators for mutually exclusive groups
454 text
= _re
.sub(r
'(%s) ' % open, r
'\1', text
)
455 text
= _re
.sub(r
' (%s)' % close
, r
'\1', text
)
456 text
= _re
.sub(r
'%s *%s' % (open, close
), r
'', text
)
457 text
= _re
.sub(r
'\(([^|]*)\)', r
'\1', text
)
463 def _format_text(self
, text
):
464 if '%(prog)' in text
:
465 text
= text
% dict(prog
=self
._prog
)
466 text_width
= self
._width
- self
._current
_indent
467 indent
= ' ' * self
._current
_indent
468 return self
._fill
_text
(text
, text_width
, indent
) + '\n\n'
470 def _format_action(self
, action
):
471 # determine the required width and the entry label
472 help_position
= min(self
._action
_max
_length
+ 2,
473 self
._max
_help
_position
)
474 help_width
= self
._width
- help_position
475 action_width
= help_position
- self
._current
_indent
- 2
476 action_header
= self
._format
_action
_invocation
(action
)
478 # ho nelp; start on same line and add a final newline
480 tup
= self
._current
_indent
, '', action_header
481 action_header
= '%*s%s\n' % tup
483 # short action name; start on the same line and pad two spaces
484 elif len(action_header
) <= action_width
:
485 tup
= self
._current
_indent
, '', action_width
, action_header
486 action_header
= '%*s%-*s ' % tup
489 # long action name; start on the next line
491 tup
= self
._current
_indent
, '', action_header
492 action_header
= '%*s%s\n' % tup
493 indent_first
= help_position
495 # collect the pieces of the action help
496 parts
= [action_header
]
498 # if there was help for the action, add lines of help text
500 help_text
= self
._expand
_help
(action
)
501 help_lines
= self
._split
_lines
(help_text
, help_width
)
502 parts
.append('%*s%s\n' % (indent_first
, '', help_lines
[0]))
503 for line
in help_lines
[1:]:
504 parts
.append('%*s%s\n' % (help_position
, '', line
))
506 # or add a newline if the description doesn't end with one
507 elif not action_header
.endswith('\n'):
510 # if there are any sub-actions, add their help as well
511 for subaction
in self
._iter
_indented
_subactions
(action
):
512 parts
.append(self
._format
_action
(subaction
))
514 # return a single string
515 return self
._join
_parts
(parts
)
517 def _format_action_invocation(self
, action
):
518 if not action
.option_strings
:
519 metavar
, = self
._metavar
_formatter
(action
, action
.dest
)(1)
525 # if the Optional doesn't take a value, format is:
527 if action
.nargs
== 0:
528 parts
.extend(action
.option_strings
)
530 # if the Optional takes a value, format is:
531 # -s ARGS, --long ARGS
533 default
= action
.dest
.upper()
534 args_string
= self
._format
_args
(action
, default
)
535 for option_string
in action
.option_strings
:
536 parts
.append('%s %s' % (option_string
, args_string
))
538 return ', '.join(parts
)
540 def _metavar_formatter(self
, action
, default_metavar
):
541 if action
.metavar
is not None:
542 result
= action
.metavar
543 elif action
.choices
is not None:
544 choice_strs
= [str(choice
) for choice
in action
.choices
]
545 result
= '{%s}' % ','.join(choice_strs
)
547 result
= default_metavar
549 def format(tuple_size
):
550 if isinstance(result
, tuple):
553 return (result
, ) * tuple_size
556 def _format_args(self
, action
, default_metavar
):
557 get_metavar
= self
._metavar
_formatter
(action
, default_metavar
)
558 if action
.nargs
is None:
559 result
= '%s' % get_metavar(1)
560 elif action
.nargs
== OPTIONAL
:
561 result
= '[%s]' % get_metavar(1)
562 elif action
.nargs
== ZERO_OR_MORE
:
563 result
= '[%s [%s ...]]' % get_metavar(2)
564 elif action
.nargs
== ONE_OR_MORE
:
565 result
= '%s [%s ...]' % get_metavar(2)
566 elif action
.nargs
== REMAINDER
:
568 elif action
.nargs
== PARSER
:
569 result
= '%s ...' % get_metavar(1)
571 formats
= ['%s' for _
in range(action
.nargs
)]
572 result
= ' '.join(formats
) % get_metavar(action
.nargs
)
575 def _expand_help(self
, action
):
576 params
= dict(vars(action
), prog
=self
._prog
)
577 for name
in list(params
):
578 if params
[name
] is SUPPRESS
:
580 for name
in list(params
):
581 if hasattr(params
[name
], '__name__'):
582 params
[name
] = params
[name
].__name
__
583 if params
.get('choices') is not None:
584 choices_str
= ', '.join([str(c
) for c
in params
['choices']])
585 params
['choices'] = choices_str
586 return self
._get
_help
_string
(action
) % params
588 def _iter_indented_subactions(self
, action
):
590 get_subactions
= action
._get
_subactions
591 except AttributeError:
595 for subaction
in get_subactions():
599 def _split_lines(self
, text
, width
):
600 text
= self
._whitespace
_matcher
.sub(' ', text
).strip()
601 return _textwrap
.wrap(text
, width
)
603 def _fill_text(self
, text
, width
, indent
):
604 text
= self
._whitespace
_matcher
.sub(' ', text
).strip()
605 return _textwrap
.fill(text
, width
, initial_indent
=indent
,
606 subsequent_indent
=indent
)
608 def _get_help_string(self
, action
):
612 class RawDescriptionHelpFormatter(HelpFormatter
):
613 """Help message formatter which retains any formatting in descriptions.
615 Only the name of this class is considered a public API. All the methods
616 provided by the class are considered an implementation detail.
619 def _fill_text(self
, text
, width
, indent
):
620 return ''.join([indent
+ line
for line
in text
.splitlines(True)])
623 class RawTextHelpFormatter(RawDescriptionHelpFormatter
):
624 """Help message formatter which retains formatting of all help text.
626 Only the name of this class is considered a public API. All the methods
627 provided by the class are considered an implementation detail.
630 def _split_lines(self
, text
, width
):
631 return text
.splitlines()
634 class ArgumentDefaultsHelpFormatter(HelpFormatter
):
635 """Help message formatter which adds default values to argument help.
637 Only the name of this class is considered a public API. All the methods
638 provided by the class are considered an implementation detail.
641 def _get_help_string(self
, action
):
643 if '%(default)' not in action
.help:
644 if action
.default
is not SUPPRESS
:
645 defaulting_nargs
= [OPTIONAL
, ZERO_OR_MORE
]
646 if action
.option_strings
or action
.nargs
in defaulting_nargs
:
647 help += ' (default: %(default)s)'
651 # =====================
652 # Options and Arguments
653 # =====================
655 def _get_action_name(argument
):
658 elif argument
.option_strings
:
659 return '/'.join(argument
.option_strings
)
660 elif argument
.metavar
not in (None, SUPPRESS
):
661 return argument
.metavar
662 elif argument
.dest
not in (None, SUPPRESS
):
668 class ArgumentError(Exception):
669 """An error from creating or using an argument (optional or positional).
671 The string value of this exception is the message, augmented with
672 information about the argument that caused it.
675 def __init__(self
, argument
, message
):
676 self
.argument_name
= _get_action_name(argument
)
677 self
.message
= message
680 if self
.argument_name
is None:
681 format
= '%(message)s'
683 format
= 'argument %(argument_name)s: %(message)s'
684 return format
% dict(message
=self
.message
,
685 argument_name
=self
.argument_name
)
688 class ArgumentTypeError(Exception):
689 """An error from trying to convert a command line string to a type."""
697 class Action(_AttributeHolder
):
698 """Information about how to convert command line strings to Python objects.
700 Action objects are used by an ArgumentParser to represent the information
701 needed to parse a single argument from one or more strings from the
702 command line. The keyword arguments to the Action constructor are also
703 all attributes of Action instances.
707 - option_strings -- A list of command-line option strings which
708 should be associated with this action.
710 - dest -- The name of the attribute to hold the created object(s)
712 - nargs -- The number of command-line arguments that should be
713 consumed. By default, one argument will be consumed and a single
714 value will be produced. Other values include:
715 - N (an integer) consumes N arguments (and produces a list)
716 - '?' consumes zero or one arguments
717 - '*' consumes zero or more arguments (and produces a list)
718 - '+' consumes one or more arguments (and produces a list)
719 Note that the difference between the default and nargs=1 is that
720 with the default, a single value will be produced, while with
721 nargs=1, a list containing a single value will be produced.
723 - const -- The value to be produced if the option is specified and the
724 option uses an action that takes no values.
726 - default -- The value to be produced if the option is not specified.
728 - type -- The type which the command-line arguments should be converted
729 to, should be one of 'string', 'int', 'float', 'complex' or a
730 callable object that accepts a single string argument. If None,
733 - choices -- A container of values that should be allowed. If not None,
734 after a command-line argument has been converted to the appropriate
735 type, an exception will be raised if it is not a member of this
738 - required -- True if the action must always be specified at the
739 command line. This is only meaningful for optional command-line
742 - help -- The help string describing the argument.
744 - metavar -- The name to be used for the option's argument with the
745 help string. If None, the 'dest' value will be used as the name.
759 self
.option_strings
= option_strings
763 self
.default
= default
765 self
.choices
= choices
766 self
.required
= required
768 self
.metavar
= metavar
770 def _get_kwargs(self
):
782 return [(name
, getattr(self
, name
)) for name
in names
]
784 def __call__(self
, parser
, namespace
, values
, option_string
=None):
785 raise NotImplementedError(_('.__call__() not defined'))
788 class _StoreAction(Action
):
802 raise ValueError('nargs for store actions must be > 0; if you '
803 'have nothing to store, actions such as store '
804 'true or store const may be more appropriate')
805 if const
is not None and nargs
!= OPTIONAL
:
806 raise ValueError('nargs must be %r to supply const' % OPTIONAL
)
807 super(_StoreAction
, self
).__init
__(
808 option_strings
=option_strings
,
819 def __call__(self
, parser
, namespace
, values
, option_string
=None):
820 setattr(namespace
, self
.dest
, values
)
823 class _StoreConstAction(Action
):
833 super(_StoreConstAction
, self
).__init
__(
834 option_strings
=option_strings
,
842 def __call__(self
, parser
, namespace
, values
, option_string
=None):
843 setattr(namespace
, self
.dest
, self
.const
)
846 class _StoreTrueAction(_StoreConstAction
):
854 super(_StoreTrueAction
, self
).__init
__(
855 option_strings
=option_strings
,
863 class _StoreFalseAction(_StoreConstAction
):
871 super(_StoreFalseAction
, self
).__init
__(
872 option_strings
=option_strings
,
880 class _AppendAction(Action
):
894 raise ValueError('nargs for append actions must be > 0; if arg '
895 'strings are not supplying the value to append, '
896 'the append const action may be more appropriate')
897 if const
is not None and nargs
!= OPTIONAL
:
898 raise ValueError('nargs must be %r to supply const' % OPTIONAL
)
899 super(_AppendAction
, self
).__init
__(
900 option_strings
=option_strings
,
911 def __call__(self
, parser
, namespace
, values
, option_string
=None):
912 items
= _copy
.copy(_ensure_value(namespace
, self
.dest
, []))
914 setattr(namespace
, self
.dest
, items
)
917 class _AppendConstAction(Action
):
927 super(_AppendConstAction
, self
).__init
__(
928 option_strings
=option_strings
,
937 def __call__(self
, parser
, namespace
, values
, option_string
=None):
938 items
= _copy
.copy(_ensure_value(namespace
, self
.dest
, []))
939 items
.append(self
.const
)
940 setattr(namespace
, self
.dest
, items
)
943 class _CountAction(Action
):
951 super(_CountAction
, self
).__init
__(
952 option_strings
=option_strings
,
959 def __call__(self
, parser
, namespace
, values
, option_string
=None):
960 new_count
= _ensure_value(namespace
, self
.dest
, 0) + 1
961 setattr(namespace
, self
.dest
, new_count
)
964 class _HelpAction(Action
):
971 super(_HelpAction
, self
).__init
__(
972 option_strings
=option_strings
,
978 def __call__(self
, parser
, namespace
, values
, option_string
=None):
983 class _VersionAction(Action
):
990 help="show program's version number and exit"):
991 super(_VersionAction
, self
).__init
__(
992 option_strings
=option_strings
,
997 self
.version
= version
999 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1000 version
= self
.version
1002 version
= parser
.version
1003 formatter
= parser
._get
_formatter
()
1004 formatter
.add_text(version
)
1005 parser
.exit(message
=formatter
.format_help())
1008 class _SubParsersAction(Action
):
1010 class _ChoicesPseudoAction(Action
):
1012 def __init__(self
, name
, help):
1013 sup
= super(_SubParsersAction
._ChoicesPseudoAction
, self
)
1014 sup
.__init
__(option_strings
=[], dest
=name
, help=help)
1024 self
._prog
_prefix
= prog
1025 self
._parser
_class
= parser_class
1026 self
._name
_parser
_map
= {}
1027 self
._choices
_actions
= []
1029 super(_SubParsersAction
, self
).__init
__(
1030 option_strings
=option_strings
,
1033 choices
=self
._name
_parser
_map
,
1037 def add_parser(self
, name
, **kwargs
):
1038 # set prog from the existing prefix
1039 if kwargs
.get('prog') is None:
1040 kwargs
['prog'] = '%s %s' % (self
._prog
_prefix
, name
)
1042 # create a pseudo-action to hold the choice help
1043 if 'help' in kwargs
:
1044 help = kwargs
.pop('help')
1045 choice_action
= self
._ChoicesPseudoAction
(name
, help)
1046 self
._choices
_actions
.append(choice_action
)
1048 # create the parser and add it to the map
1049 parser
= self
._parser
_class
(**kwargs
)
1050 self
._name
_parser
_map
[name
] = parser
1053 def _get_subactions(self
):
1054 return self
._choices
_actions
1056 def __call__(self
, parser
, namespace
, values
, option_string
=None):
1057 parser_name
= values
[0]
1058 arg_strings
= values
[1:]
1060 # set the parser name if requested
1061 if self
.dest
is not SUPPRESS
:
1062 setattr(namespace
, self
.dest
, parser_name
)
1066 parser
= self
._name
_parser
_map
[parser_name
]
1068 tup
= parser_name
, ', '.join(self
._name
_parser
_map
)
1069 msg
= _('unknown parser %r (choices: %s)' % tup
)
1070 raise ArgumentError(self
, msg
)
1072 # parse all the remaining options into the namespace
1073 parser
.parse_args(arg_strings
, namespace
)
1080 class FileType(object):
1081 """Factory for creating file object types
1083 Instances of FileType are typically passed as type= arguments to the
1084 ArgumentParser add_argument() method.
1087 - mode -- A string indicating how the file is to be opened. Accepts the
1088 same values as the builtin open() function.
1089 - bufsize -- The file's desired buffer size. Accepts the same values as
1090 the builtin open() function.
1093 def __init__(self
, mode
='r', bufsize
=None):
1095 self
._bufsize
= bufsize
1097 def __call__(self
, string
):
1098 # the special argument "-" means sys.std{in,out}
1100 if 'r' in self
._mode
:
1102 elif 'w' in self
._mode
:
1105 msg
= _('argument "-" with mode %r' % self
._mode
)
1106 raise ValueError(msg
)
1108 # all other arguments are used as file names
1110 return open(string
, self
._mode
, self
._bufsize
)
1112 return open(string
, self
._mode
)
1115 args
= [self
._mode
, self
._bufsize
]
1116 args_str
= ', '.join([repr(arg
) for arg
in args
if arg
is not None])
1117 return '%s(%s)' % (type(self
).__name
__, args_str
)
1119 # ===========================
1120 # Optional and Positional Parsing
1121 # ===========================
1123 class Namespace(_AttributeHolder
):
1124 """Simple object for storing attributes.
1126 Implements equality by attribute names and values, and provides a simple
1127 string representation.
1130 def __init__(self
, **kwargs
):
1132 setattr(self
, name
, kwargs
[name
])
1136 def __eq__(self
, other
):
1137 return vars(self
) == vars(other
)
1139 def __ne__(self
, other
):
1140 return not (self
== other
)
1142 def __contains__(self
, key
):
1143 return key
in self
.__dict
__
1146 class _ActionsContainer(object):
1153 super(_ActionsContainer
, self
).__init
__()
1155 self
.description
= description
1156 self
.argument_default
= argument_default
1157 self
.prefix_chars
= prefix_chars
1158 self
.conflict_handler
= conflict_handler
1161 self
._registries
= {}
1164 self
.register('action', None, _StoreAction
)
1165 self
.register('action', 'store', _StoreAction
)
1166 self
.register('action', 'store_const', _StoreConstAction
)
1167 self
.register('action', 'store_true', _StoreTrueAction
)
1168 self
.register('action', 'store_false', _StoreFalseAction
)
1169 self
.register('action', 'append', _AppendAction
)
1170 self
.register('action', 'append_const', _AppendConstAction
)
1171 self
.register('action', 'count', _CountAction
)
1172 self
.register('action', 'help', _HelpAction
)
1173 self
.register('action', 'version', _VersionAction
)
1174 self
.register('action', 'parsers', _SubParsersAction
)
1176 # raise an exception if the conflict handler is invalid
1181 self
._option
_string
_actions
= {}
1184 self
._action
_groups
= []
1185 self
._mutually
_exclusive
_groups
= []
1190 # determines whether an "option" looks like a negative number
1191 self
._negative
_number
_matcher
= _re
.compile(r
'^-\d+$|^-\d*\.\d+$')
1193 # whether or not there are any optionals that look like negative
1194 # numbers -- uses a list so it can be shared and edited
1195 self
._has
_negative
_number
_optionals
= []
1197 # ====================
1198 # Registration methods
1199 # ====================
1200 def register(self
, registry_name
, value
, object):
1201 registry
= self
._registries
.setdefault(registry_name
, {})
1202 registry
[value
] = object
1204 def _registry_get(self
, registry_name
, value
, default
=None):
1205 return self
._registries
[registry_name
].get(value
, default
)
1207 # ==================================
1208 # Namespace default accessor methods
1209 # ==================================
1210 def set_defaults(self
, **kwargs
):
1211 self
._defaults
.update(kwargs
)
1213 # if these defaults match any existing arguments, replace
1214 # the previous default on the object with the new one
1215 for action
in self
._actions
:
1216 if action
.dest
in kwargs
:
1217 action
.default
= kwargs
[action
.dest
]
1219 def get_default(self
, dest
):
1220 for action
in self
._actions
:
1221 if action
.dest
== dest
and action
.default
is not None:
1222 return action
.default
1223 return self
._defaults
.get(dest
, None)
1226 # =======================
1227 # Adding argument actions
1228 # =======================
1229 def add_argument(self
, *args
, **kwargs
):
1231 add_argument(dest, ..., name=value, ...)
1232 add_argument(option_string, option_string, ..., name=value, ...)
1235 # if no positional args are supplied or only one is supplied and
1236 # it doesn't look like an option string, parse a positional
1238 chars
= self
.prefix_chars
1239 if not args
or len(args
) == 1 and args
[0][0] not in chars
:
1240 if args
and 'dest' in kwargs
:
1241 raise ValueError('dest supplied twice for positional argument')
1242 kwargs
= self
._get
_positional
_kwargs
(*args
, **kwargs
)
1244 # otherwise, we're adding an optional argument
1246 kwargs
= self
._get
_optional
_kwargs
(*args
, **kwargs
)
1248 # if no default was supplied, use the parser-level default
1249 if 'default' not in kwargs
:
1250 dest
= kwargs
['dest']
1251 if dest
in self
._defaults
:
1252 kwargs
['default'] = self
._defaults
[dest
]
1253 elif self
.argument_default
is not None:
1254 kwargs
['default'] = self
.argument_default
1256 # create the action object, and add it to the parser
1257 action_class
= self
._pop
_action
_class
(kwargs
)
1258 if not _callable(action_class
):
1259 raise ValueError('unknown action "%s"' % action_class
)
1260 action
= action_class(**kwargs
)
1262 # raise an error if the action type is not callable
1263 type_func
= self
._registry
_get
('type', action
.type, action
.type)
1264 if not _callable(type_func
):
1265 raise ValueError('%r is not callable' % type_func
)
1267 return self
._add
_action
(action
)
1269 def add_argument_group(self
, *args
, **kwargs
):
1270 group
= _ArgumentGroup(self
, *args
, **kwargs
)
1271 self
._action
_groups
.append(group
)
1274 def add_mutually_exclusive_group(self
, **kwargs
):
1275 group
= _MutuallyExclusiveGroup(self
, **kwargs
)
1276 self
._mutually
_exclusive
_groups
.append(group
)
1279 def _add_action(self
, action
):
1280 # resolve any conflicts
1281 self
._check
_conflict
(action
)
1283 # add to actions list
1284 self
._actions
.append(action
)
1285 action
.container
= self
1287 # index the action by any option strings it has
1288 for option_string
in action
.option_strings
:
1289 self
._option
_string
_actions
[option_string
] = action
1291 # set the flag if any option strings look like negative numbers
1292 for option_string
in action
.option_strings
:
1293 if self
._negative
_number
_matcher
.match(option_string
):
1294 if not self
._has
_negative
_number
_optionals
:
1295 self
._has
_negative
_number
_optionals
.append(True)
1297 # return the created action
1300 def _remove_action(self
, action
):
1301 self
._actions
.remove(action
)
1303 def _add_container_actions(self
, container
):
1304 # collect groups by titles
1305 title_group_map
= {}
1306 for group
in self
._action
_groups
:
1307 if group
.title
in title_group_map
:
1308 msg
= _('cannot merge actions - two groups are named %r')
1309 raise ValueError(msg
% (group
.title
))
1310 title_group_map
[group
.title
] = group
1312 # map each action to its group
1314 for group
in container
._action
_groups
:
1316 # if a group with the title exists, use that, otherwise
1317 # create a new group matching the container's group
1318 if group
.title
not in title_group_map
:
1319 title_group_map
[group
.title
] = self
.add_argument_group(
1321 description
=group
.description
,
1322 conflict_handler
=group
.conflict_handler
)
1324 # map the actions to their new group
1325 for action
in group
._group
_actions
:
1326 group_map
[action
] = title_group_map
[group
.title
]
1328 # add container's mutually exclusive groups
1329 # NOTE: if add_mutually_exclusive_group ever gains title= and
1330 # description= then this code will need to be expanded as above
1331 for group
in container
._mutually
_exclusive
_groups
:
1332 mutex_group
= self
.add_mutually_exclusive_group(
1333 required
=group
.required
)
1335 # map the actions to their new mutex group
1336 for action
in group
._group
_actions
:
1337 group_map
[action
] = mutex_group
1339 # add all actions to this container or their group
1340 for action
in container
._actions
:
1341 group_map
.get(action
, self
)._add
_action
(action
)
1343 def _get_positional_kwargs(self
, dest
, **kwargs
):
1344 # make sure required is not specified
1345 if 'required' in kwargs
:
1346 msg
= _("'required' is an invalid argument for positionals")
1347 raise TypeError(msg
)
1349 # mark positional arguments as required if at least one is
1351 if kwargs
.get('nargs') not in [OPTIONAL
, ZERO_OR_MORE
]:
1352 kwargs
['required'] = True
1353 if kwargs
.get('nargs') == ZERO_OR_MORE
and 'default' not in kwargs
:
1354 kwargs
['required'] = True
1356 # return the keyword arguments with no option strings
1357 return dict(kwargs
, dest
=dest
, option_strings
=[])
1359 def _get_optional_kwargs(self
, *args
, **kwargs
):
1360 # determine short and long option strings
1362 long_option_strings
= []
1363 for option_string
in args
:
1364 # error on strings that don't start with an appropriate prefix
1365 if not option_string
[0] in self
.prefix_chars
:
1366 msg
= _('invalid option string %r: '
1367 'must start with a character %r')
1368 tup
= option_string
, self
.prefix_chars
1369 raise ValueError(msg
% tup
)
1371 # strings starting with two prefix characters are long options
1372 option_strings
.append(option_string
)
1373 if option_string
[0] in self
.prefix_chars
:
1374 if len(option_string
) > 1:
1375 if option_string
[1] in self
.prefix_chars
:
1376 long_option_strings
.append(option_string
)
1378 # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1379 dest
= kwargs
.pop('dest', None)
1381 if long_option_strings
:
1382 dest_option_string
= long_option_strings
[0]
1384 dest_option_string
= option_strings
[0]
1385 dest
= dest_option_string
.lstrip(self
.prefix_chars
)
1387 msg
= _('dest= is required for options like %r')
1388 raise ValueError(msg
% option_string
)
1389 dest
= dest
.replace('-', '_')
1391 # return the updated keyword arguments
1392 return dict(kwargs
, dest
=dest
, option_strings
=option_strings
)
1394 def _pop_action_class(self
, kwargs
, default
=None):
1395 action
= kwargs
.pop('action', default
)
1396 return self
._registry
_get
('action', action
, action
)
1398 def _get_handler(self
):
1399 # determine function from conflict handler string
1400 handler_func_name
= '_handle_conflict_%s' % self
.conflict_handler
1402 return getattr(self
, handler_func_name
)
1403 except AttributeError:
1404 msg
= _('invalid conflict_resolution value: %r')
1405 raise ValueError(msg
% self
.conflict_handler
)
1407 def _check_conflict(self
, action
):
1409 # find all options that conflict with this option
1410 confl_optionals
= []
1411 for option_string
in action
.option_strings
:
1412 if option_string
in self
._option
_string
_actions
:
1413 confl_optional
= self
._option
_string
_actions
[option_string
]
1414 confl_optionals
.append((option_string
, confl_optional
))
1416 # resolve any conflicts
1418 conflict_handler
= self
._get
_handler
()
1419 conflict_handler(action
, confl_optionals
)
1421 def _handle_conflict_error(self
, action
, conflicting_actions
):
1422 message
= _('conflicting option string(s): %s')
1423 conflict_string
= ', '.join([option_string
1424 for option_string
, action
1425 in conflicting_actions
])
1426 raise ArgumentError(action
, message
% conflict_string
)
1428 def _handle_conflict_resolve(self
, action
, conflicting_actions
):
1430 # remove all conflicting options
1431 for option_string
, action
in conflicting_actions
:
1433 # remove the conflicting option
1434 action
.option_strings
.remove(option_string
)
1435 self
._option
_string
_actions
.pop(option_string
, None)
1437 # if the option now has no option string, remove it from the
1438 # container holding it
1439 if not action
.option_strings
:
1440 action
.container
._remove
_action
(action
)
1443 class _ArgumentGroup(_ActionsContainer
):
1445 def __init__(self
, container
, title
=None, description
=None, **kwargs
):
1446 # add any missing keyword arguments by checking the container
1447 update
= kwargs
.setdefault
1448 update('conflict_handler', container
.conflict_handler
)
1449 update('prefix_chars', container
.prefix_chars
)
1450 update('argument_default', container
.argument_default
)
1451 super_init
= super(_ArgumentGroup
, self
).__init
__
1452 super_init(description
=description
, **kwargs
)
1456 self
._group
_actions
= []
1458 # share most attributes with the container
1459 self
._registries
= container
._registries
1460 self
._actions
= container
._actions
1461 self
._option
_string
_actions
= container
._option
_string
_actions
1462 self
._defaults
= container
._defaults
1463 self
._has
_negative
_number
_optionals
= \
1464 container
._has
_negative
_number
_optionals
1466 def _add_action(self
, action
):
1467 action
= super(_ArgumentGroup
, self
)._add
_action
(action
)
1468 self
._group
_actions
.append(action
)
1471 def _remove_action(self
, action
):
1472 super(_ArgumentGroup
, self
)._remove
_action
(action
)
1473 self
._group
_actions
.remove(action
)
1476 class _MutuallyExclusiveGroup(_ArgumentGroup
):
1478 def __init__(self
, container
, required
=False):
1479 super(_MutuallyExclusiveGroup
, self
).__init
__(container
)
1480 self
.required
= required
1481 self
._container
= container
1483 def _add_action(self
, action
):
1485 msg
= _('mutually exclusive arguments must be optional')
1486 raise ValueError(msg
)
1487 action
= self
._container
._add
_action
(action
)
1488 self
._group
_actions
.append(action
)
1491 def _remove_action(self
, action
):
1492 self
._container
._remove
_action
(action
)
1493 self
._group
_actions
.remove(action
)
1496 class ArgumentParser(_AttributeHolder
, _ActionsContainer
):
1497 """Object for parsing command line strings into Python objects.
1500 - prog -- The name of the program (default: sys.argv[0])
1501 - usage -- A usage message (default: auto-generated from arguments)
1502 - description -- A description of what the program does
1503 - epilog -- Text following the argument descriptions
1504 - parents -- Parsers whose arguments should be copied into this one
1505 - formatter_class -- HelpFormatter class for printing help messages
1506 - prefix_chars -- Characters that prefix optional arguments
1507 - fromfile_prefix_chars -- Characters that prefix files containing
1508 additional arguments
1509 - argument_default -- The default value for all arguments
1510 - conflict_handler -- String indicating how to handle conflicts
1511 - add_help -- Add a -h/-help option
1521 formatter_class
=HelpFormatter
,
1523 fromfile_prefix_chars
=None,
1524 argument_default
=None,
1525 conflict_handler
='error',
1528 if version
is not None:
1531 """The "version" argument to ArgumentParser is deprecated. """
1533 """"add_argument(..., action='version', version="N", ...)" """
1534 """instead""", DeprecationWarning)
1536 superinit
= super(ArgumentParser
, self
).__init
__
1537 superinit(description
=description
,
1538 prefix_chars
=prefix_chars
,
1539 argument_default
=argument_default
,
1540 conflict_handler
=conflict_handler
)
1542 # default setting for prog
1544 prog
= _os
.path
.basename(_sys
.argv
[0])
1548 self
.epilog
= epilog
1549 self
.version
= version
1550 self
.formatter_class
= formatter_class
1551 self
.fromfile_prefix_chars
= fromfile_prefix_chars
1552 self
.add_help
= add_help
1554 add_group
= self
.add_argument_group
1555 self
._positionals
= add_group(_('positional arguments'))
1556 self
._optionals
= add_group(_('optional arguments'))
1557 self
._subparsers
= None
1560 def identity(string
):
1562 self
.register('type', None, identity
)
1564 # add help and version arguments if necessary
1565 # (using explicit default to override global argument_default)
1568 '-h', '--help', action
='help', default
=SUPPRESS
,
1569 help=_('show this help message and exit'))
1572 '-v', '--version', action
='version', default
=SUPPRESS
,
1573 version
=self
.version
,
1574 help=_("show program's version number and exit"))
1576 # add parent arguments and defaults
1577 for parent
in parents
:
1578 self
._add
_container
_actions
(parent
)
1580 defaults
= parent
._defaults
1581 except AttributeError:
1584 self
._defaults
.update(defaults
)
1586 # =======================
1587 # Pretty __repr__ methods
1588 # =======================
1589 def _get_kwargs(self
):
1599 return [(name
, getattr(self
, name
)) for name
in names
]
1601 # ==================================
1602 # Optional/Positional adding methods
1603 # ==================================
1604 def add_subparsers(self
, **kwargs
):
1605 if self
._subparsers
is not None:
1606 self
.error(_('cannot have multiple subparser arguments'))
1608 # add the parser class to the arguments if it's not present
1609 kwargs
.setdefault('parser_class', type(self
))
1611 if 'title' in kwargs
or 'description' in kwargs
:
1612 title
= _(kwargs
.pop('title', 'subcommands'))
1613 description
= _(kwargs
.pop('description', None))
1614 self
._subparsers
= self
.add_argument_group(title
, description
)
1616 self
._subparsers
= self
._positionals
1618 # prog defaults to the usage message of this parser, skipping
1619 # optional arguments and with no "usage:" prefix
1620 if kwargs
.get('prog') is None:
1621 formatter
= self
._get
_formatter
()
1622 positionals
= self
._get
_positional
_actions
()
1623 groups
= self
._mutually
_exclusive
_groups
1624 formatter
.add_usage(self
.usage
, positionals
, groups
, '')
1625 kwargs
['prog'] = formatter
.format_help().strip()
1627 # create the parsers action and add it to the positionals list
1628 parsers_class
= self
._pop
_action
_class
(kwargs
, 'parsers')
1629 action
= parsers_class(option_strings
=[], **kwargs
)
1630 self
._subparsers
._add
_action
(action
)
1632 # return the created parsers action
1635 def _add_action(self
, action
):
1636 if action
.option_strings
:
1637 self
._optionals
._add
_action
(action
)
1639 self
._positionals
._add
_action
(action
)
1642 def _get_optional_actions(self
):
1644 for action
in self
._actions
1645 if action
.option_strings
]
1647 def _get_positional_actions(self
):
1649 for action
in self
._actions
1650 if not action
.option_strings
]
1652 # =====================================
1653 # Command line argument parsing methods
1654 # =====================================
1655 def parse_args(self
, args
=None, namespace
=None):
1656 args
, argv
= self
.parse_known_args(args
, namespace
)
1658 msg
= _('unrecognized arguments: %s')
1659 self
.error(msg
% ' '.join(argv
))
1662 def parse_known_args(self
, args
=None, namespace
=None):
1663 # args default to the system args
1665 args
= _sys
.argv
[1:]
1667 # default Namespace built from parser defaults
1668 if namespace
is None:
1669 namespace
= Namespace()
1671 # add any action defaults that aren't present
1672 for action
in self
._actions
:
1673 if action
.dest
is not SUPPRESS
:
1674 if not hasattr(namespace
, action
.dest
):
1675 if action
.default
is not SUPPRESS
:
1676 default
= action
.default
1677 if isinstance(action
.default
, basestring
):
1678 default
= self
._get
_value
(action
, default
)
1679 setattr(namespace
, action
.dest
, default
)
1681 # add any parser defaults that aren't present
1682 for dest
in self
._defaults
:
1683 if not hasattr(namespace
, dest
):
1684 setattr(namespace
, dest
, self
._defaults
[dest
])
1686 # parse the arguments and exit if there are any errors
1688 return self
._parse
_known
_args
(args
, namespace
)
1689 except ArgumentError
:
1690 err
= _sys
.exc_info()[1]
1691 self
.error(str(err
))
1693 def _parse_known_args(self
, arg_strings
, namespace
):
1694 # replace arg strings that are file references
1695 if self
.fromfile_prefix_chars
is not None:
1696 arg_strings
= self
._read
_args
_from
_files
(arg_strings
)
1698 # map all mutually exclusive arguments to the other arguments
1699 # they can't occur with
1700 action_conflicts
= {}
1701 for mutex_group
in self
._mutually
_exclusive
_groups
:
1702 group_actions
= mutex_group
._group
_actions
1703 for i
, mutex_action
in enumerate(mutex_group
._group
_actions
):
1704 conflicts
= action_conflicts
.setdefault(mutex_action
, [])
1705 conflicts
.extend(group_actions
[:i
])
1706 conflicts
.extend(group_actions
[i
+ 1:])
1708 # find all option indices, and determine the arg_string_pattern
1709 # which has an 'O' if there is an option at an index,
1710 # an 'A' if there is an argument, or a '-' if there is a '--'
1711 option_string_indices
= {}
1712 arg_string_pattern_parts
= []
1713 arg_strings_iter
= iter(arg_strings
)
1714 for i
, arg_string
in enumerate(arg_strings_iter
):
1716 # all args after -- are non-options
1717 if arg_string
== '--':
1718 arg_string_pattern_parts
.append('-')
1719 for arg_string
in arg_strings_iter
:
1720 arg_string_pattern_parts
.append('A')
1722 # otherwise, add the arg to the arg strings
1723 # and note the index if it was an option
1725 option_tuple
= self
._parse
_optional
(arg_string
)
1726 if option_tuple
is None:
1729 option_string_indices
[i
] = option_tuple
1731 arg_string_pattern_parts
.append(pattern
)
1733 # join the pieces together to form the pattern
1734 arg_strings_pattern
= ''.join(arg_string_pattern_parts
)
1736 # converts arg strings to the appropriate and then takes the action
1737 seen_actions
= set()
1738 seen_non_default_actions
= set()
1740 def take_action(action
, argument_strings
, option_string
=None):
1741 seen_actions
.add(action
)
1742 argument_values
= self
._get
_values
(action
, argument_strings
)
1744 # error if this argument is not allowed with other previously
1745 # seen arguments, assuming that actions that use the default
1746 # value don't really count as "present"
1747 if argument_values
is not action
.default
:
1748 seen_non_default_actions
.add(action
)
1749 for conflict_action
in action_conflicts
.get(action
, []):
1750 if conflict_action
in seen_non_default_actions
:
1751 msg
= _('not allowed with argument %s')
1752 action_name
= _get_action_name(conflict_action
)
1753 raise ArgumentError(action
, msg
% action_name
)
1755 # take the action if we didn't receive a SUPPRESS value
1756 # (e.g. from a default)
1757 if argument_values
is not SUPPRESS
:
1758 action(self
, namespace
, argument_values
, option_string
)
1760 # function to convert arg_strings into an optional action
1761 def consume_optional(start_index
):
1763 # get the optional identified at this index
1764 option_tuple
= option_string_indices
[start_index
]
1765 action
, option_string
, explicit_arg
= option_tuple
1767 # identify additional optionals in the same arg string
1768 # (e.g. -xyz is the same as -x -y -z if no args are required)
1769 match_argument
= self
._match
_argument
1773 # if we found no optional action, skip it
1775 extras
.append(arg_strings
[start_index
])
1776 return start_index
+ 1
1778 # if there is an explicit argument, try to match the
1779 # optional's string arguments to only this
1780 if explicit_arg
is not None:
1781 arg_count
= match_argument(action
, 'A')
1783 # if the action is a single-dash option and takes no
1784 # arguments, try to parse more single-dash options out
1785 # of the tail of the option string
1786 chars
= self
.prefix_chars
1787 if arg_count
== 0 and option_string
[1] not in chars
:
1788 action_tuples
.append((action
, [], option_string
))
1789 for char
in self
.prefix_chars
:
1790 option_string
= char
+ explicit_arg
[0]
1791 explicit_arg
= explicit_arg
[1:] or None
1792 optionals_map
= self
._option
_string
_actions
1793 if option_string
in optionals_map
:
1794 action
= optionals_map
[option_string
]
1797 msg
= _('ignored explicit argument %r')
1798 raise ArgumentError(action
, msg
% explicit_arg
)
1800 # if the action expect exactly one argument, we've
1801 # successfully matched the option; exit the loop
1802 elif arg_count
== 1:
1803 stop
= start_index
+ 1
1804 args
= [explicit_arg
]
1805 action_tuples
.append((action
, args
, option_string
))
1808 # error if a double-dash option did not use the
1811 msg
= _('ignored explicit argument %r')
1812 raise ArgumentError(action
, msg
% explicit_arg
)
1814 # if there is no explicit argument, try to match the
1815 # optional's string arguments with the following strings
1816 # if successful, exit the loop
1818 start
= start_index
+ 1
1819 selected_patterns
= arg_strings_pattern
[start
:]
1820 arg_count
= match_argument(action
, selected_patterns
)
1821 stop
= start
+ arg_count
1822 args
= arg_strings
[start
:stop
]
1823 action_tuples
.append((action
, args
, option_string
))
1826 # add the Optional to the list and return the index at which
1827 # the Optional's string args stopped
1828 assert action_tuples
1829 for action
, args
, option_string
in action_tuples
:
1830 take_action(action
, args
, option_string
)
1833 # the list of Positionals left to be parsed; this is modified
1834 # by consume_positionals()
1835 positionals
= self
._get
_positional
_actions
()
1837 # function to convert arg_strings into positional actions
1838 def consume_positionals(start_index
):
1839 # match as many Positionals as possible
1840 match_partial
= self
._match
_arguments
_partial
1841 selected_pattern
= arg_strings_pattern
[start_index
:]
1842 arg_counts
= match_partial(positionals
, selected_pattern
)
1844 # slice off the appropriate arg strings for each Positional
1845 # and add the Positional and its args to the list
1846 for action
, arg_count
in zip(positionals
, arg_counts
):
1847 args
= arg_strings
[start_index
: start_index
+ arg_count
]
1848 start_index
+= arg_count
1849 take_action(action
, args
)
1851 # slice off the Positionals that we just parsed and return the
1852 # index at which the Positionals' string args stopped
1853 positionals
[:] = positionals
[len(arg_counts
):]
1856 # consume Positionals and Optionals alternately, until we have
1857 # passed the last option string
1860 if option_string_indices
:
1861 max_option_string_index
= max(option_string_indices
)
1863 max_option_string_index
= -1
1864 while start_index
<= max_option_string_index
:
1866 # consume any Positionals preceding the next option
1867 next_option_string_index
= min([
1869 for index
in option_string_indices
1870 if index
>= start_index
])
1871 if start_index
!= next_option_string_index
:
1872 positionals_end_index
= consume_positionals(start_index
)
1874 # only try to parse the next optional if we didn't consume
1875 # the option string during the positionals parsing
1876 if positionals_end_index
> start_index
:
1877 start_index
= positionals_end_index
1880 start_index
= positionals_end_index
1882 # if we consumed all the positionals we could and we're not
1883 # at the index of an option string, there were extra arguments
1884 if start_index
not in option_string_indices
:
1885 strings
= arg_strings
[start_index
:next_option_string_index
]
1886 extras
.extend(strings
)
1887 start_index
= next_option_string_index
1889 # consume the next optional and any arguments for it
1890 start_index
= consume_optional(start_index
)
1892 # consume any positionals following the last Optional
1893 stop_index
= consume_positionals(start_index
)
1895 # if we didn't consume all the argument strings, there were extras
1896 extras
.extend(arg_strings
[stop_index
:])
1898 # if we didn't use all the Positional objects, there were too few
1899 # arg strings supplied.
1901 self
.error(_('too few arguments'))
1903 # make sure all required actions were present
1904 for action
in self
._actions
:
1906 if action
not in seen_actions
:
1907 name
= _get_action_name(action
)
1908 self
.error(_('argument %s is required') % name
)
1910 # make sure all required groups had one option present
1911 for group
in self
._mutually
_exclusive
_groups
:
1913 for action
in group
._group
_actions
:
1914 if action
in seen_non_default_actions
:
1917 # if no actions were used, report the error
1919 names
= [_get_action_name(action
)
1920 for action
in group
._group
_actions
1921 if action
.help is not SUPPRESS
]
1922 msg
= _('one of the arguments %s is required')
1923 self
.error(msg
% ' '.join(names
))
1925 # return the updated namespace and the extra arguments
1926 return namespace
, extras
1928 def _read_args_from_files(self
, arg_strings
):
1929 # expand arguments referencing files
1930 new_arg_strings
= []
1931 for arg_string
in arg_strings
:
1933 # for regular arguments, just add them back into the list
1934 if arg_string
[0] not in self
.fromfile_prefix_chars
:
1935 new_arg_strings
.append(arg_string
)
1937 # replace arguments referencing files with the file content
1940 args_file
= open(arg_string
[1:])
1943 for arg_line
in args_file
.read().splitlines():
1944 for arg
in self
.convert_arg_line_to_args(arg_line
):
1945 arg_strings
.append(arg
)
1946 arg_strings
= self
._read
_args
_from
_files
(arg_strings
)
1947 new_arg_strings
.extend(arg_strings
)
1951 err
= _sys
.exc_info()[1]
1952 self
.error(str(err
))
1954 # return the modified argument list
1955 return new_arg_strings
1957 def convert_arg_line_to_args(self
, arg_line
):
1960 def _match_argument(self
, action
, arg_strings_pattern
):
1961 # match the pattern for this action to the arg strings
1962 nargs_pattern
= self
._get
_nargs
_pattern
(action
)
1963 match
= _re
.match(nargs_pattern
, arg_strings_pattern
)
1965 # raise an exception if we weren't able to find a match
1968 None: _('expected one argument'),
1969 OPTIONAL
: _('expected at most one argument'),
1970 ONE_OR_MORE
: _('expected at least one argument'),
1972 default
= _('expected %s argument(s)') % action
.nargs
1973 msg
= nargs_errors
.get(action
.nargs
, default
)
1974 raise ArgumentError(action
, msg
)
1976 # return the number of arguments matched
1977 return len(match
.group(1))
1979 def _match_arguments_partial(self
, actions
, arg_strings_pattern
):
1980 # progressively shorten the actions list by slicing off the
1981 # final actions until we find a match
1983 for i
in range(len(actions
), 0, -1):
1984 actions_slice
= actions
[:i
]
1985 pattern
= ''.join([self
._get
_nargs
_pattern
(action
)
1986 for action
in actions_slice
])
1987 match
= _re
.match(pattern
, arg_strings_pattern
)
1988 if match
is not None:
1989 result
.extend([len(string
) for string
in match
.groups()])
1992 # return the list of arg string counts
1995 def _parse_optional(self
, arg_string
):
1996 # if it's an empty string, it was meant to be a positional
2000 # if it doesn't start with a prefix, it was meant to be positional
2001 if not arg_string
[0] in self
.prefix_chars
:
2004 # if the option string is present in the parser, return the action
2005 if arg_string
in self
._option
_string
_actions
:
2006 action
= self
._option
_string
_actions
[arg_string
]
2007 return action
, arg_string
, None
2009 # if it's just a single character, it was meant to be positional
2010 if len(arg_string
) == 1:
2013 # if the option string before the "=" is present, return the action
2014 if '=' in arg_string
:
2015 option_string
, explicit_arg
= arg_string
.split('=', 1)
2016 if option_string
in self
._option
_string
_actions
:
2017 action
= self
._option
_string
_actions
[option_string
]
2018 return action
, option_string
, explicit_arg
2020 # search through all possible prefixes of the option string
2021 # and all actions in the parser for possible interpretations
2022 option_tuples
= self
._get
_option
_tuples
(arg_string
)
2024 # if multiple actions match, the option string was ambiguous
2025 if len(option_tuples
) > 1:
2026 options
= ', '.join([option_string
2027 for action
, option_string
, explicit_arg
in option_tuples
])
2028 tup
= arg_string
, options
2029 self
.error(_('ambiguous option: %s could match %s') % tup
)
2031 # if exactly one action matched, this segmentation is good,
2032 # so return the parsed action
2033 elif len(option_tuples
) == 1:
2034 option_tuple
, = option_tuples
2037 # if it was not found as an option, but it looks like a negative
2038 # number, it was meant to be positional
2039 # unless there are negative-number-like options
2040 if self
._negative
_number
_matcher
.match(arg_string
):
2041 if not self
._has
_negative
_number
_optionals
:
2044 # if it contains a space, it was meant to be a positional
2045 if ' ' in arg_string
:
2048 # it was meant to be an optional but there is no such option
2049 # in this parser (though it might be a valid option in a subparser)
2050 return None, arg_string
, None
2052 def _get_option_tuples(self
, option_string
):
2055 # option strings starting with two prefix characters are only
2057 chars
= self
.prefix_chars
2058 if option_string
[0] in chars
and option_string
[1] in chars
:
2059 if '=' in option_string
:
2060 option_prefix
, explicit_arg
= option_string
.split('=', 1)
2062 option_prefix
= option_string
2064 for option_string
in self
._option
_string
_actions
:
2065 if option_string
.startswith(option_prefix
):
2066 action
= self
._option
_string
_actions
[option_string
]
2067 tup
= action
, option_string
, explicit_arg
2070 # single character options can be concatenated with their arguments
2071 # but multiple character options always have to have their argument
2073 elif option_string
[0] in chars
and option_string
[1] not in chars
:
2074 option_prefix
= option_string
2076 short_option_prefix
= option_string
[:2]
2077 short_explicit_arg
= option_string
[2:]
2079 for option_string
in self
._option
_string
_actions
:
2080 if option_string
== short_option_prefix
:
2081 action
= self
._option
_string
_actions
[option_string
]
2082 tup
= action
, option_string
, short_explicit_arg
2084 elif option_string
.startswith(option_prefix
):
2085 action
= self
._option
_string
_actions
[option_string
]
2086 tup
= action
, option_string
, explicit_arg
2089 # shouldn't ever get here
2091 self
.error(_('unexpected option string: %s') % option_string
)
2093 # return the collected option tuples
2096 def _get_nargs_pattern(self
, action
):
2097 # in all examples below, we have to allow for '--' args
2098 # which are represented as '-' in the pattern
2099 nargs
= action
.nargs
2101 # the default (None) is assumed to be a single argument
2103 nargs_pattern
= '(-*A-*)'
2105 # allow zero or one arguments
2106 elif nargs
== OPTIONAL
:
2107 nargs_pattern
= '(-*A?-*)'
2109 # allow zero or more arguments
2110 elif nargs
== ZERO_OR_MORE
:
2111 nargs_pattern
= '(-*[A-]*)'
2113 # allow one or more arguments
2114 elif nargs
== ONE_OR_MORE
:
2115 nargs_pattern
= '(-*A[A-]*)'
2117 # allow any number of options or arguments
2118 elif nargs
== REMAINDER
:
2119 nargs_pattern
= '([-AO]*)'
2121 # allow one argument followed by any number of options or arguments
2122 elif nargs
== PARSER
:
2123 nargs_pattern
= '(-*A[-AO]*)'
2125 # all others should be integers
2127 nargs_pattern
= '(-*%s-*)' % '-*'.join('A' * nargs
)
2129 # if this is an optional action, -- is not allowed
2130 if action
.option_strings
:
2131 nargs_pattern
= nargs_pattern
.replace('-*', '')
2132 nargs_pattern
= nargs_pattern
.replace('-', '')
2134 # return the pattern
2135 return nargs_pattern
2137 # ========================
2138 # Value conversion methods
2139 # ========================
2140 def _get_values(self
, action
, arg_strings
):
2141 # for everything but PARSER args, strip out '--'
2142 if action
.nargs
not in [PARSER
, REMAINDER
]:
2143 arg_strings
= [s
for s
in arg_strings
if s
!= '--']
2145 # optional argument produces a default when not present
2146 if not arg_strings
and action
.nargs
== OPTIONAL
:
2147 if action
.option_strings
:
2148 value
= action
.const
2150 value
= action
.default
2151 if isinstance(value
, basestring
):
2152 value
= self
._get
_value
(action
, value
)
2153 self
._check
_value
(action
, value
)
2155 # when nargs='*' on a positional, if there were no command-line
2156 # args, use the default if it is anything other than None
2157 elif (not arg_strings
and action
.nargs
== ZERO_OR_MORE
and
2158 not action
.option_strings
):
2159 if action
.default
is not None:
2160 value
= action
.default
2163 self
._check
_value
(action
, value
)
2165 # single argument or optional argument produces a single value
2166 elif len(arg_strings
) == 1 and action
.nargs
in [None, OPTIONAL
]:
2167 arg_string
, = arg_strings
2168 value
= self
._get
_value
(action
, arg_string
)
2169 self
._check
_value
(action
, value
)
2171 # REMAINDER arguments convert all values, checking none
2172 elif action
.nargs
== REMAINDER
:
2173 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2175 # PARSER arguments convert all values, but check only the first
2176 elif action
.nargs
== PARSER
:
2177 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2178 self
._check
_value
(action
, value
[0])
2180 # all other types of nargs produce a list
2182 value
= [self
._get
_value
(action
, v
) for v
in arg_strings
]
2184 self
._check
_value
(action
, v
)
2186 # return the converted value
2189 def _get_value(self
, action
, arg_string
):
2190 type_func
= self
._registry
_get
('type', action
.type, action
.type)
2191 if not _callable(type_func
):
2192 msg
= _('%r is not callable')
2193 raise ArgumentError(action
, msg
% type_func
)
2195 # convert the value to the appropriate type
2197 result
= type_func(arg_string
)
2199 # ArgumentTypeErrors indicate errors
2200 except ArgumentTypeError
:
2201 name
= getattr(action
.type, '__name__', repr(action
.type))
2202 msg
= str(_sys
.exc_info()[1])
2203 raise ArgumentError(action
, msg
)
2205 # TypeErrors or ValueErrors also indicate errors
2206 except (TypeError, ValueError):
2207 name
= getattr(action
.type, '__name__', repr(action
.type))
2208 msg
= _('invalid %s value: %r')
2209 raise ArgumentError(action
, msg
% (name
, arg_string
))
2211 # return the converted value
2214 def _check_value(self
, action
, value
):
2215 # converted value must be one of the choices (if specified)
2216 if action
.choices
is not None and value
not in action
.choices
:
2217 tup
= value
, ', '.join(map(repr, action
.choices
))
2218 msg
= _('invalid choice: %r (choose from %s)') % tup
2219 raise ArgumentError(action
, msg
)
2221 # =======================
2222 # Help-formatting methods
2223 # =======================
2224 def format_usage(self
):
2225 formatter
= self
._get
_formatter
()
2226 formatter
.add_usage(self
.usage
, self
._actions
,
2227 self
._mutually
_exclusive
_groups
)
2228 return formatter
.format_help()
2230 def format_help(self
):
2231 formatter
= self
._get
_formatter
()
2234 formatter
.add_usage(self
.usage
, self
._actions
,
2235 self
._mutually
_exclusive
_groups
)
2238 formatter
.add_text(self
.description
)
2240 # positionals, optionals and user-defined groups
2241 for action_group
in self
._action
_groups
:
2242 formatter
.start_section(action_group
.title
)
2243 formatter
.add_text(action_group
.description
)
2244 formatter
.add_arguments(action_group
._group
_actions
)
2245 formatter
.end_section()
2248 formatter
.add_text(self
.epilog
)
2250 # determine help from format above
2251 return formatter
.format_help()
2253 def format_version(self
):
2256 'The format_version method is deprecated -- the "version" '
2257 'argument to ArgumentParser is no longer supported.',
2259 formatter
= self
._get
_formatter
()
2260 formatter
.add_text(self
.version
)
2261 return formatter
.format_help()
2263 def _get_formatter(self
):
2264 return self
.formatter_class(prog
=self
.prog
)
2266 # =====================
2267 # Help-printing methods
2268 # =====================
2269 def print_usage(self
, file=None):
2272 self
._print
_message
(self
.format_usage(), file)
2274 def print_help(self
, file=None):
2277 self
._print
_message
(self
.format_help(), file)
2279 def print_version(self
, file=None):
2282 'The print_version method is deprecated -- the "version" '
2283 'argument to ArgumentParser is no longer supported.',
2285 self
._print
_message
(self
.format_version(), file)
2287 def _print_message(self
, message
, file=None):
2296 def exit(self
, status
=0, message
=None):
2298 self
._print
_message
(message
, _sys
.stderr
)
2301 def error(self
, message
):
2302 """error(message: string)
2304 Prints a usage message incorporating the message to stderr and
2307 If you override this in a subclass, it should not return -- it
2308 should either exit or raise an exception.
2310 self
.print_usage(_sys
.stderr
)
2311 self
.exit(2, _('%s: error: %s\n') % (self
.prog
, message
))