1
# -*- coding: utf-8 -*-
3
# Copyright © 2006-2009 Steven J. Bethard <steven.bethard@gmail.com>.
5
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
6
# use this file except in compliance with the License. You may obtain a copy
9
# http://www.apache.org/licenses/LICENSE-2.0
11
# Unless required by applicable law or agreed to in writing, software
12
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
# License for the specific language governing permissions and limitations
17
"""Command-line parsing library
19
This module is an optparse-inspired command-line parsing library that:
21
- handles both optional and positional arguments
22
- produces highly informative usage messages
23
- supports parsers that dispatch to sub-parsers
25
The following is a simple usage example that sums integers from the
26
command-line and writes the result to a file::
28
parser = argparse.ArgumentParser(
29
description='sum the integers at the command line')
31
'integers', metavar='int', nargs='+', type=int,
32
help='an integer to be summed')
34
'--log', default=sys.stdout, type=argparse.FileType('w'),
35
help='the file where the sum should be written')
36
args = parser.parse_args()
37
args.log.write('%s' % sum(args.integers))
40
The module contains the following public classes:
42
- ArgumentParser -- The main entry point for command-line parsing. As the
43
example above shows, the add_argument() method is used to populate
44
the parser with actions for optional and positional arguments. Then
45
the parse_args() method is invoked to convert the args at the
46
command-line into an object with attributes.
48
- ArgumentError -- The exception raised by ArgumentParser objects when
49
there are errors with the parser's actions. Errors raised while
50
parsing the command-line are caught by ArgumentParser and emitted
51
as command-line messages.
53
- FileType -- A factory for defining types of files to be created. As the
54
example above shows, instances of FileType are typically passed as
55
the type= argument of add_argument() calls.
57
- Action -- The base class for parser actions. Typically actions are
58
selected by passing strings like 'store_true' or 'append_const' to
59
the action= argument of add_argument(). However, for greater
60
customization of ArgumentParser actions, subclasses of Action may
61
be defined and passed as the action= argument.
63
- HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
64
ArgumentDefaultsHelpFormatter -- Formatter classes which
65
may be passed as the formatter_class= argument to the
66
ArgumentParser constructor. HelpFormatter is the default,
67
RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
68
not to change the formatting for help text, and
69
ArgumentDefaultsHelpFormatter adds information about argument defaults
72
All other classes in this module are considered implementation details.
73
(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
74
considered public as object names -- the API of the formatter objects is
75
still considered an implementation detail.)
86
'RawDescriptionHelpFormatter',
87
'RawTextHelpFormatter',
88
'ArgumentDefaultsHelpFormatter',
96
import textwrap as _textwrap
104
from sets import Set as _set
107
_basestring = basestring
115
def _sorted(iterable, reverse=False):
116
result = list(iterable)
124
return hasattr(obj, '__call__') or hasattr(obj, '__bases__')
126
# silence Python 2.6 buggy warnings about Exception.message
127
if _sys.version_info[:2] == (2, 6):
129
warnings.filterwarnings(
131
message='BaseException.message has been deprecated as of Python 2.6',
132
category=DeprecationWarning,
136
SUPPRESS = '==SUPPRESS=='
144
# =============================
145
# Utility functions and classes
146
# =============================
148
class _AttributeHolder(object):
149
"""Abstract base class that provides __repr__.
151
The __repr__ method returns a string in the format::
152
ClassName(attr=name, attr=name, ...)
153
The attributes are determined either by a class-level attribute,
154
'_kwarg_names', or by inspecting the instance __dict__.
158
type_name = type(self).__name__
160
for arg in self._get_args():
161
arg_strings.append(repr(arg))
162
for name, value in self._get_kwargs():
163
arg_strings.append('%s=%r' % (name, value))
164
return '%s(%s)' % (type_name, ', '.join(arg_strings))
166
def _get_kwargs(self):
167
return _sorted(self.__dict__.items())
173
def _ensure_value(namespace, name, value):
174
if getattr(namespace, name, None) is None:
175
setattr(namespace, name, value)
176
return getattr(namespace, name)
183
class HelpFormatter(object):
184
"""Formatter for generating usage messages and argument help strings.
186
Only the name of this class is considered a public API. All the methods
187
provided by the class are considered an implementation detail.
193
max_help_position=24,
196
# default setting for width
199
width = int(_os.environ['COLUMNS'])
200
except (KeyError, ValueError):
205
self._indent_increment = indent_increment
206
self._max_help_position = max_help_position
209
self._current_indent = 0
211
self._action_max_length = 0
213
self._root_section = self._Section(self, None)
214
self._current_section = self._root_section
216
self._whitespace_matcher = _re.compile(r'\s+')
217
self._long_break_matcher = _re.compile(r'\n\n\n+')
219
# ===============================
220
# Section and indentation methods
221
# ===============================
223
self._current_indent += self._indent_increment
227
self._current_indent -= self._indent_increment
228
assert self._current_indent >= 0, 'Indent decreased below 0.'
231
class _Section(object):
233
def __init__(self, formatter, parent, heading=None):
234
self.formatter = formatter
236
self.heading = heading
239
def format_help(self):
240
# format the indented section
241
if self.parent is not None:
242
self.formatter._indent()
243
join = self.formatter._join_parts
244
for func, args in self.items:
246
item_help = join([func(*args) for func, args in self.items])
247
if self.parent is not None:
248
self.formatter._dedent()
250
# return nothing if the section was empty
254
# add the heading if the section was non-empty
255
if self.heading is not SUPPRESS and self.heading is not None:
256
current_indent = self.formatter._current_indent
257
heading = '%*s%s:\n' % (current_indent, '', self.heading)
261
# join the section-initial newline, the heading and the help
262
return join(['\n', heading, item_help, '\n'])
264
def _add_item(self, func, args):
265
self._current_section.items.append((func, args))
267
# ========================
268
# Message building methods
269
# ========================
270
def start_section(self, heading):
272
section = self._Section(self, self._current_section, heading)
273
self._add_item(section.format_help, [])
274
self._current_section = section
276
def end_section(self):
277
self._current_section = self._current_section.parent
280
def add_text(self, text):
281
if text is not SUPPRESS and text is not None:
282
self._add_item(self._format_text, [text])
284
def add_usage(self, usage, actions, groups, prefix=None):
285
if usage is not SUPPRESS:
286
args = usage, actions, groups, prefix
287
self._add_item(self._format_usage, args)
289
def add_argument(self, action):
290
if action.help is not SUPPRESS:
292
# find all invocations
293
get_invocation = self._format_action_invocation
294
invocations = [get_invocation(action)]
295
for subaction in self._iter_indented_subactions(action):
296
invocations.append(get_invocation(subaction))
298
# update the maximum item length
299
invocation_length = max([len(s) for s in invocations])
300
action_length = invocation_length + self._current_indent
301
self._action_max_length = max(self._action_max_length,
304
# add the item to the list
305
self._add_item(self._format_action, [action])
307
def add_arguments(self, actions):
308
for action in actions:
309
self.add_argument(action)
311
# =======================
312
# Help-formatting methods
313
# =======================
314
def format_help(self):
315
help = self._root_section.format_help()
317
help = self._long_break_matcher.sub('\n\n', help)
318
help = help.strip('\n') + '\n'
321
def _join_parts(self, part_strings):
323
for part in part_strings
324
if part and part is not SUPPRESS])
326
def _format_usage(self, usage, actions, groups, prefix):
328
prefix = _('usage: ')
330
# if usage is specified, use that
331
if usage is not None:
332
usage = usage % dict(prog=self._prog)
334
# if no optionals or positionals are available, usage is just prog
335
elif usage is None and not actions:
336
usage = '%(prog)s' % dict(prog=self._prog)
338
# if optionals and positionals are available, calculate usage
340
prog = '%(prog)s' % dict(prog=self._prog)
342
# split optionals from positionals
345
for action in actions:
346
if action.option_strings:
347
optionals.append(action)
349
positionals.append(action)
351
# build full usage string
352
format = self._format_actions_usage
353
action_usage = format(optionals + positionals, groups)
354
usage = ' '.join([s for s in [prog, action_usage] if s])
356
# wrap the usage parts if it's too long
357
text_width = self._width - self._current_indent
358
if len(prefix) + len(usage) > text_width:
360
# break usage into wrappable parts
361
part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
362
opt_usage = format(optionals, groups)
363
pos_usage = format(positionals, groups)
364
opt_parts = _re.findall(part_regexp, opt_usage)
365
pos_parts = _re.findall(part_regexp, pos_usage)
366
assert ' '.join(opt_parts) == opt_usage
367
assert ' '.join(pos_parts) == pos_usage
369
# helper for wrapping lines
370
def get_lines(parts, indent, prefix=None):
373
if prefix is not None:
374
line_len = len(prefix) - 1
376
line_len = len(indent) - 1
378
if line_len + 1 + len(part) > text_width:
379
lines.append(indent + ' '.join(line))
381
line_len = len(indent) - 1
383
line_len += len(part) + 1
385
lines.append(indent + ' '.join(line))
386
if prefix is not None:
387
lines[0] = lines[0][len(indent):]
390
# if prog is short, follow it with optionals or positionals
391
if len(prefix) + len(prog) <= 0.75 * text_width:
392
indent = ' ' * (len(prefix) + len(prog) + 1)
394
lines = get_lines([prog] + opt_parts, indent, prefix)
395
lines.extend(get_lines(pos_parts, indent))
397
lines = get_lines([prog] + pos_parts, indent, prefix)
401
# if prog is long, put it on its own line
403
indent = ' ' * len(prefix)
404
parts = opt_parts + pos_parts
405
lines = get_lines(parts, indent)
408
lines.extend(get_lines(opt_parts, indent))
409
lines.extend(get_lines(pos_parts, indent))
410
lines = [prog] + lines
412
# join lines into usage
413
usage = '\n'.join(lines)
415
# prefix with 'usage:'
416
return '%s%s\n\n' % (prefix, usage)
418
def _format_actions_usage(self, actions, groups):
419
# find group indices and identify actions in groups
420
group_actions = _set()
424
start = actions.index(group._group_actions[0])
428
end = start + len(group._group_actions)
429
if actions[start:end] == group._group_actions:
430
for action in group._group_actions:
431
group_actions.add(action)
432
if not group.required:
438
for i in range(start + 1, end):
441
# collect all actions format strings
443
for i, action in enumerate(actions):
445
# suppressed arguments are marked with None
446
# remove | separators for suppressed arguments
447
if action.help is SUPPRESS:
449
if inserts.get(i) == '|':
451
elif inserts.get(i + 1) == '|':
454
# produce all arg strings
455
elif not action.option_strings:
456
part = self._format_args(action, action.dest)
458
# if it's in a group, strip the outer []
459
if action in group_actions:
460
if part[0] == '[' and part[-1] == ']':
463
# add the action string to the list
466
# produce the first way to invoke the option in brackets
468
option_string = action.option_strings[0]
470
# if the Optional doesn't take a value, format is:
472
if action.nargs == 0:
473
part = '%s' % option_string
475
# if the Optional takes a value, format is:
476
# -s ARGS or --long ARGS
478
default = action.dest.upper()
479
args_string = self._format_args(action, default)
480
part = '%s %s' % (option_string, args_string)
482
# make it look optional if it's not required or in a group
483
if not action.required and action not in group_actions:
486
# add the action string to the list
489
# insert things at the necessary indices
490
for i in _sorted(inserts, reverse=True):
491
parts[i:i] = [inserts[i]]
493
# join all the action items with spaces
494
text = ' '.join([item for item in parts if item is not None])
496
# clean up separators for mutually exclusive groups
499
text = _re.sub(r'(%s) ' % open, r'\1', text)
500
text = _re.sub(r' (%s)' % close, r'\1', text)
501
text = _re.sub(r'%s *%s' % (open, close), r'', text)
502
text = _re.sub(r'\(([^|]*)\)', r'\1', text)
508
def _format_text(self, text):
509
if '%(prog)' in text:
510
text = text % dict(prog=self._prog)
511
text_width = self._width - self._current_indent
512
indent = ' ' * self._current_indent
513
return self._fill_text(text, text_width, indent) + '\n\n'
515
def _format_action(self, action):
516
# determine the required width and the entry label
517
help_position = min(self._action_max_length + 2,
518
self._max_help_position)
519
help_width = self._width - help_position
520
action_width = help_position - self._current_indent - 2
521
action_header = self._format_action_invocation(action)
523
# ho nelp; start on same line and add a final newline
525
tup = self._current_indent, '', action_header
526
action_header = '%*s%s\n' % tup
528
# short action name; start on the same line and pad two spaces
529
elif len(action_header) <= action_width:
530
tup = self._current_indent, '', action_width, action_header
531
action_header = '%*s%-*s ' % tup
534
# long action name; start on the next line
536
tup = self._current_indent, '', action_header
537
action_header = '%*s%s\n' % tup
538
indent_first = help_position
540
# collect the pieces of the action help
541
parts = [action_header]
543
# if there was help for the action, add lines of help text
545
help_text = self._expand_help(action)
546
help_lines = self._split_lines(help_text, help_width)
547
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
548
for line in help_lines[1:]:
549
parts.append('%*s%s\n' % (help_position, '', line))
551
# or add a newline if the description doesn't end with one
552
elif not action_header.endswith('\n'):
555
# if there are any sub-actions, add their help as well
556
for subaction in self._iter_indented_subactions(action):
557
parts.append(self._format_action(subaction))
559
# return a single string
560
return self._join_parts(parts)
562
def _format_action_invocation(self, action):
563
if not action.option_strings:
564
metavar, = self._metavar_formatter(action, action.dest)(1)
570
# if the Optional doesn't take a value, format is:
572
if action.nargs == 0:
573
parts.extend(action.option_strings)
575
# if the Optional takes a value, format is:
576
# -s ARGS, --long ARGS
578
default = action.dest.upper()
579
args_string = self._format_args(action, default)
580
for option_string in action.option_strings:
581
parts.append('%s %s' % (option_string, args_string))
583
return ', '.join(parts)
585
def _metavar_formatter(self, action, default_metavar):
586
if action.metavar is not None:
587
result = action.metavar
588
elif action.choices is not None:
589
choice_strs = [str(choice) for choice in action.choices]
590
result = '{%s}' % ','.join(choice_strs)
592
result = default_metavar
594
def format(tuple_size):
595
if isinstance(result, tuple):
598
return (result, ) * tuple_size
601
def _format_args(self, action, default_metavar):
602
get_metavar = self._metavar_formatter(action, default_metavar)
603
if action.nargs is None:
604
result = '%s' % get_metavar(1)
605
elif action.nargs == OPTIONAL:
606
result = '[%s]' % get_metavar(1)
607
elif action.nargs == ZERO_OR_MORE:
608
result = '[%s [%s ...]]' % get_metavar(2)
609
elif action.nargs == ONE_OR_MORE:
610
result = '%s [%s ...]' % get_metavar(2)
611
elif action.nargs == REMAINDER:
613
elif action.nargs == PARSER:
614
result = '%s ...' % get_metavar(1)
616
formats = ['%s' for _ in range(action.nargs)]
617
result = ' '.join(formats) % get_metavar(action.nargs)
620
def _expand_help(self, action):
621
params = dict(vars(action), prog=self._prog)
622
for name in list(params):
623
if params[name] is SUPPRESS:
625
for name in list(params):
626
if hasattr(params[name], '__name__'):
627
params[name] = params[name].__name__
628
if params.get('choices') is not None:
629
choices_str = ', '.join([str(c) for c in params['choices']])
630
params['choices'] = choices_str
631
return self._get_help_string(action) % params
633
def _iter_indented_subactions(self, action):
635
get_subactions = action._get_subactions
636
except AttributeError:
640
for subaction in get_subactions():
644
def _split_lines(self, text, width):
645
text = self._whitespace_matcher.sub(' ', text).strip()
646
return _textwrap.wrap(text, width)
648
def _fill_text(self, text, width, indent):
649
text = self._whitespace_matcher.sub(' ', text).strip()
650
return _textwrap.fill(text, width, initial_indent=indent,
651
subsequent_indent=indent)
653
def _get_help_string(self, action):
657
class RawDescriptionHelpFormatter(HelpFormatter):
658
"""Help message formatter which retains any formatting in descriptions.
660
Only the name of this class is considered a public API. All the methods
661
provided by the class are considered an implementation detail.
664
def _fill_text(self, text, width, indent):
665
return ''.join([indent + line for line in text.splitlines(True)])
668
class RawTextHelpFormatter(RawDescriptionHelpFormatter):
669
"""Help message formatter which retains formatting of all help text.
671
Only the name of this class is considered a public API. All the methods
672
provided by the class are considered an implementation detail.
675
def _split_lines(self, text, width):
676
return text.splitlines()
679
class ArgumentDefaultsHelpFormatter(HelpFormatter):
680
"""Help message formatter which adds default values to argument help.
682
Only the name of this class is considered a public API. All the methods
683
provided by the class are considered an implementation detail.
686
def _get_help_string(self, action):
688
if '%(default)' not in action.help:
689
if action.default is not SUPPRESS:
690
defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
691
if action.option_strings or action.nargs in defaulting_nargs:
692
help += ' (default: %(default)s)'
696
# =====================
697
# Options and Arguments
698
# =====================
700
def _get_action_name(argument):
703
elif argument.option_strings:
704
return '/'.join(argument.option_strings)
705
elif argument.metavar not in (None, SUPPRESS):
706
return argument.metavar
707
elif argument.dest not in (None, SUPPRESS):
713
class ArgumentError(Exception):
714
"""An error from creating or using an argument (optional or positional).
716
The string value of this exception is the message, augmented with
717
information about the argument that caused it.
720
def __init__(self, argument, message):
721
self.argument_name = _get_action_name(argument)
722
self.message = message
725
if self.argument_name is None:
726
format = '%(message)s'
728
format = 'argument %(argument_name)s: %(message)s'
729
return format % dict(message=self.message,
730
argument_name=self.argument_name)
733
class ArgumentTypeError(Exception):
734
"""An error from trying to convert a command line string to a type."""
742
class Action(_AttributeHolder):
743
"""Information about how to convert command line strings to Python objects.
745
Action objects are used by an ArgumentParser to represent the information
746
needed to parse a single argument from one or more strings from the
747
command line. The keyword arguments to the Action constructor are also
748
all attributes of Action instances.
752
- option_strings -- A list of command-line option strings which
753
should be associated with this action.
755
- dest -- The name of the attribute to hold the created object(s)
757
- nargs -- The number of command-line arguments that should be
758
consumed. By default, one argument will be consumed and a single
759
value will be produced. Other values include:
760
- N (an integer) consumes N arguments (and produces a list)
761
- '?' consumes zero or one arguments
762
- '*' consumes zero or more arguments (and produces a list)
763
- '+' consumes one or more arguments (and produces a list)
764
Note that the difference between the default and nargs=1 is that
765
with the default, a single value will be produced, while with
766
nargs=1, a list containing a single value will be produced.
768
- const -- The value to be produced if the option is specified and the
769
option uses an action that takes no values.
771
- default -- The value to be produced if the option is not specified.
773
- type -- The type which the command-line arguments should be converted
774
to, should be one of 'string', 'int', 'float', 'complex' or a
775
callable object that accepts a single string argument. If None,
778
- choices -- A container of values that should be allowed. If not None,
779
after a command-line argument has been converted to the appropriate
780
type, an exception will be raised if it is not a member of this
783
- required -- True if the action must always be specified at the
784
command line. This is only meaningful for optional command-line
787
- help -- The help string describing the argument.
789
- metavar -- The name to be used for the option's argument with the
790
help string. If None, the 'dest' value will be used as the name.
804
self.option_strings = option_strings
808
self.default = default
810
self.choices = choices
811
self.required = required
813
self.metavar = metavar
815
def _get_kwargs(self):
827
return [(name, getattr(self, name)) for name in names]
829
def __call__(self, parser, namespace, values, option_string=None):
830
raise NotImplementedError(_('.__call__() not defined'))
833
class _StoreAction(Action):
847
raise ValueError('nargs for store actions must be > 0; if you '
848
'have nothing to store, actions such as store '
849
'true or store const may be more appropriate')
850
if const is not None and nargs != OPTIONAL:
851
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
852
super(_StoreAction, self).__init__(
853
option_strings=option_strings,
864
def __call__(self, parser, namespace, values, option_string=None):
865
setattr(namespace, self.dest, values)
868
class _StoreConstAction(Action):
878
super(_StoreConstAction, self).__init__(
879
option_strings=option_strings,
887
def __call__(self, parser, namespace, values, option_string=None):
888
setattr(namespace, self.dest, self.const)
891
class _StoreTrueAction(_StoreConstAction):
899
super(_StoreTrueAction, self).__init__(
900
option_strings=option_strings,
908
class _StoreFalseAction(_StoreConstAction):
916
super(_StoreFalseAction, self).__init__(
917
option_strings=option_strings,
925
class _AppendAction(Action):
939
raise ValueError('nargs for append actions must be > 0; if arg '
940
'strings are not supplying the value to append, '
941
'the append const action may be more appropriate')
942
if const is not None and nargs != OPTIONAL:
943
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
944
super(_AppendAction, self).__init__(
945
option_strings=option_strings,
956
def __call__(self, parser, namespace, values, option_string=None):
957
items = _copy.copy(_ensure_value(namespace, self.dest, []))
959
setattr(namespace, self.dest, items)
962
class _AppendConstAction(Action):
972
super(_AppendConstAction, self).__init__(
973
option_strings=option_strings,
982
def __call__(self, parser, namespace, values, option_string=None):
983
items = _copy.copy(_ensure_value(namespace, self.dest, []))
984
items.append(self.const)
985
setattr(namespace, self.dest, items)
988
class _CountAction(Action):
996
super(_CountAction, self).__init__(
997
option_strings=option_strings,
1004
def __call__(self, parser, namespace, values, option_string=None):
1005
new_count = _ensure_value(namespace, self.dest, 0) + 1
1006
setattr(namespace, self.dest, new_count)
1009
class _HelpAction(Action):
1016
super(_HelpAction, self).__init__(
1017
option_strings=option_strings,
1023
def __call__(self, parser, namespace, values, option_string=None):
1028
class _VersionAction(Action):
1036
super(_VersionAction, self).__init__(
1037
option_strings=option_strings,
1042
self.version = version
1044
def __call__(self, parser, namespace, values, option_string=None):
1045
version = self.version
1047
version = parser.version
1048
formatter = parser._get_formatter()
1049
formatter.add_text(version)
1050
parser.exit(message=formatter.format_help())
1053
class _SubParsersAction(Action):
1055
class _ChoicesPseudoAction(Action):
1057
def __init__(self, name, help):
1058
sup = super(_SubParsersAction._ChoicesPseudoAction, self)
1059
sup.__init__(option_strings=[], dest=name, help=help)
1069
self._prog_prefix = prog
1070
self._parser_class = parser_class
1071
self._name_parser_map = {}
1072
self._choices_actions = []
1074
super(_SubParsersAction, self).__init__(
1075
option_strings=option_strings,
1078
choices=self._name_parser_map,
1082
def add_parser(self, name, **kwargs):
1083
# set prog from the existing prefix
1084
if kwargs.get('prog') is None:
1085
kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1087
# create a pseudo-action to hold the choice help
1088
if 'help' in kwargs:
1089
help = kwargs.pop('help')
1090
choice_action = self._ChoicesPseudoAction(name, help)
1091
self._choices_actions.append(choice_action)
1093
# create the parser and add it to the map
1094
parser = self._parser_class(**kwargs)
1095
self._name_parser_map[name] = parser
1098
def _get_subactions(self):
1099
return self._choices_actions
1101
def __call__(self, parser, namespace, values, option_string=None):
1102
parser_name = values[0]
1103
arg_strings = values[1:]
1105
# set the parser name if requested
1106
if self.dest is not SUPPRESS:
1107
setattr(namespace, self.dest, parser_name)
1111
parser = self._name_parser_map[parser_name]
1113
tup = parser_name, ', '.join(self._name_parser_map)
1114
msg = _('unknown parser %r (choices: %s)' % tup)
1115
raise ArgumentError(self, msg)
1117
# parse all the remaining options into the namespace
1118
parser.parse_args(arg_strings, namespace)
1125
class FileType(object):
1126
"""Factory for creating file object types
1128
Instances of FileType are typically passed as type= arguments to the
1129
ArgumentParser add_argument() method.
1132
- mode -- A string indicating how the file is to be opened. Accepts the
1133
same values as the builtin open() function.
1134
- bufsize -- The file's desired buffer size. Accepts the same values as
1135
the builtin open() function.
1138
def __init__(self, mode='r', bufsize=None):
1140
self._bufsize = bufsize
1142
def __call__(self, string):
1143
# the special argument "-" means sys.std{in,out}
1145
if 'r' in self._mode:
1147
elif 'w' in self._mode:
1150
msg = _('argument "-" with mode %r' % self._mode)
1151
raise ValueError(msg)
1153
# all other arguments are used as file names
1155
return open(string, self._mode, self._bufsize)
1157
return open(string, self._mode)
1160
args = [self._mode, self._bufsize]
1161
args_str = ', '.join([repr(arg) for arg in args if arg is not None])
1162
return '%s(%s)' % (type(self).__name__, args_str)
1164
# ===========================
1165
# Optional and Positional Parsing
1166
# ===========================
1168
class Namespace(_AttributeHolder):
1169
"""Simple object for storing attributes.
1171
Implements equality by attribute names and values, and provides a simple
1172
string representation.
1175
def __init__(self, **kwargs):
1177
setattr(self, name, kwargs[name])
1179
def __eq__(self, other):
1180
return vars(self) == vars(other)
1182
def __ne__(self, other):
1183
return not (self == other)
1185
def __contains__(self, key):
1186
return key in self.__dict__
1189
class _ActionsContainer(object):
1196
super(_ActionsContainer, self).__init__()
1198
self.description = description
1199
self.argument_default = argument_default
1200
self.prefix_chars = prefix_chars
1201
self.conflict_handler = conflict_handler
1204
self._registries = {}
1207
self.register('action', None, _StoreAction)
1208
self.register('action', 'store', _StoreAction)
1209
self.register('action', 'store_const', _StoreConstAction)
1210
self.register('action', 'store_true', _StoreTrueAction)
1211
self.register('action', 'store_false', _StoreFalseAction)
1212
self.register('action', 'append', _AppendAction)
1213
self.register('action', 'append_const', _AppendConstAction)
1214
self.register('action', 'count', _CountAction)
1215
self.register('action', 'help', _HelpAction)
1216
self.register('action', 'version', _VersionAction)
1217
self.register('action', 'parsers', _SubParsersAction)
1219
# raise an exception if the conflict handler is invalid
1224
self._option_string_actions = {}
1227
self._action_groups = []
1228
self._mutually_exclusive_groups = []
1233
# determines whether an "option" looks like a negative number
1234
self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1236
# whether or not there are any optionals that look like negative
1237
# numbers -- uses a list so it can be shared and edited
1238
self._has_negative_number_optionals = []
1240
# ====================
1241
# Registration methods
1242
# ====================
1243
def register(self, registry_name, value, object):
1244
registry = self._registries.setdefault(registry_name, {})
1245
registry[value] = object
1247
def _registry_get(self, registry_name, value, default=None):
1248
return self._registries[registry_name].get(value, default)
1250
# ==================================
1251
# Namespace default accessor methods
1252
# ==================================
1253
def set_defaults(self, **kwargs):
1254
self._defaults.update(kwargs)
1256
# if these defaults match any existing arguments, replace
1257
# the previous default on the object with the new one
1258
for action in self._actions:
1259
if action.dest in kwargs:
1260
action.default = kwargs[action.dest]
1262
def get_default(self, dest):
1263
for action in self._actions:
1264
if action.dest == dest and action.default is not None:
1265
return action.default
1266
return self._defaults.get(dest, None)
1269
# =======================
1270
# Adding argument actions
1271
# =======================
1272
def add_argument(self, *args, **kwargs):
1274
add_argument(dest, ..., name=value, ...)
1275
add_argument(option_string, option_string, ..., name=value, ...)
1278
# if no positional args are supplied or only one is supplied and
1279
# it doesn't look like an option string, parse a positional
1281
chars = self.prefix_chars
1282
if not args or len(args) == 1 and args[0][0] not in chars:
1283
if args and 'dest' in kwargs:
1284
raise ValueError('dest supplied twice for positional argument')
1285
kwargs = self._get_positional_kwargs(*args, **kwargs)
1287
# otherwise, we're adding an optional argument
1289
kwargs = self._get_optional_kwargs(*args, **kwargs)
1291
# if no default was supplied, use the parser-level default
1292
if 'default' not in kwargs:
1293
dest = kwargs['dest']
1294
if dest in self._defaults:
1295
kwargs['default'] = self._defaults[dest]
1296
elif self.argument_default is not None:
1297
kwargs['default'] = self.argument_default
1299
# create the action object, and add it to the parser
1300
action_class = self._pop_action_class(kwargs)
1301
if not _callable(action_class):
1302
raise ValueError('unknown action "%s"' % action_class)
1303
action = action_class(**kwargs)
1305
# raise an error if the action type is not callable
1306
type_func = self._registry_get('type', action.type, action.type)
1307
if not _callable(type_func):
1308
raise ValueError('%r is not callable' % type_func)
1310
return self._add_action(action)
1312
def add_argument_group(self, *args, **kwargs):
1313
group = _ArgumentGroup(self, *args, **kwargs)
1314
self._action_groups.append(group)
1317
def add_mutually_exclusive_group(self, **kwargs):
1318
group = _MutuallyExclusiveGroup(self, **kwargs)
1319
self._mutually_exclusive_groups.append(group)
1322
def _add_action(self, action):
1323
# resolve any conflicts
1324
self._check_conflict(action)
1326
# add to actions list
1327
self._actions.append(action)
1328
action.container = self
1330
# index the action by any option strings it has
1331
for option_string in action.option_strings:
1332
self._option_string_actions[option_string] = action
1334
# set the flag if any option strings look like negative numbers
1335
for option_string in action.option_strings:
1336
if self._negative_number_matcher.match(option_string):
1337
if not self._has_negative_number_optionals:
1338
self._has_negative_number_optionals.append(True)
1340
# return the created action
1343
def _remove_action(self, action):
1344
self._actions.remove(action)
1346
def _add_container_actions(self, container):
1347
# collect groups by titles
1348
title_group_map = {}
1349
for group in self._action_groups:
1350
if group.title in title_group_map:
1351
msg = _('cannot merge actions - two groups are named %r')
1352
raise ValueError(msg % (group.title))
1353
title_group_map[group.title] = group
1355
# map each action to its group
1357
for group in container._action_groups:
1359
# if a group with the title exists, use that, otherwise
1360
# create a new group matching the container's group
1361
if group.title not in title_group_map:
1362
title_group_map[group.title] = self.add_argument_group(
1364
description=group.description,
1365
conflict_handler=group.conflict_handler)
1367
# map the actions to their new group
1368
for action in group._group_actions:
1369
group_map[action] = title_group_map[group.title]
1371
# add container's mutually exclusive groups
1372
# NOTE: if add_mutually_exclusive_group ever gains title= and
1373
# description= then this code will need to be expanded as above
1374
for group in container._mutually_exclusive_groups:
1375
mutex_group = self.add_mutually_exclusive_group(
1376
required=group.required)
1378
# map the actions to their new mutex group
1379
for action in group._group_actions:
1380
group_map[action] = mutex_group
1382
# add all actions to this container or their group
1383
for action in container._actions:
1384
group_map.get(action, self)._add_action(action)
1386
def _get_positional_kwargs(self, dest, **kwargs):
1387
# make sure required is not specified
1388
if 'required' in kwargs:
1389
msg = _("'required' is an invalid argument for positionals")
1390
raise TypeError(msg)
1392
# mark positional arguments as required if at least one is
1394
if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1395
kwargs['required'] = True
1396
if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1397
kwargs['required'] = True
1399
# return the keyword arguments with no option strings
1400
return dict(kwargs, dest=dest, option_strings=[])
1402
def _get_optional_kwargs(self, *args, **kwargs):
1403
# determine short and long option strings
1405
long_option_strings = []
1406
for option_string in args:
1407
# error on strings that don't start with an appropriate prefix
1408
if not option_string[0] in self.prefix_chars:
1409
msg = _('invalid option string %r: '
1410
'must start with a character %r')
1411
tup = option_string, self.prefix_chars
1412
raise ValueError(msg % tup)
1414
# strings starting with two prefix characters are long options
1415
option_strings.append(option_string)
1416
if option_string[0] in self.prefix_chars:
1417
if len(option_string) > 1:
1418
if option_string[1] in self.prefix_chars:
1419
long_option_strings.append(option_string)
1421
# infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1422
dest = kwargs.pop('dest', None)
1424
if long_option_strings:
1425
dest_option_string = long_option_strings[0]
1427
dest_option_string = option_strings[0]
1428
dest = dest_option_string.lstrip(self.prefix_chars)
1430
msg = _('dest= is required for options like %r')
1431
raise ValueError(msg % option_string)
1432
dest = dest.replace('-', '_')
1434
# return the updated keyword arguments
1435
return dict(kwargs, dest=dest, option_strings=option_strings)
1437
def _pop_action_class(self, kwargs, default=None):
1438
action = kwargs.pop('action', default)
1439
return self._registry_get('action', action, action)
1441
def _get_handler(self):
1442
# determine function from conflict handler string
1443
handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1445
return getattr(self, handler_func_name)
1446
except AttributeError:
1447
msg = _('invalid conflict_resolution value: %r')
1448
raise ValueError(msg % self.conflict_handler)
1450
def _check_conflict(self, action):
1452
# find all options that conflict with this option
1453
confl_optionals = []
1454
for option_string in action.option_strings:
1455
if option_string in self._option_string_actions:
1456
confl_optional = self._option_string_actions[option_string]
1457
confl_optionals.append((option_string, confl_optional))
1459
# resolve any conflicts
1461
conflict_handler = self._get_handler()
1462
conflict_handler(action, confl_optionals)
1464
def _handle_conflict_error(self, action, conflicting_actions):
1465
message = _('conflicting option string(s): %s')
1466
conflict_string = ', '.join([option_string
1467
for option_string, action
1468
in conflicting_actions])
1469
raise ArgumentError(action, message % conflict_string)
1471
def _handle_conflict_resolve(self, action, conflicting_actions):
1473
# remove all conflicting options
1474
for option_string, action in conflicting_actions:
1476
# remove the conflicting option
1477
action.option_strings.remove(option_string)
1478
self._option_string_actions.pop(option_string, None)
1480
# if the option now has no option string, remove it from the
1481
# container holding it
1482
if not action.option_strings:
1483
action.container._remove_action(action)
1486
class _ArgumentGroup(_ActionsContainer):
1488
def __init__(self, container, title=None, description=None, **kwargs):
1489
# add any missing keyword arguments by checking the container
1490
update = kwargs.setdefault
1491
update('conflict_handler', container.conflict_handler)
1492
update('prefix_chars', container.prefix_chars)
1493
update('argument_default', container.argument_default)
1494
super_init = super(_ArgumentGroup, self).__init__
1495
super_init(description=description, **kwargs)
1499
self._group_actions = []
1501
# share most attributes with the container
1502
self._registries = container._registries
1503
self._actions = container._actions
1504
self._option_string_actions = container._option_string_actions
1505
self._defaults = container._defaults
1506
self._has_negative_number_optionals = \
1507
container._has_negative_number_optionals
1509
def _add_action(self, action):
1510
action = super(_ArgumentGroup, self)._add_action(action)
1511
self._group_actions.append(action)
1514
def _remove_action(self, action):
1515
super(_ArgumentGroup, self)._remove_action(action)
1516
self._group_actions.remove(action)
1519
class _MutuallyExclusiveGroup(_ArgumentGroup):
1521
def __init__(self, container, required=False):
1522
super(_MutuallyExclusiveGroup, self).__init__(container)
1523
self.required = required
1524
self._container = container
1526
def _add_action(self, action):
1528
msg = _('mutually exclusive arguments must be optional')
1529
raise ValueError(msg)
1530
action = self._container._add_action(action)
1531
self._group_actions.append(action)
1534
def _remove_action(self, action):
1535
self._container._remove_action(action)
1536
self._group_actions.remove(action)
1539
class ArgumentParser(_AttributeHolder, _ActionsContainer):
1540
"""Object for parsing command line strings into Python objects.
1543
- prog -- The name of the program (default: sys.argv[0])
1544
- usage -- A usage message (default: auto-generated from arguments)
1545
- description -- A description of what the program does
1546
- epilog -- Text following the argument descriptions
1547
- parents -- Parsers whose arguments should be copied into this one
1548
- formatter_class -- HelpFormatter class for printing help messages
1549
- prefix_chars -- Characters that prefix optional arguments
1550
- fromfile_prefix_chars -- Characters that prefix files containing
1551
additional arguments
1552
- argument_default -- The default value for all arguments
1553
- conflict_handler -- String indicating how to handle conflicts
1554
- add_help -- Add a -h/-help option
1564
formatter_class=HelpFormatter,
1566
fromfile_prefix_chars=None,
1567
argument_default=None,
1568
conflict_handler='error',
1571
if version is not None:
1574
"""The "version" argument to ArgumentParser is deprecated. """
1576
""""add_argument(..., action='version', version="N", ...)" """
1577
"""instead""", DeprecationWarning)
1579
superinit = super(ArgumentParser, self).__init__
1580
superinit(description=description,
1581
prefix_chars=prefix_chars,
1582
argument_default=argument_default,
1583
conflict_handler=conflict_handler)
1585
# default setting for prog
1587
prog = _os.path.basename(_sys.argv[0])
1591
self.epilog = epilog
1592
self.version = version
1593
self.formatter_class = formatter_class
1594
self.fromfile_prefix_chars = fromfile_prefix_chars
1595
self.add_help = add_help
1597
add_group = self.add_argument_group
1598
self._positionals = add_group(_('positional arguments'))
1599
self._optionals = add_group(_('optional arguments'))
1600
self._subparsers = None
1603
def identity(string):
1605
self.register('type', None, identity)
1607
# add help and version arguments if necessary
1608
# (using explicit default to override global argument_default)
1611
'-h', '--help', action='help', default=SUPPRESS,
1612
help=_('show this help message and exit'))
1615
'-v', '--version', action='version', default=SUPPRESS,
1616
version=self.version,
1617
help=_("show program's version number and exit"))
1619
# add parent arguments and defaults
1620
for parent in parents:
1621
self._add_container_actions(parent)
1623
defaults = parent._defaults
1624
except AttributeError:
1627
self._defaults.update(defaults)
1629
# =======================
1630
# Pretty __repr__ methods
1631
# =======================
1632
def _get_kwargs(self):
1642
return [(name, getattr(self, name)) for name in names]
1644
# ==================================
1645
# Optional/Positional adding methods
1646
# ==================================
1647
def add_subparsers(self, **kwargs):
1648
if self._subparsers is not None:
1649
self.error(_('cannot have multiple subparser arguments'))
1651
# add the parser class to the arguments if it's not present
1652
kwargs.setdefault('parser_class', type(self))
1654
if 'title' in kwargs or 'description' in kwargs:
1655
title = _(kwargs.pop('title', 'subcommands'))
1656
description = _(kwargs.pop('description', None))
1657
self._subparsers = self.add_argument_group(title, description)
1659
self._subparsers = self._positionals
1661
# prog defaults to the usage message of this parser, skipping
1662
# optional arguments and with no "usage:" prefix
1663
if kwargs.get('prog') is None:
1664
formatter = self._get_formatter()
1665
positionals = self._get_positional_actions()
1666
groups = self._mutually_exclusive_groups
1667
formatter.add_usage(self.usage, positionals, groups, '')
1668
kwargs['prog'] = formatter.format_help().strip()
1670
# create the parsers action and add it to the positionals list
1671
parsers_class = self._pop_action_class(kwargs, 'parsers')
1672
action = parsers_class(option_strings=[], **kwargs)
1673
self._subparsers._add_action(action)
1675
# return the created parsers action
1678
def _add_action(self, action):
1679
if action.option_strings:
1680
self._optionals._add_action(action)
1682
self._positionals._add_action(action)
1685
def _get_optional_actions(self):
1687
for action in self._actions
1688
if action.option_strings]
1690
def _get_positional_actions(self):
1692
for action in self._actions
1693
if not action.option_strings]
1695
# =====================================
1696
# Command line argument parsing methods
1697
# =====================================
1698
def parse_args(self, args=None, namespace=None):
1699
args, argv = self.parse_known_args(args, namespace)
1701
msg = _('unrecognized arguments: %s')
1702
self.error(msg % ' '.join(argv))
1705
def parse_known_args(self, args=None, namespace=None):
1706
# args default to the system args
1708
args = _sys.argv[1:]
1710
# default Namespace built from parser defaults
1711
if namespace is None:
1712
namespace = Namespace()
1714
# add any action defaults that aren't present
1715
for action in self._actions:
1716
if action.dest is not SUPPRESS:
1717
if not hasattr(namespace, action.dest):
1718
if action.default is not SUPPRESS:
1719
default = action.default
1720
if isinstance(action.default, _basestring):
1721
default = self._get_value(action, default)
1722
setattr(namespace, action.dest, default)
1724
# add any parser defaults that aren't present
1725
for dest in self._defaults:
1726
if not hasattr(namespace, dest):
1727
setattr(namespace, dest, self._defaults[dest])
1729
# parse the arguments and exit if there are any errors
1731
return self._parse_known_args(args, namespace)
1732
except ArgumentError:
1733
err = _sys.exc_info()[1]
1734
self.error(str(err))
1736
def _parse_known_args(self, arg_strings, namespace):
1737
# replace arg strings that are file references
1738
if self.fromfile_prefix_chars is not None:
1739
arg_strings = self._read_args_from_files(arg_strings)
1741
# map all mutually exclusive arguments to the other arguments
1742
# they can't occur with
1743
action_conflicts = {}
1744
for mutex_group in self._mutually_exclusive_groups:
1745
group_actions = mutex_group._group_actions
1746
for i, mutex_action in enumerate(mutex_group._group_actions):
1747
conflicts = action_conflicts.setdefault(mutex_action, [])
1748
conflicts.extend(group_actions[:i])
1749
conflicts.extend(group_actions[i + 1:])
1751
# find all option indices, and determine the arg_string_pattern
1752
# which has an 'O' if there is an option at an index,
1753
# an 'A' if there is an argument, or a '-' if there is a '--'
1754
option_string_indices = {}
1755
arg_string_pattern_parts = []
1756
arg_strings_iter = iter(arg_strings)
1757
for i, arg_string in enumerate(arg_strings_iter):
1759
# all args after -- are non-options
1760
if arg_string == '--':
1761
arg_string_pattern_parts.append('-')
1762
for arg_string in arg_strings_iter:
1763
arg_string_pattern_parts.append('A')
1765
# otherwise, add the arg to the arg strings
1766
# and note the index if it was an option
1768
option_tuple = self._parse_optional(arg_string)
1769
if option_tuple is None:
1772
option_string_indices[i] = option_tuple
1774
arg_string_pattern_parts.append(pattern)
1776
# join the pieces together to form the pattern
1777
arg_strings_pattern = ''.join(arg_string_pattern_parts)
1779
# converts arg strings to the appropriate and then takes the action
1780
seen_actions = _set()
1781
seen_non_default_actions = _set()
1783
def take_action(action, argument_strings, option_string=None):
1784
seen_actions.add(action)
1785
argument_values = self._get_values(action, argument_strings)
1787
# error if this argument is not allowed with other previously
1788
# seen arguments, assuming that actions that use the default
1789
# value don't really count as "present"
1790
if argument_values is not action.default:
1791
seen_non_default_actions.add(action)
1792
for conflict_action in action_conflicts.get(action, []):
1793
if conflict_action in seen_non_default_actions:
1794
msg = _('not allowed with argument %s')
1795
action_name = _get_action_name(conflict_action)
1796
raise ArgumentError(action, msg % action_name)
1798
# take the action if we didn't receive a SUPPRESS value
1799
# (e.g. from a default)
1800
if argument_values is not SUPPRESS:
1801
action(self, namespace, argument_values, option_string)
1803
# function to convert arg_strings into an optional action
1804
def consume_optional(start_index):
1806
# get the optional identified at this index
1807
option_tuple = option_string_indices[start_index]
1808
action, option_string, explicit_arg = option_tuple
1810
# identify additional optionals in the same arg string
1811
# (e.g. -xyz is the same as -x -y -z if no args are required)
1812
match_argument = self._match_argument
1816
# if we found no optional action, skip it
1818
extras.append(arg_strings[start_index])
1819
return start_index + 1
1821
# if there is an explicit argument, try to match the
1822
# optional's string arguments to only this
1823
if explicit_arg is not None:
1824
arg_count = match_argument(action, 'A')
1826
# if the action is a single-dash option and takes no
1827
# arguments, try to parse more single-dash options out
1828
# of the tail of the option string
1829
chars = self.prefix_chars
1830
if arg_count == 0 and option_string[1] not in chars:
1831
action_tuples.append((action, [], option_string))
1832
for char in self.prefix_chars:
1833
option_string = char + explicit_arg[0]
1834
explicit_arg = explicit_arg[1:] or None
1835
optionals_map = self._option_string_actions
1836
if option_string in optionals_map:
1837
action = optionals_map[option_string]
1840
msg = _('ignored explicit argument %r')
1841
raise ArgumentError(action, msg % explicit_arg)
1843
# if the action expect exactly one argument, we've
1844
# successfully matched the option; exit the loop
1845
elif arg_count == 1:
1846
stop = start_index + 1
1847
args = [explicit_arg]
1848
action_tuples.append((action, args, option_string))
1851
# error if a double-dash option did not use the
1854
msg = _('ignored explicit argument %r')
1855
raise ArgumentError(action, msg % explicit_arg)
1857
# if there is no explicit argument, try to match the
1858
# optional's string arguments with the following strings
1859
# if successful, exit the loop
1861
start = start_index + 1
1862
selected_patterns = arg_strings_pattern[start:]
1863
arg_count = match_argument(action, selected_patterns)
1864
stop = start + arg_count
1865
args = arg_strings[start:stop]
1866
action_tuples.append((action, args, option_string))
1869
# add the Optional to the list and return the index at which
1870
# the Optional's string args stopped
1871
assert action_tuples
1872
for action, args, option_string in action_tuples:
1873
take_action(action, args, option_string)
1876
# the list of Positionals left to be parsed; this is modified
1877
# by consume_positionals()
1878
positionals = self._get_positional_actions()
1880
# function to convert arg_strings into positional actions
1881
def consume_positionals(start_index):
1882
# match as many Positionals as possible
1883
match_partial = self._match_arguments_partial
1884
selected_pattern = arg_strings_pattern[start_index:]
1885
arg_counts = match_partial(positionals, selected_pattern)
1887
# slice off the appropriate arg strings for each Positional
1888
# and add the Positional and its args to the list
1889
for action, arg_count in zip(positionals, arg_counts):
1890
args = arg_strings[start_index: start_index + arg_count]
1891
start_index += arg_count
1892
take_action(action, args)
1894
# slice off the Positionals that we just parsed and return the
1895
# index at which the Positionals' string args stopped
1896
positionals[:] = positionals[len(arg_counts):]
1899
# consume Positionals and Optionals alternately, until we have
1900
# passed the last option string
1903
if option_string_indices:
1904
max_option_string_index = max(option_string_indices)
1906
max_option_string_index = -1
1907
while start_index <= max_option_string_index:
1909
# consume any Positionals preceding the next option
1910
next_option_string_index = min([
1912
for index in option_string_indices
1913
if index >= start_index])
1914
if start_index != next_option_string_index:
1915
positionals_end_index = consume_positionals(start_index)
1917
# only try to parse the next optional if we didn't consume
1918
# the option string during the positionals parsing
1919
if positionals_end_index > start_index:
1920
start_index = positionals_end_index
1923
start_index = positionals_end_index
1925
# if we consumed all the positionals we could and we're not
1926
# at the index of an option string, there were extra arguments
1927
if start_index not in option_string_indices:
1928
strings = arg_strings[start_index:next_option_string_index]
1929
extras.extend(strings)
1930
start_index = next_option_string_index
1932
# consume the next optional and any arguments for it
1933
start_index = consume_optional(start_index)
1935
# consume any positionals following the last Optional
1936
stop_index = consume_positionals(start_index)
1938
# if we didn't consume all the argument strings, there were extras
1939
extras.extend(arg_strings[stop_index:])
1941
# if we didn't use all the Positional objects, there were too few
1942
# arg strings supplied.
1944
self.error(_('too few arguments'))
1946
# make sure all required actions were present
1947
for action in self._actions:
1949
if action not in seen_actions:
1950
name = _get_action_name(action)
1951
self.error(_('argument %s is required') % name)
1953
# make sure all required groups had one option present
1954
for group in self._mutually_exclusive_groups:
1956
for action in group._group_actions:
1957
if action in seen_non_default_actions:
1960
# if no actions were used, report the error
1962
names = [_get_action_name(action)
1963
for action in group._group_actions
1964
if action.help is not SUPPRESS]
1965
msg = _('one of the arguments %s is required')
1966
self.error(msg % ' '.join(names))
1968
# return the updated namespace and the extra arguments
1969
return namespace, extras
1971
def _read_args_from_files(self, arg_strings):
1972
# expand arguments referencing files
1973
new_arg_strings = []
1974
for arg_string in arg_strings:
1976
# for regular arguments, just add them back into the list
1977
if arg_string[0] not in self.fromfile_prefix_chars:
1978
new_arg_strings.append(arg_string)
1980
# replace arguments referencing files with the file content
1983
args_file = open(arg_string[1:])
1986
for arg_line in args_file.read().splitlines():
1987
for arg in self.convert_arg_line_to_args(arg_line):
1988
arg_strings.append(arg)
1989
arg_strings = self._read_args_from_files(arg_strings)
1990
new_arg_strings.extend(arg_strings)
1994
err = _sys.exc_info()[1]
1995
self.error(str(err))
1997
# return the modified argument list
1998
return new_arg_strings
2000
def convert_arg_line_to_args(self, arg_line):
2003
def _match_argument(self, action, arg_strings_pattern):
2004
# match the pattern for this action to the arg strings
2005
nargs_pattern = self._get_nargs_pattern(action)
2006
match = _re.match(nargs_pattern, arg_strings_pattern)
2008
# raise an exception if we weren't able to find a match
2011
None: _('expected one argument'),
2012
OPTIONAL: _('expected at most one argument'),
2013
ONE_OR_MORE: _('expected at least one argument'),
2015
default = _('expected %s argument(s)') % action.nargs
2016
msg = nargs_errors.get(action.nargs, default)
2017
raise ArgumentError(action, msg)
2019
# return the number of arguments matched
2020
return len(match.group(1))
2022
def _match_arguments_partial(self, actions, arg_strings_pattern):
2023
# progressively shorten the actions list by slicing off the
2024
# final actions until we find a match
2026
for i in range(len(actions), 0, -1):
2027
actions_slice = actions[:i]
2028
pattern = ''.join([self._get_nargs_pattern(action)
2029
for action in actions_slice])
2030
match = _re.match(pattern, arg_strings_pattern)
2031
if match is not None:
2032
result.extend([len(string) for string in match.groups()])
2035
# return the list of arg string counts
2038
def _parse_optional(self, arg_string):
2039
# if it's an empty string, it was meant to be a positional
2043
# if it doesn't start with a prefix, it was meant to be positional
2044
if not arg_string[0] in self.prefix_chars:
2047
# if the option string is present in the parser, return the action
2048
if arg_string in self._option_string_actions:
2049
action = self._option_string_actions[arg_string]
2050
return action, arg_string, None
2052
# if it's just a single character, it was meant to be positional
2053
if len(arg_string) == 1:
2056
# if the option string before the "=" is present, return the action
2057
if '=' in arg_string:
2058
option_string, explicit_arg = arg_string.split('=', 1)
2059
if option_string in self._option_string_actions:
2060
action = self._option_string_actions[option_string]
2061
return action, option_string, explicit_arg
2063
# search through all possible prefixes of the option string
2064
# and all actions in the parser for possible interpretations
2065
option_tuples = self._get_option_tuples(arg_string)
2067
# if multiple actions match, the option string was ambiguous
2068
if len(option_tuples) > 1:
2069
options = ', '.join([option_string
2070
for action, option_string, explicit_arg in option_tuples])
2071
tup = arg_string, options
2072
self.error(_('ambiguous option: %s could match %s') % tup)
2074
# if exactly one action matched, this segmentation is good,
2075
# so return the parsed action
2076
elif len(option_tuples) == 1:
2077
option_tuple, = option_tuples
2080
# if it was not found as an option, but it looks like a negative
2081
# number, it was meant to be positional
2082
# unless there are negative-number-like options
2083
if self._negative_number_matcher.match(arg_string):
2084
if not self._has_negative_number_optionals:
2087
# if it contains a space, it was meant to be a positional
2088
if ' ' in arg_string:
2091
# it was meant to be an optional but there is no such option
2092
# in this parser (though it might be a valid option in a subparser)
2093
return None, arg_string, None
2095
def _get_option_tuples(self, option_string):
2098
# option strings starting with two prefix characters are only
2100
chars = self.prefix_chars
2101
if option_string[0] in chars and option_string[1] in chars:
2102
if '=' in option_string:
2103
option_prefix, explicit_arg = option_string.split('=', 1)
2105
option_prefix = option_string
2107
for option_string in self._option_string_actions:
2108
if option_string.startswith(option_prefix):
2109
action = self._option_string_actions[option_string]
2110
tup = action, option_string, explicit_arg
2113
# single character options can be concatenated with their arguments
2114
# but multiple character options always have to have their argument
2116
elif option_string[0] in chars and option_string[1] not in chars:
2117
option_prefix = option_string
2119
short_option_prefix = option_string[:2]
2120
short_explicit_arg = option_string[2:]
2122
for option_string in self._option_string_actions:
2123
if option_string == short_option_prefix:
2124
action = self._option_string_actions[option_string]
2125
tup = action, option_string, short_explicit_arg
2127
elif option_string.startswith(option_prefix):
2128
action = self._option_string_actions[option_string]
2129
tup = action, option_string, explicit_arg
2132
# shouldn't ever get here
2134
self.error(_('unexpected option string: %s') % option_string)
2136
# return the collected option tuples
2139
def _get_nargs_pattern(self, action):
2140
# in all examples below, we have to allow for '--' args
2141
# which are represented as '-' in the pattern
2142
nargs = action.nargs
2144
# the default (None) is assumed to be a single argument
2146
nargs_pattern = '(-*A-*)'
2148
# allow zero or one arguments
2149
elif nargs == OPTIONAL:
2150
nargs_pattern = '(-*A?-*)'
2152
# allow zero or more arguments
2153
elif nargs == ZERO_OR_MORE:
2154
nargs_pattern = '(-*[A-]*)'
2156
# allow one or more arguments
2157
elif nargs == ONE_OR_MORE:
2158
nargs_pattern = '(-*A[A-]*)'
2160
# allow any number of options or arguments
2161
elif nargs == REMAINDER:
2162
nargs_pattern = '([-AO]*)'
2164
# allow one argument followed by any number of options or arguments
2165
elif nargs == PARSER:
2166
nargs_pattern = '(-*A[-AO]*)'
2168
# all others should be integers
2170
nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2172
# if this is an optional action, -- is not allowed
2173
if action.option_strings:
2174
nargs_pattern = nargs_pattern.replace('-*', '')
2175
nargs_pattern = nargs_pattern.replace('-', '')
2177
# return the pattern
2178
return nargs_pattern
2180
# ========================
2181
# Value conversion methods
2182
# ========================
2183
def _get_values(self, action, arg_strings):
2184
# for everything but PARSER args, strip out '--'
2185
if action.nargs not in [PARSER, REMAINDER]:
2186
arg_strings = [s for s in arg_strings if s != '--']
2188
# optional argument produces a default when not present
2189
if not arg_strings and action.nargs == OPTIONAL:
2190
if action.option_strings:
2191
value = action.const
2193
value = action.default
2194
if isinstance(value, _basestring):
2195
value = self._get_value(action, value)
2196
self._check_value(action, value)
2198
# when nargs='*' on a positional, if there were no command-line
2199
# args, use the default if it is anything other than None
2200
elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2201
not action.option_strings):
2202
if action.default is not None:
2203
value = action.default
2206
self._check_value(action, value)
2208
# single argument or optional argument produces a single value
2209
elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2210
arg_string, = arg_strings
2211
value = self._get_value(action, arg_string)
2212
self._check_value(action, value)
2214
# REMAINDER arguments convert all values, checking none
2215
elif action.nargs == REMAINDER:
2216
value = [self._get_value(action, v) for v in arg_strings]
2218
# PARSER arguments convert all values, but check only the first
2219
elif action.nargs == PARSER:
2220
value = [self._get_value(action, v) for v in arg_strings]
2221
self._check_value(action, value[0])
2223
# all other types of nargs produce a list
2225
value = [self._get_value(action, v) for v in arg_strings]
2227
self._check_value(action, v)
2229
# return the converted value
2232
def _get_value(self, action, arg_string):
2233
type_func = self._registry_get('type', action.type, action.type)
2234
if not _callable(type_func):
2235
msg = _('%r is not callable')
2236
raise ArgumentError(action, msg % type_func)
2238
# convert the value to the appropriate type
2240
result = type_func(arg_string)
2242
# ArgumentTypeErrors indicate errors
2243
except ArgumentTypeError:
2244
name = getattr(action.type, '__name__', repr(action.type))
2245
msg = str(_sys.exc_info()[1])
2246
raise ArgumentError(action, msg)
2248
# TypeErrors or ValueErrors also indicate errors
2249
except (TypeError, ValueError):
2250
name = getattr(action.type, '__name__', repr(action.type))
2251
msg = _('invalid %s value: %r')
2252
raise ArgumentError(action, msg % (name, arg_string))
2254
# return the converted value
2257
def _check_value(self, action, value):
2258
# converted value must be one of the choices (if specified)
2259
if action.choices is not None and value not in action.choices:
2260
tup = value, ', '.join(map(repr, action.choices))
2261
msg = _('invalid choice: %r (choose from %s)') % tup
2262
raise ArgumentError(action, msg)
2264
# =======================
2265
# Help-formatting methods
2266
# =======================
2267
def format_usage(self):
2268
formatter = self._get_formatter()
2269
formatter.add_usage(self.usage, self._actions,
2270
self._mutually_exclusive_groups)
2271
return formatter.format_help()
2273
def format_help(self):
2274
formatter = self._get_formatter()
2277
formatter.add_usage(self.usage, self._actions,
2278
self._mutually_exclusive_groups)
2281
formatter.add_text(self.description)
2283
# positionals, optionals and user-defined groups
2284
for action_group in self._action_groups:
2285
formatter.start_section(action_group.title)
2286
formatter.add_text(action_group.description)
2287
formatter.add_arguments(action_group._group_actions)
2288
formatter.end_section()
2291
formatter.add_text(self.epilog)
2293
# determine help from format above
2294
return formatter.format_help()
2296
def format_version(self):
2299
'The format_version method is deprecated -- the "version" '
2300
'argument to ArgumentParser is no longer supported.',
2302
formatter = self._get_formatter()
2303
formatter.add_text(self.version)
2304
return formatter.format_help()
2306
def _get_formatter(self):
2307
return self.formatter_class(prog=self.prog)
2309
# =====================
2310
# Help-printing methods
2311
# =====================
2312
def print_usage(self, file=None):
2315
self._print_message(self.format_usage(), file)
2317
def print_help(self, file=None):
2320
self._print_message(self.format_help(), file)
2322
def print_version(self, file=None):
2325
'The print_version method is deprecated -- the "version" '
2326
'argument to ArgumentParser is no longer supported.',
2328
self._print_message(self.format_version(), file)
2330
def _print_message(self, message, file=None):
2339
def exit(self, status=0, message=None):
2341
self._print_message(message, _sys.stderr)
2344
def error(self, message):
2345
"""error(message: string)
2347
Prints a usage message incorporating the message to stderr and
2350
If you override this in a subclass, it should not return -- it
2351
should either exit or raise an exception.
2353
self.print_usage(_sys.stderr)
2354
self.exit(2, _('%s: error: %s\n') % (self.prog, message))