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

Skip to content

Latest commit

 

History

History
2603 lines (2156 loc) · 96.4 KB

File metadata and controls

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