Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Latest commit

 

History

History
2571 lines (2130 loc) · 95.4 KB

File metadata and controls

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