-
-
Notifications
You must be signed in to change notification settings - Fork 34.5k
Expand file tree
/
Copy pathargparse.py
More file actions
2510 lines (2078 loc) · 93.3 KB
/
argparse.py
File metadata and controls
2510 lines (2078 loc) · 93.3 KB
Edit and raw actions
OlderNewer
1
# Author: Steven J. Bethard <[email protected]>.
2
3
"""Command-line parsing library
4
5
This module is an optparse-inspired command-line parsing library that:
6
7
- handles both optional and positional arguments
8
- produces highly informative usage messages
9
- supports parsers that dispatch to sub-parsers
10
11
The following is a simple usage example that sums integers from the
12
command-line and writes the result to a file::
13
14
parser = argparse.ArgumentParser(
15
description='sum the integers at the command line')
16
parser.add_argument(
17
'integers', metavar='int', nargs='+', type=int,
18
help='an integer to be summed')
19
parser.add_argument(
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))
24
args.log.close()
25
26
The module contains the following public classes:
27
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.
33
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.
38
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.
42
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.
48
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
56
to the help.
57
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.)
62
"""
63
64
__version__ = '1.1'
65
__all__ = [
66
'ArgumentParser',
67
'ArgumentError',
68
'ArgumentTypeError',
69
'FileType',
70
'HelpFormatter',
71
'ArgumentDefaultsHelpFormatter',
72
'RawDescriptionHelpFormatter',
73
'RawTextHelpFormatter',
74
'MetavarTypeHelpFormatter',
75
'Namespace',
76
'Action',
77
'ONE_OR_MORE',
78
'OPTIONAL',
79
'PARSER',
80
'REMAINDER',
81
'SUPPRESS',
82
'ZERO_OR_MORE',
83
]
84
85
86
import os as _os
87
import re as _re
88
import shutil as _shutil
89
import sys as _sys
90
91
from gettext import gettext as _, ngettext
92
93
SUPPRESS = '==SUPPRESS=='
94
95
OPTIONAL = '?'
96
ZERO_OR_MORE = '*'
97
ONE_OR_MORE = '+'
98
PARSER = 'A...'
99
REMAINDER = '...'
100
_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
101
102
# =============================
103
# Utility functions and classes
104
# =============================
105
106
class _AttributeHolder(object):
107
"""Abstract base class that provides __repr__.
108
109
The __repr__ method returns a string in the format::
110
ClassName(attr=name, attr=name, ...)
111
The attributes are determined either by a class-level attribute,
112
'_kwarg_names', or by inspecting the instance __dict__.
113
"""
114
115
def __repr__(self):
116
type_name = type(self).__name__
117
arg_strings = []
118
star_args = {}
119
for arg in self._get_args():
120
arg_strings.append(repr(arg))
121
for name, value in self._get_kwargs():
122
if name.isidentifier():
123
arg_strings.append('%s=%r' % (name, value))
124
else:
125
star_args[name] = value
126
if star_args:
127
arg_strings.append('**%s' % repr(star_args))
128
return '%s(%s)' % (type_name, ', '.join(arg_strings))
129
130
def _get_kwargs(self):
131
return sorted(self.__dict__.items())
132
133
def _get_args(self):
134
return []
135
136
137
def _copy_items(items):
138
if items is None:
139
return []
140
# The copy module is used only in the 'append' and 'append_const'
141
# actions, and it is needed only when the default value isn't a list.
142
# Delay its import for speeding up the common case.
143
if type(items) is list:
144
return items[:]
145
import copy
146
return copy.copy(items)
147
148
149
# ===============
150
# Formatting Help
151
# ===============
152
153
class HelpFormatter(object):
154
"""Formatter for generating usage messages and argument help strings.
155
156
Only the name of this class is considered a public API. All the methods
157
provided by the class are considered an implementation detail.
158
"""
159
160
def __init__(self,
161
prog,
162
indent_increment=2,
163
max_help_position=24,
164
width=None):
165
166
# default setting for width
167
if width is None:
168
width = _shutil.get_terminal_size().columns
169
width -= 2
170
171
self._prog = prog
172
self._indent_increment = indent_increment
173
self._max_help_position = min(max_help_position,
174
max(width - 20, indent_increment * 2))
175
self._width = width
176
177
self._current_indent = 0
178
self._level = 0
179
self._action_max_length = 0
180
181
self._root_section = self._Section(self, None)
182
self._current_section = self._root_section
183
184
self._whitespace_matcher = _re.compile(r'\s+', _re.ASCII)
185
self._long_break_matcher = _re.compile(r'\n\n\n+')
186
187
# ===============================
188
# Section and indentation methods
189
# ===============================
190
def _indent(self):
191
self._current_indent += self._indent_increment
192
self._level += 1
193
194
def _dedent(self):
195
self._current_indent -= self._indent_increment
196
assert self._current_indent >= 0, 'Indent decreased below 0.'
197
self._level -= 1
198
199
class _Section(object):
200
201
def __init__(self, formatter, parent, heading=None):
202
self.formatter = formatter
203
self.parent = parent
204
self.heading = heading
205
self.items = []
206
207
def format_help(self):
208
# format the indented section
209
if self.parent is not None:
210
self.formatter._indent()
211
join = self.formatter._join_parts
212
item_help = join([func(*args) for func, args in self.items])
213
if self.parent is not None:
214
self.formatter._dedent()
215
216
# return nothing if the section was empty
217
if not item_help:
218
return ''
219
220
# add the heading if the section was non-empty
221
if self.heading is not SUPPRESS and self.heading is not None:
222
current_indent = self.formatter._current_indent
223
heading = '%*s%s:\n' % (current_indent, '', self.heading)
224
else:
225
heading = ''
226
227
# join the section-initial newline, the heading and the help
228
return join(['\n', heading, item_help, '\n'])
229
230
def _add_item(self, func, args):
231
self._current_section.items.append((func, args))
232
233
# ========================
234
# Message building methods
235
# ========================
236
def start_section(self, heading):
237
self._indent()
238
section = self._Section(self, self._current_section, heading)
239
self._add_item(section.format_help, [])
240
self._current_section = section
241
242
def end_section(self):
243
self._current_section = self._current_section.parent
244
self._dedent()
245
246
def add_text(self, text):
247
if text is not SUPPRESS and text is not None:
248
self._add_item(self._format_text, [text])
249
250
def add_usage(self, usage, actions, groups, prefix=None):
251
if usage is not SUPPRESS:
252
args = usage, actions, groups, prefix
253
self._add_item(self._format_usage, args)
254
255
def add_argument(self, action):
256
if action.help is not SUPPRESS:
257
258
# find all invocations
259
get_invocation = self._format_action_invocation
260
invocations = [get_invocation(action)]
261
for subaction in self._iter_indented_subactions(action):
262
invocations.append(get_invocation(subaction))
263
264
# update the maximum item length
265
invocation_length = max([len(s) for s in invocations])
266
action_length = invocation_length + self._current_indent
267
self._action_max_length = max(self._action_max_length,
268
action_length)
269
270
# add the item to the list
271
self._add_item(self._format_action, [action])
272
273
def add_arguments(self, actions):
274
for action in actions:
275
self.add_argument(action)
276
277
# =======================
278
# Help-formatting methods
279
# =======================
280
def format_help(self):
281
help = self._root_section.format_help()
282
if help:
283
help = self._long_break_matcher.sub('\n\n', help)
284
help = help.strip('\n') + '\n'
285
return help
286
287
def _join_parts(self, part_strings):
288
return ''.join([part
289
for part in part_strings
290
if part and part is not SUPPRESS])
291
292
def _format_usage(self, usage, actions, groups, prefix):
293
if prefix is None:
294
prefix = _('usage: ')
295
296
# if usage is specified, use that
297
if usage is not None:
298
usage = usage % dict(prog=self._prog)
299
300
# if no optionals or positionals are available, usage is just prog
301
elif usage is None and not actions:
302
usage = '%(prog)s' % dict(prog=self._prog)
303
304
# if optionals and positionals are available, calculate usage
305
elif usage is None:
306
prog = '%(prog)s' % dict(prog=self._prog)
307
308
# split optionals from positionals
309
optionals = []
310
positionals = []
311
for action in actions:
312
if action.option_strings:
313
optionals.append(action)
314
else:
315
positionals.append(action)
316
317
# build full usage string
318
format = self._format_actions_usage
319
action_usage = format(optionals + positionals, groups)
320
usage = ' '.join([s for s in [prog, action_usage] if s])
321
322
# wrap the usage parts if it's too long
323
text_width = self._width - self._current_indent
324
if len(prefix) + len(usage) > text_width:
325
326
# break usage into wrappable parts
327
part_regexp = (
328
r'\(.*?\)+(?=\s|$)|'
329
r'\[.*?\]+(?=\s|$)|'
330
r'\S+'
331
)
332
opt_usage = format(optionals, groups)
333
pos_usage = format(positionals, groups)
334
opt_parts = _re.findall(part_regexp, opt_usage)
335
pos_parts = _re.findall(part_regexp, pos_usage)
336
assert ' '.join(opt_parts) == opt_usage
337
assert ' '.join(pos_parts) == pos_usage
338
339
# helper for wrapping lines
340
def get_lines(parts, indent, prefix=None):
341
lines = []
342
line = []
343
if prefix is not None:
344
line_len = len(prefix) - 1
345
else:
346
line_len = len(indent) - 1
347
for part in parts:
348
if line_len + 1 + len(part) > text_width and line:
349
lines.append(indent + ' '.join(line))
350
line = []
351
line_len = len(indent) - 1
352
line.append(part)
353
line_len += len(part) + 1
354
if line:
355
lines.append(indent + ' '.join(line))
356
if prefix is not None:
357
lines[0] = lines[0][len(indent):]
358
return lines
359
360
# if prog is short, follow it with optionals or positionals
361
if len(prefix) + len(prog) <= 0.75 * text_width:
362
indent = ' ' * (len(prefix) + len(prog) + 1)
363
if opt_parts:
364
lines = get_lines([prog] + opt_parts, indent, prefix)
365
lines.extend(get_lines(pos_parts, indent))
366
elif pos_parts:
367
lines = get_lines([prog] + pos_parts, indent, prefix)
368
else:
369
lines = [prog]
370
371
# if prog is long, put it on its own line
372
else:
373
indent = ' ' * len(prefix)
374
parts = opt_parts + pos_parts
375
lines = get_lines(parts, indent)
376
if len(lines) > 1:
377
lines = []
378
lines.extend(get_lines(opt_parts, indent))
379
lines.extend(get_lines(pos_parts, indent))
380
lines = [prog] + lines
381
382
# join lines into usage
383
usage = '\n'.join(lines)
384
385
# prefix with 'usage:'
386
return '%s%s\n\n' % (prefix, usage)
387
388
def _format_actions_usage(self, actions, groups):
389
# find group indices and identify actions in groups
390
group_actions = set()
391
inserts = {}
392
for group in groups:
393
try:
394
start = actions.index(group._group_actions[0])
395
except ValueError:
396
continue
397
else:
398
end = start + len(group._group_actions)
399
if actions[start:end] == group._group_actions:
400
for action in group._group_actions:
401
group_actions.add(action)
402
if not group.required:
403
if start in inserts:
404
inserts[start] += ' ['
405
else:
406
inserts[start] = '['
407
inserts[end] = ']'
408
else:
409
if start in inserts:
410
inserts[start] += ' ('
411
else:
412
inserts[start] = '('
413
inserts[end] = ')'
414
for i in range(start + 1, end):
415
inserts[i] = '|'
416
417
# collect all actions format strings
418
parts = []
419
for i, action in enumerate(actions):
420
421
# suppressed arguments are marked with None
422
# remove | separators for suppressed arguments
423
if action.help is SUPPRESS:
424
parts.append(None)
425
if inserts.get(i) == '|':
426
inserts.pop(i)
427
elif inserts.get(i + 1) == '|':
428
inserts.pop(i + 1)
429
430
# produce all arg strings
431
elif not action.option_strings:
432
default = self._get_default_metavar_for_positional(action)
433
part = self._format_args(action, default)
434
435
# if it's in a group, strip the outer []
436
if action in group_actions:
437
if part[0] == '[' and part[-1] == ']':
438
part = part[1:-1]
439
440
# add the action string to the list
441
parts.append(part)
442
443
# produce the first way to invoke the option in brackets
444
else:
445
option_string = action.option_strings[0]
446
447
# if the Optional doesn't take a value, format is:
448
# -s or --long
449
if action.nargs == 0:
450
part = '%s' % option_string
451
452
# if the Optional takes a value, format is:
453
# -s ARGS or --long ARGS
454
else:
455
default = self._get_default_metavar_for_optional(action)
456
args_string = self._format_args(action, default)
457
part = '%s %s' % (option_string, args_string)
458
459
# make it look optional if it's not required or in a group
460
if not action.required and action not in group_actions:
461
part = '[%s]' % part
462
463
# add the action string to the list
464
parts.append(part)
465
466
# insert things at the necessary indices
467
for i in sorted(inserts, reverse=True):
468
parts[i:i] = [inserts[i]]
469
470
# join all the action items with spaces
471
text = ' '.join([item for item in parts if item is not None])
472
473
# clean up separators for mutually exclusive groups
474
open = r'[\[(]'
475
close = r'[\])]'
476
text = _re.sub(r'(%s) ' % open, r'\1', text)
477
text = _re.sub(r' (%s)' % close, r'\1', text)
478
text = _re.sub(r'%s *%s' % (open, close), r'', text)
479
text = _re.sub(r'\(([^|]*)\)', r'\1', text)
480
text = text.strip()
481
482
# return the text
483
return text
484
485
def _format_text(self, text):
486
if '%(prog)' in text:
487
text = text % dict(prog=self._prog)
488
text_width = max(self._width - self._current_indent, 11)
489
indent = ' ' * self._current_indent
490
return self._fill_text(text, text_width, indent) + '\n\n'
491
492
def _format_action(self, action):
493
# determine the required width and the entry label
494
help_position = min(self._action_max_length + 2,
495
self._max_help_position)
496
help_width = max(self._width - help_position, 11)
497
action_width = help_position - self._current_indent - 2
498
action_header = self._format_action_invocation(action)
499
500
# no help; start on same line and add a final newline
501
if not action.help:
502
tup = self._current_indent, '', action_header
503
action_header = '%*s%s\n' % tup
504
505
# short action name; start on the same line and pad two spaces
506
elif len(action_header) <= action_width:
507
tup = self._current_indent, '', action_width, action_header
508
action_header = '%*s%-*s ' % tup
509
indent_first = 0
510
511
# long action name; start on the next line
512
else:
513
tup = self._current_indent, '', action_header
514
action_header = '%*s%s\n' % tup
515
indent_first = help_position
516
517
# collect the pieces of the action help
518
parts = [action_header]
519
520
# if there was help for the action, add lines of help text
521
if action.help:
522
help_text = self._expand_help(action)
523
help_lines = self._split_lines(help_text, help_width)
524
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
525
for line in help_lines[1:]:
526
parts.append('%*s%s\n' % (help_position, '', line))
527
528
# or add a newline if the description doesn't end with one
529
elif not action_header.endswith('\n'):
530
parts.append('\n')
531
532
# if there are any sub-actions, add their help as well
533
for subaction in self._iter_indented_subactions(action):
534
parts.append(self._format_action(subaction))
535
536
# return a single string
537
return self._join_parts(parts)
538
539
def _format_action_invocation(self, action):
540
if not action.option_strings:
541
default = self._get_default_metavar_for_positional(action)
542
metavar, = self._metavar_formatter(action, default)(1)
543
return metavar
544
545
else:
546
parts = []
547
548
# if the Optional doesn't take a value, format is:
549
# -s, --long
550
if action.nargs == 0:
551
parts.extend(action.option_strings)
552
553
# if the Optional takes a value, format is:
554
# -s ARGS, --long ARGS
555
else:
556
default = self._get_default_metavar_for_optional(action)
557
args_string = self._format_args(action, default)
558
for option_string in action.option_strings:
559
parts.append('%s %s' % (option_string, args_string))
560
561
return ', '.join(parts)
562
563
def _metavar_formatter(self, action, default_metavar):
564
if action.metavar is not None:
565
result = action.metavar
566
elif action.choices is not None:
567
choice_strs = [str(choice) for choice in action.choices]
568
result = '{%s}' % ','.join(choice_strs)
569
else:
570
result = default_metavar
571
572
def format(tuple_size):
573
if isinstance(result, tuple):
574
return result
575
else:
576
return (result, ) * tuple_size
577
return format
578
579
def _format_args(self, action, default_metavar):
580
get_metavar = self._metavar_formatter(action, default_metavar)
581
if action.nargs is None:
582
result = '%s' % get_metavar(1)
583
elif action.nargs == OPTIONAL:
584
result = '[%s]' % get_metavar(1)
585
elif action.nargs == ZERO_OR_MORE:
586
result = '[%s [%s ...]]' % get_metavar(2)
587
elif action.nargs == ONE_OR_MORE:
588
result = '%s [%s ...]' % get_metavar(2)
589
elif action.nargs == REMAINDER:
590
result = '...'
591
elif action.nargs == PARSER:
592
result = '%s ...' % get_metavar(1)
593
elif action.nargs == SUPPRESS:
594
result = ''
595
else:
596
try:
597
formats = ['%s' for _ in range(action.nargs)]
598
except TypeError:
599
raise ValueError("invalid nargs value") from None
600
result = ' '.join(formats) % get_metavar(action.nargs)
601
return result
602
603
def _expand_help(self, action):
604
params = dict(vars(action), prog=self._prog)
605
for name in list(params):
606
if params[name] is SUPPRESS:
607
del params[name]
608
for name in list(params):
609
if hasattr(params[name], '__name__'):
610
params[name] = params[name].__name__
611
if params.get('choices') is not None:
612
choices_str = ', '.join([str(c) for c in params['choices']])
613
params['choices'] = choices_str
614
return self._get_help_string(action) % params
615
616
def _iter_indented_subactions(self, action):
617
try:
618
get_subactions = action._get_subactions
619
except AttributeError:
620
pass
621
else:
622
self._indent()
623
yield from get_subactions()
624
self._dedent()
625
626
def _split_lines(self, text, width):
627
text = self._whitespace_matcher.sub(' ', text).strip()
628
# The textwrap module is used only for formatting help.
629
# Delay its import for speeding up the common usage of argparse.
630
import textwrap
631
return textwrap.wrap(text, width)
632
633
def _fill_text(self, text, width, indent):
634
text = self._whitespace_matcher.sub(' ', text).strip()
635
import textwrap
636
return textwrap.fill(text, width,
637
initial_indent=indent,
638
subsequent_indent=indent)
639
640
def _get_help_string(self, action):
641
return action.help
642
643
def _get_default_metavar_for_optional(self, action):
644
return action.dest.upper()
645
646
def _get_default_metavar_for_positional(self, action):
647
return action.dest
648
649
650
class RawDescriptionHelpFormatter(HelpFormatter):
651
"""Help message formatter which retains any formatting in descriptions.
652
653
Only the name of this class is considered a public API. All the methods
654
provided by the class are considered an implementation detail.
655
"""
656
657
def _fill_text(self, text, width, indent):
658
return ''.join(indent + line for line in text.splitlines(keepends=True))
659
660
661
class RawTextHelpFormatter(RawDescriptionHelpFormatter):
662
"""Help message formatter which retains formatting of all help text.
663
664
Only the name of this class is considered a public API. All the methods
665
provided by the class are considered an implementation detail.
666
"""
667
668
def _split_lines(self, text, width):
669
return text.splitlines()
670
671
672
class ArgumentDefaultsHelpFormatter(HelpFormatter):
673
"""Help message formatter which adds default values to argument help.
674
675
Only the name of this class is considered a public API. All the methods
676
provided by the class are considered an implementation detail.
677
"""
678
679
def _get_help_string(self, action):
680
help = action.help
681
if '%(default)' not in action.help:
682
if action.default is not SUPPRESS:
683
defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
684
if action.option_strings or action.nargs in defaulting_nargs:
685
help += ' (default: %(default)s)'
686
return help
687
688
689
class MetavarTypeHelpFormatter(HelpFormatter):
690
"""Help message formatter which uses the argument 'type' as the default
691
metavar value (instead of the argument 'dest')
692
693
Only the name of this class is considered a public API. All the methods
694
provided by the class are considered an implementation detail.
695
"""
696
697
def _get_default_metavar_for_optional(self, action):
698
return action.type.__name__
699
700
def _get_default_metavar_for_positional(self, action):
701
return action.type.__name__
702
703
704
705
# =====================
706
# Options and Arguments
707
# =====================
708
709
def _get_action_name(argument):
710
if argument is None:
711
return None
712
elif argument.option_strings:
713
return '/'.join(argument.option_strings)
714
elif argument.metavar not in (None, SUPPRESS):
715
return argument.metavar
716
elif argument.dest not in (None, SUPPRESS):
717
return argument.dest
718
else:
719
return None
720
721
722
class ArgumentError(Exception):
723
"""An error from creating or using an argument (optional or positional).
724
725
The string value of this exception is the message, augmented with
726
information about the argument that caused it.
727
"""
728
729
def __init__(self, argument, message):
730
self.argument_name = _get_action_name(argument)
731
self.message = message
732
733
def __str__(self):
734
if self.argument_name is None:
735
format = '%(message)s'
736
else:
737
format = 'argument %(argument_name)s: %(message)s'
738
return format % dict(message=self.message,
739
argument_name=self.argument_name)
740
741
742
class ArgumentTypeError(Exception):
743
"""An error from trying to convert a command line string to a type."""
744
pass
745
746
747
# ==============
748
# Action classes
749
# ==============
750
751
class Action(_AttributeHolder):
752
"""Information about how to convert command line strings to Python objects.
753
754
Action objects are used by an ArgumentParser to represent the information
755
needed to parse a single argument from one or more strings from the
756
command line. The keyword arguments to the Action constructor are also
757
all attributes of Action instances.
758
759
Keyword Arguments:
760
761
- option_strings -- A list of command-line option strings which
762
should be associated with this action.
763
764
- dest -- The name of the attribute to hold the created object(s)
765
766
- nargs -- The number of command-line arguments that should be
767
consumed. By default, one argument will be consumed and a single
768
value will be produced. Other values include:
769
- N (an integer) consumes N arguments (and produces a list)
770
- '?' consumes zero or one arguments
771
- '*' consumes zero or more arguments (and produces a list)
772
- '+' consumes one or more arguments (and produces a list)
773
Note that the difference between the default and nargs=1 is that
774
with the default, a single value will be produced, while with
775
nargs=1, a list containing a single value will be produced.
776
777
- const -- The value to be produced if the option is specified and the
778
option uses an action that takes no values.
779
780
- default -- The value to be produced if the option is not specified.
781
782
- type -- A callable that accepts a single string argument, and
783
returns the converted value. The standard Python types str, int,
784
float, and complex are useful examples of such callables. If None,
785
str is used.
786
787
- choices -- A container of values that should be allowed. If not None,
788
after a command-line argument has been converted to the appropriate
789
type, an exception will be raised if it is not a member of this
790
collection.
791
792
- required -- True if the action must always be specified at the
793
command line. This is only meaningful for optional command-line
794
arguments.
795
796
- help -- The help string describing the argument.
797
798
- metavar -- The name to be used for the option's argument with the
799
help string. If None, the 'dest' value will be used as the name.
800
"""
801
802
def __init__(self,
803
option_strings,
804
dest,
805
nargs=None,
806
const=None,
807
default=None,
808
type=None,
809
choices=None,
810
required=False,
811
help=None,
812
metavar=None):
813
self.option_strings = option_strings
814
self.dest = dest
815
self.nargs = nargs
816
self.const = const
817
self.default = default
818
self.type = type
819
self.choices = choices
820
self.required = required
821
self.help = help
822
self.metavar = metavar
823
824
def _get_kwargs(self):
825
names = [
826
'option_strings',
827
'dest',
828
'nargs',
829
'const',
830
'default',
831
'type',
832
'choices',
833
'help',
834
'metavar',
835
]
836
return [(name, getattr(self, name)) for name in names]
837
838
def __call__(self, parser, namespace, values, option_string=None):
839
raise NotImplementedError(_('.__call__() not defined'))
840
841
842
class _StoreAction(Action):
843
844
def __init__(self,
845
option_strings,
846
dest,
847
nargs=None,
848
const=None,
849
default=None,
850
type=None,
851
choices=None,
852
required=False,
853
help=None,
854
metavar=None):
855
if nargs == 0:
856
raise ValueError('nargs for store actions must be != 0; if you '
857
'have nothing to store, actions such as store '
858
'true or store const may be more appropriate')
859
if const is not None and nargs != OPTIONAL:
860
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
861
super(_StoreAction, self).__init__(
862
option_strings=option_strings,
863
dest=dest,
864
nargs=nargs,
865
const=const,
866
default=default,
867
type=type,
868
choices=choices,
869
required=required,
870
help=help,
871
metavar=metavar)
872
873
def __call__(self, parser, namespace, values, option_string=None):
874
setattr(namespace, self.dest, values)
875
876
877
class _StoreConstAction(Action):
878
879
def __init__(self,
880
option_strings,
881
dest,
882
const,
883
default=None,
884
required=False,
885
help=None,
886
metavar=None):
887
super(_StoreConstAction, self).__init__(
888
option_strings=option_strings,
889
dest=dest,
890
nargs=0,
891
const=const,
892
default=default,
893
required=required,
894
help=help)
895
896
def __call__(self, parser, namespace, values, option_string=None):
897
setattr(namespace, self.dest, self.const)
898
899
900
class _StoreTrueAction(_StoreConstAction):
901
902
def __init__(self,
903
option_strings,
904
dest,
905
default=False,
906
required=False,
907
help=None):
908
super(_StoreTrueAction, self).__init__(
909
option_strings=option_strings,
910
dest=dest,
911
const=True,
912
default=default,
913
required=required,
914
help=help)
915
916
917
class _StoreFalseAction(_StoreConstAction):
918
919
def __init__(self,
920
option_strings,
921
dest,
922
default=True,
923
required=False,
924
help=None):
925
super(_StoreFalseAction, self).__init__(
926
option_strings=option_strings,
927
dest=dest,
928
const=False,
929
default=default,
930
required=required,
931
help=help)
932
933
934
class _AppendAction(Action):
935
936
def __init__(self,
937
option_strings,
938
dest,
939
nargs=None,
940
const=None,
941
default=None,
942
type=None,
943
choices=None,
944
required=False,
945
help=None,
946
metavar=None):
947
if nargs == 0:
948
raise ValueError('nargs for append actions must be != 0; if arg '
949
'strings are not supplying the value to append, '
950
'the append const action may be more appropriate')
951
if const is not None and nargs != OPTIONAL:
952
raise ValueError('nargs must be %r to supply const' % OPTIONAL)
953
super(_AppendAction, self).__init__(
954
option_strings=option_strings,
955
dest=dest,
956
nargs=nargs,
957
const=const,
958
default=default,
959
type=type,
960
choices=choices,
961
required=required,
962
help=help,
963
metavar=metavar)
964
965
def __call__(self, parser, namespace, values, option_string=None):
966
items = getattr(namespace, self.dest, None)
967
items = _copy_items(items)
968
items.append(values)
969
setattr(namespace, self.dest, items)
970
971
972
class _AppendConstAction(Action):
973
974
def __init__(self,
975
option_strings,
976
dest,
977
const,
978
default=None,
979
required=False,
980
help=None,
981
metavar=None):
982
super(_AppendConstAction, self).__init__(
983
option_strings=option_strings,
984
dest=dest,
985
nargs=0,
986
const=const,
987
default=default,
988
required=required,
989
help=help,
990
metavar=metavar)
991
992
def __call__(self, parser, namespace, values, option_string=None):
993
items = getattr(namespace, self.dest, None)
994
items = _copy_items(items)
995
items.append(self.const)
996
setattr(namespace, self.dest, items)
997
998
999
class _CountAction(Action):
1000