ยปCore Development>Code coverage>Lib/argparse.py

Python code coverage for Lib/argparse.py

#countcontent
1n/a# Author: Steven J. Bethard <steven.bethard@gmail.com>.
2n/a
3n/a"""Command-line parsing library
4n/a
5n/aThis module is an optparse-inspired command-line parsing library that:
6n/a
7n/a - handles both optional and positional arguments
8n/a - produces highly informative usage messages
9n/a - supports parsers that dispatch to sub-parsers
10n/a
11n/aThe following is a simple usage example that sums integers from the
12n/acommand-line and writes the result to a file::
13n/a
14n/a parser = argparse.ArgumentParser(
15n/a description='sum the integers at the command line')
16n/a parser.add_argument(
17n/a 'integers', metavar='int', nargs='+', type=int,
18n/a help='an integer to be summed')
19n/a parser.add_argument(
20n/a '--log', default=sys.stdout, type=argparse.FileType('w'),
21n/a help='the file where the sum should be written')
22n/a args = parser.parse_args()
23n/a args.log.write('%s' % sum(args.integers))
24n/a args.log.close()
25n/a
26n/aThe module contains the following public classes:
27n/a
28n/a - ArgumentParser -- The main entry point for command-line parsing. As the
29n/a example above shows, the add_argument() method is used to populate
30n/a the parser with actions for optional and positional arguments. Then
31n/a the parse_args() method is invoked to convert the args at the
32n/a command-line into an object with attributes.
33n/a
34n/a - ArgumentError -- The exception raised by ArgumentParser objects when
35n/a there are errors with the parser's actions. Errors raised while
36n/a parsing the command-line are caught by ArgumentParser and emitted
37n/a as command-line messages.
38n/a
39n/a - FileType -- A factory for defining types of files to be created. As the
40n/a example above shows, instances of FileType are typically passed as
41n/a the type= argument of add_argument() calls.
42n/a
43n/a - Action -- The base class for parser actions. Typically actions are
44n/a selected by passing strings like 'store_true' or 'append_const' to
45n/a the action= argument of add_argument(). However, for greater
46n/a customization of ArgumentParser actions, subclasses of Action may
47n/a be defined and passed as the action= argument.
48n/a
49n/a - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
50n/a ArgumentDefaultsHelpFormatter -- Formatter classes which
51n/a may be passed as the formatter_class= argument to the
52n/a ArgumentParser constructor. HelpFormatter is the default,
53n/a RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
54n/a not to change the formatting for help text, and
55n/a ArgumentDefaultsHelpFormatter adds information about argument defaults
56n/a to the help.
57n/a
58n/aAll other classes in this module are considered implementation details.
59n/a(Also note that HelpFormatter and RawDescriptionHelpFormatter are only
60n/aconsidered public as object names -- the API of the formatter objects is
61n/astill considered an implementation detail.)
62n/a"""
63n/a
64n/a__version__ = '1.1'
65n/a__all__ = [
66n/a 'ArgumentParser',
67n/a 'ArgumentError',
68n/a 'ArgumentTypeError',
69n/a 'FileType',
70n/a 'HelpFormatter',
71n/a 'ArgumentDefaultsHelpFormatter',
72n/a 'RawDescriptionHelpFormatter',
73n/a 'RawTextHelpFormatter',
74n/a 'MetavarTypeHelpFormatter',
75n/a 'Namespace',
76n/a 'Action',
77n/a 'ONE_OR_MORE',
78n/a 'OPTIONAL',
79n/a 'PARSER',
80n/a 'REMAINDER',
81n/a 'SUPPRESS',
82n/a 'ZERO_OR_MORE',
83n/a]
84n/a
85n/a
86n/aimport collections as _collections
87n/aimport copy as _copy
88n/aimport os as _os
89n/aimport re as _re
90n/aimport sys as _sys
91n/aimport textwrap as _textwrap
92n/a
93n/afrom gettext import gettext as _, ngettext
94n/a
95n/a
96n/aSUPPRESS = '==SUPPRESS=='
97n/a
98n/aOPTIONAL = '?'
99n/aZERO_OR_MORE = '*'
100n/aONE_OR_MORE = '+'
101n/aPARSER = 'A...'
102n/aREMAINDER = '...'
103n/a_UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args'
104n/a
105n/a# =============================
106n/a# Utility functions and classes
107n/a# =============================
108n/a
109n/aclass _AttributeHolder(object):
110n/a """Abstract base class that provides __repr__.
111n/a
112n/a The __repr__ method returns a string in the format::
113n/a ClassName(attr=name, attr=name, ...)
114n/a The attributes are determined either by a class-level attribute,
115n/a '_kwarg_names', or by inspecting the instance __dict__.
116n/a """
117n/a
118n/a def __repr__(self):
119n/a type_name = type(self).__name__
120n/a arg_strings = []
121n/a star_args = {}
122n/a for arg in self._get_args():
123n/a arg_strings.append(repr(arg))
124n/a for name, value in self._get_kwargs():
125n/a if name.isidentifier():
126n/a arg_strings.append('%s=%r' % (name, value))
127n/a else:
128n/a star_args[name] = value
129n/a if star_args:
130n/a arg_strings.append('**%s' % repr(star_args))
131n/a return '%s(%s)' % (type_name, ', '.join(arg_strings))
132n/a
133n/a def _get_kwargs(self):
134n/a return sorted(self.__dict__.items())
135n/a
136n/a def _get_args(self):
137n/a return []
138n/a
139n/a
140n/adef _ensure_value(namespace, name, value):
141n/a if getattr(namespace, name, None) is None:
142n/a setattr(namespace, name, value)
143n/a return getattr(namespace, name)
144n/a
145n/a
146n/a# ===============
147n/a# Formatting Help
148n/a# ===============
149n/a
150n/aclass HelpFormatter(object):
151n/a """Formatter for generating usage messages and argument help strings.
152n/a
153n/a Only the name of this class is considered a public API. All the methods
154n/a provided by the class are considered an implementation detail.
155n/a """
156n/a
157n/a def __init__(self,
158n/a prog,
159n/a indent_increment=2,
160n/a max_help_position=24,
161n/a width=None):
162n/a
163n/a # default setting for width
164n/a if width is None:
165n/a try:
166n/a width = int(_os.environ['COLUMNS'])
167n/a except (KeyError, ValueError):
168n/a width = 80
169n/a width -= 2
170n/a
171n/a self._prog = prog
172n/a self._indent_increment = indent_increment
173n/a self._max_help_position = max_help_position
174n/a self._max_help_position = min(max_help_position,
175n/a max(width - 20, indent_increment * 2))
176n/a self._width = width
177n/a
178n/a self._current_indent = 0
179n/a self._level = 0
180n/a self._action_max_length = 0
181n/a
182n/a self._root_section = self._Section(self, None)
183n/a self._current_section = self._root_section
184n/a
185n/a self._whitespace_matcher = _re.compile(r'\s+', _re.ASCII)
186n/a self._long_break_matcher = _re.compile(r'\n\n\n+')
187n/a
188n/a # ===============================
189n/a # Section and indentation methods
190n/a # ===============================
191n/a def _indent(self):
192n/a self._current_indent += self._indent_increment
193n/a self._level += 1
194n/a
195n/a def _dedent(self):
196n/a self._current_indent -= self._indent_increment
197n/a assert self._current_indent >= 0, 'Indent decreased below 0.'
198n/a self._level -= 1
199n/a
200n/a class _Section(object):
201n/a
202n/a def __init__(self, formatter, parent, heading=None):
203n/a self.formatter = formatter
204n/a self.parent = parent
205n/a self.heading = heading
206n/a self.items = []
207n/a
208n/a def format_help(self):
209n/a # format the indented section
210n/a if self.parent is not None:
211n/a self.formatter._indent()
212n/a join = self.formatter._join_parts
213n/a item_help = join([func(*args) for func, args in self.items])
214n/a if self.parent is not None:
215n/a self.formatter._dedent()
216n/a
217n/a # return nothing if the section was empty
218n/a if not item_help:
219n/a return ''
220n/a
221n/a # add the heading if the section was non-empty
222n/a if self.heading is not SUPPRESS and self.heading is not None:
223n/a current_indent = self.formatter._current_indent
224n/a heading = '%*s%s:\n' % (current_indent, '', self.heading)
225n/a else:
226n/a heading = ''
227n/a
228n/a # join the section-initial newline, the heading and the help
229n/a return join(['\n', heading, item_help, '\n'])
230n/a
231n/a def _add_item(self, func, args):
232n/a self._current_section.items.append((func, args))
233n/a
234n/a # ========================
235n/a # Message building methods
236n/a # ========================
237n/a def start_section(self, heading):
238n/a self._indent()
239n/a section = self._Section(self, self._current_section, heading)
240n/a self._add_item(section.format_help, [])
241n/a self._current_section = section
242n/a
243n/a def end_section(self):
244n/a self._current_section = self._current_section.parent
245n/a self._dedent()
246n/a
247n/a def add_text(self, text):
248n/a if text is not SUPPRESS and text is not None:
249n/a self._add_item(self._format_text, [text])
250n/a
251n/a def add_usage(self, usage, actions, groups, prefix=None):
252n/a if usage is not SUPPRESS:
253n/a args = usage, actions, groups, prefix
254n/a self._add_item(self._format_usage, args)
255n/a
256n/a def add_argument(self, action):
257n/a if action.help is not SUPPRESS:
258n/a
259n/a # find all invocations
260n/a get_invocation = self._format_action_invocation
261n/a invocations = [get_invocation(action)]
262n/a for subaction in self._iter_indented_subactions(action):
263n/a invocations.append(get_invocation(subaction))
264n/a
265n/a # update the maximum item length
266n/a invocation_length = max([len(s) for s in invocations])
267n/a action_length = invocation_length + self._current_indent
268n/a self._action_max_length = max(self._action_max_length,
269n/a action_length)
270n/a
271n/a # add the item to the list
272n/a self._add_item(self._format_action, [action])
273n/a
274n/a def add_arguments(self, actions):
275n/a for action in actions:
276n/a self.add_argument(action)
277n/a
278n/a # =======================
279n/a # Help-formatting methods
280n/a # =======================
281n/a def format_help(self):
282n/a help = self._root_section.format_help()
283n/a if help:
284n/a help = self._long_break_matcher.sub('\n\n', help)
285n/a help = help.strip('\n') + '\n'
286n/a return help
287n/a
288n/a def _join_parts(self, part_strings):
289n/a return ''.join([part
290n/a for part in part_strings
291n/a if part and part is not SUPPRESS])
292n/a
293n/a def _format_usage(self, usage, actions, groups, prefix):
294n/a if prefix is None:
295n/a prefix = _('usage: ')
296n/a
297n/a # if usage is specified, use that
298n/a if usage is not None:
299n/a usage = usage % dict(prog=self._prog)
300n/a
301n/a # if no optionals or positionals are available, usage is just prog
302n/a elif usage is None and not actions:
303n/a usage = '%(prog)s' % dict(prog=self._prog)
304n/a
305n/a # if optionals and positionals are available, calculate usage
306n/a elif usage is None:
307n/a prog = '%(prog)s' % dict(prog=self._prog)
308n/a
309n/a # split optionals from positionals
310n/a optionals = []
311n/a positionals = []
312n/a for action in actions:
313n/a if action.option_strings:
314n/a optionals.append(action)
315n/a else:
316n/a positionals.append(action)
317n/a
318n/a # build full usage string
319n/a format = self._format_actions_usage
320n/a action_usage = format(optionals + positionals, groups)
321n/a usage = ' '.join([s for s in [prog, action_usage] if s])
322n/a
323n/a # wrap the usage parts if it's too long
324n/a text_width = self._width - self._current_indent
325n/a if len(prefix) + len(usage) > text_width:
326n/a
327n/a # break usage into wrappable parts
328n/a part_regexp = r'\(.*?\)+|\[.*?\]+|\S+'
329n/a opt_usage = format(optionals, groups)
330n/a pos_usage = format(positionals, groups)
331n/a opt_parts = _re.findall(part_regexp, opt_usage)
332n/a pos_parts = _re.findall(part_regexp, pos_usage)
333n/a assert ' '.join(opt_parts) == opt_usage
334n/a assert ' '.join(pos_parts) == pos_usage
335n/a
336n/a # helper for wrapping lines
337n/a def get_lines(parts, indent, prefix=None):
338n/a lines = []
339n/a line = []
340n/a if prefix is not None:
341n/a line_len = len(prefix) - 1
342n/a else:
343n/a line_len = len(indent) - 1
344n/a for part in parts:
345n/a if line_len + 1 + len(part) > text_width and line:
346n/a lines.append(indent + ' '.join(line))
347n/a line = []
348n/a line_len = len(indent) - 1
349n/a line.append(part)
350n/a line_len += len(part) + 1
351n/a if line:
352n/a lines.append(indent + ' '.join(line))
353n/a if prefix is not None:
354n/a lines[0] = lines[0][len(indent):]
355n/a return lines
356n/a
357n/a # if prog is short, follow it with optionals or positionals
358n/a if len(prefix) + len(prog) <= 0.75 * text_width:
359n/a indent = ' ' * (len(prefix) + len(prog) + 1)
360n/a if opt_parts:
361n/a lines = get_lines([prog] + opt_parts, indent, prefix)
362n/a lines.extend(get_lines(pos_parts, indent))
363n/a elif pos_parts:
364n/a lines = get_lines([prog] + pos_parts, indent, prefix)
365n/a else:
366n/a lines = [prog]
367n/a
368n/a # if prog is long, put it on its own line
369n/a else:
370n/a indent = ' ' * len(prefix)
371n/a parts = opt_parts + pos_parts
372n/a lines = get_lines(parts, indent)
373n/a if len(lines) > 1:
374n/a lines = []
375n/a lines.extend(get_lines(opt_parts, indent))
376n/a lines.extend(get_lines(pos_parts, indent))
377n/a lines = [prog] + lines
378n/a
379n/a # join lines into usage
380n/a usage = '\n'.join(lines)
381n/a
382n/a # prefix with 'usage:'
383n/a return '%s%s\n\n' % (prefix, usage)
384n/a
385n/a def _format_actions_usage(self, actions, groups):
386n/a # find group indices and identify actions in groups
387n/a group_actions = set()
388n/a inserts = {}
389n/a for group in groups:
390n/a try:
391n/a start = actions.index(group._group_actions[0])
392n/a except ValueError:
393n/a continue
394n/a else:
395n/a end = start + len(group._group_actions)
396n/a if actions[start:end] == group._group_actions:
397n/a for action in group._group_actions:
398n/a group_actions.add(action)
399n/a if not group.required:
400n/a if start in inserts:
401n/a inserts[start] += ' ['
402n/a else:
403n/a inserts[start] = '['
404n/a inserts[end] = ']'
405n/a else:
406n/a if start in inserts:
407n/a inserts[start] += ' ('
408n/a else:
409n/a inserts[start] = '('
410n/a inserts[end] = ')'
411n/a for i in range(start + 1, end):
412n/a inserts[i] = '|'
413n/a
414n/a # collect all actions format strings
415n/a parts = []
416n/a for i, action in enumerate(actions):
417n/a
418n/a # suppressed arguments are marked with None
419n/a # remove | separators for suppressed arguments
420n/a if action.help is SUPPRESS:
421n/a parts.append(None)
422n/a if inserts.get(i) == '|':
423n/a inserts.pop(i)
424n/a elif inserts.get(i + 1) == '|':
425n/a inserts.pop(i + 1)
426n/a
427n/a # produce all arg strings
428n/a elif not action.option_strings:
429n/a default = self._get_default_metavar_for_positional(action)
430n/a part = self._format_args(action, default)
431n/a
432n/a # if it's in a group, strip the outer []
433n/a if action in group_actions:
434n/a if part[0] == '[' and part[-1] == ']':
435n/a part = part[1:-1]
436n/a
437n/a # add the action string to the list
438n/a parts.append(part)
439n/a
440n/a # produce the first way to invoke the option in brackets
441n/a else:
442n/a option_string = action.option_strings[0]
443n/a
444n/a # if the Optional doesn't take a value, format is:
445n/a # -s or --long
446n/a if action.nargs == 0:
447n/a part = '%s' % option_string
448n/a
449n/a # if the Optional takes a value, format is:
450n/a # -s ARGS or --long ARGS
451n/a else:
452n/a default = self._get_default_metavar_for_optional(action)
453n/a args_string = self._format_args(action, default)
454n/a part = '%s %s' % (option_string, args_string)
455n/a
456n/a # make it look optional if it's not required or in a group
457n/a if not action.required and action not in group_actions:
458n/a part = '[%s]' % part
459n/a
460n/a # add the action string to the list
461n/a parts.append(part)
462n/a
463n/a # insert things at the necessary indices
464n/a for i in sorted(inserts, reverse=True):
465n/a parts[i:i] = [inserts[i]]
466n/a
467n/a # join all the action items with spaces
468n/a text = ' '.join([item for item in parts if item is not None])
469n/a
470n/a # clean up separators for mutually exclusive groups
471n/a open = r'[\[(]'
472n/a close = r'[\])]'
473n/a text = _re.sub(r'(%s) ' % open, r'\1', text)
474n/a text = _re.sub(r' (%s)' % close, r'\1', text)
475n/a text = _re.sub(r'%s *%s' % (open, close), r'', text)
476n/a text = _re.sub(r'\(([^|]*)\)', r'\1', text)
477n/a text = text.strip()
478n/a
479n/a # return the text
480n/a return text
481n/a
482n/a def _format_text(self, text):
483n/a if '%(prog)' in text:
484n/a text = text % dict(prog=self._prog)
485n/a text_width = max(self._width - self._current_indent, 11)
486n/a indent = ' ' * self._current_indent
487n/a return self._fill_text(text, text_width, indent) + '\n\n'
488n/a
489n/a def _format_action(self, action):
490n/a # determine the required width and the entry label
491n/a help_position = min(self._action_max_length + 2,
492n/a self._max_help_position)
493n/a help_width = max(self._width - help_position, 11)
494n/a action_width = help_position - self._current_indent - 2
495n/a action_header = self._format_action_invocation(action)
496n/a
497n/a # no help; start on same line and add a final newline
498n/a if not action.help:
499n/a tup = self._current_indent, '', action_header
500n/a action_header = '%*s%s\n' % tup
501n/a
502n/a # short action name; start on the same line and pad two spaces
503n/a elif len(action_header) <= action_width:
504n/a tup = self._current_indent, '', action_width, action_header
505n/a action_header = '%*s%-*s ' % tup
506n/a indent_first = 0
507n/a
508n/a # long action name; start on the next line
509n/a else:
510n/a tup = self._current_indent, '', action_header
511n/a action_header = '%*s%s\n' % tup
512n/a indent_first = help_position
513n/a
514n/a # collect the pieces of the action help
515n/a parts = [action_header]
516n/a
517n/a # if there was help for the action, add lines of help text
518n/a if action.help:
519n/a help_text = self._expand_help(action)
520n/a help_lines = self._split_lines(help_text, help_width)
521n/a parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
522n/a for line in help_lines[1:]:
523n/a parts.append('%*s%s\n' % (help_position, '', line))
524n/a
525n/a # or add a newline if the description doesn't end with one
526n/a elif not action_header.endswith('\n'):
527n/a parts.append('\n')
528n/a
529n/a # if there are any sub-actions, add their help as well
530n/a for subaction in self._iter_indented_subactions(action):
531n/a parts.append(self._format_action(subaction))
532n/a
533n/a # return a single string
534n/a return self._join_parts(parts)
535n/a
536n/a def _format_action_invocation(self, action):
537n/a if not action.option_strings:
538n/a default = self._get_default_metavar_for_positional(action)
539n/a metavar, = self._metavar_formatter(action, default)(1)
540n/a return metavar
541n/a
542n/a else:
543n/a parts = []
544n/a
545n/a # if the Optional doesn't take a value, format is:
546n/a # -s, --long
547n/a if action.nargs == 0:
548n/a parts.extend(action.option_strings)
549n/a
550n/a # if the Optional takes a value, format is:
551n/a # -s ARGS, --long ARGS
552n/a else:
553n/a default = self._get_default_metavar_for_optional(action)
554n/a args_string = self._format_args(action, default)
555n/a for option_string in action.option_strings:
556n/a parts.append('%s %s' % (option_string, args_string))
557n/a
558n/a return ', '.join(parts)
559n/a
560n/a def _metavar_formatter(self, action, default_metavar):
561n/a if action.metavar is not None:
562n/a result = action.metavar
563n/a elif action.choices is not None:
564n/a choice_strs = [str(choice) for choice in action.choices]
565n/a result = '{%s}' % ','.join(choice_strs)
566n/a else:
567n/a result = default_metavar
568n/a
569n/a def format(tuple_size):
570n/a if isinstance(result, tuple):
571n/a return result
572n/a else:
573n/a return (result, ) * tuple_size
574n/a return format
575n/a
576n/a def _format_args(self, action, default_metavar):
577n/a get_metavar = self._metavar_formatter(action, default_metavar)
578n/a if action.nargs is None:
579n/a result = '%s' % get_metavar(1)
580n/a elif action.nargs == OPTIONAL:
581n/a result = '[%s]' % get_metavar(1)
582n/a elif action.nargs == ZERO_OR_MORE:
583n/a result = '[%s [%s ...]]' % get_metavar(2)
584n/a elif action.nargs == ONE_OR_MORE:
585n/a result = '%s [%s ...]' % get_metavar(2)
586n/a elif action.nargs == REMAINDER:
587n/a result = '...'
588n/a elif action.nargs == PARSER:
589n/a result = '%s ...' % get_metavar(1)
590n/a else:
591n/a formats = ['%s' for _ in range(action.nargs)]
592n/a result = ' '.join(formats) % get_metavar(action.nargs)
593n/a return result
594n/a
595n/a def _expand_help(self, action):
596n/a params = dict(vars(action), prog=self._prog)
597n/a for name in list(params):
598n/a if params[name] is SUPPRESS:
599n/a del params[name]
600n/a for name in list(params):
601n/a if hasattr(params[name], '__name__'):
602n/a params[name] = params[name].__name__
603n/a if params.get('choices') is not None:
604n/a choices_str = ', '.join([str(c) for c in params['choices']])
605n/a params['choices'] = choices_str
606n/a return self._get_help_string(action) % params
607n/a
608n/a def _iter_indented_subactions(self, action):
609n/a try:
610n/a get_subactions = action._get_subactions
611n/a except AttributeError:
612n/a pass
613n/a else:
614n/a self._indent()
615n/a yield from get_subactions()
616n/a self._dedent()
617n/a
618n/a def _split_lines(self, text, width):
619n/a text = self._whitespace_matcher.sub(' ', text).strip()
620n/a return _textwrap.wrap(text, width)
621n/a
622n/a def _fill_text(self, text, width, indent):
623n/a text = self._whitespace_matcher.sub(' ', text).strip()
624n/a return _textwrap.fill(text, width, initial_indent=indent,
625n/a subsequent_indent=indent)
626n/a
627n/a def _get_help_string(self, action):
628n/a return action.help
629n/a
630n/a def _get_default_metavar_for_optional(self, action):
631n/a return action.dest.upper()
632n/a
633n/a def _get_default_metavar_for_positional(self, action):
634n/a return action.dest
635n/a
636n/a
637n/aclass RawDescriptionHelpFormatter(HelpFormatter):
638n/a """Help message formatter which retains any formatting in descriptions.
639n/a
640n/a Only the name of this class is considered a public API. All the methods
641n/a provided by the class are considered an implementation detail.
642n/a """
643n/a
644n/a def _fill_text(self, text, width, indent):
645n/a return ''.join(indent + line for line in text.splitlines(keepends=True))
646n/a
647n/a
648n/aclass RawTextHelpFormatter(RawDescriptionHelpFormatter):
649n/a """Help message formatter which retains formatting of all help text.
650n/a
651n/a Only the name of this class is considered a public API. All the methods
652n/a provided by the class are considered an implementation detail.
653n/a """
654n/a
655n/a def _split_lines(self, text, width):
656n/a return text.splitlines()
657n/a
658n/a
659n/aclass ArgumentDefaultsHelpFormatter(HelpFormatter):
660n/a """Help message formatter which adds default values to argument help.
661n/a
662n/a Only the name of this class is considered a public API. All the methods
663n/a provided by the class are considered an implementation detail.
664n/a """
665n/a
666n/a def _get_help_string(self, action):
667n/a help = action.help
668n/a if '%(default)' not in action.help:
669n/a if action.default is not SUPPRESS:
670n/a defaulting_nargs = [OPTIONAL, ZERO_OR_MORE]
671n/a if action.option_strings or action.nargs in defaulting_nargs:
672n/a help += ' (default: %(default)s)'
673n/a return help
674n/a
675n/a
676n/aclass MetavarTypeHelpFormatter(HelpFormatter):
677n/a """Help message formatter which uses the argument 'type' as the default
678n/a metavar value (instead of the argument 'dest')
679n/a
680n/a Only the name of this class is considered a public API. All the methods
681n/a provided by the class are considered an implementation detail.
682n/a """
683n/a
684n/a def _get_default_metavar_for_optional(self, action):
685n/a return action.type.__name__
686n/a
687n/a def _get_default_metavar_for_positional(self, action):
688n/a return action.type.__name__
689n/a
690n/a
691n/a
692n/a# =====================
693n/a# Options and Arguments
694n/a# =====================
695n/a
696n/adef _get_action_name(argument):
697n/a if argument is None:
698n/a return None
699n/a elif argument.option_strings:
700n/a return '/'.join(argument.option_strings)
701n/a elif argument.metavar not in (None, SUPPRESS):
702n/a return argument.metavar
703n/a elif argument.dest not in (None, SUPPRESS):
704n/a return argument.dest
705n/a else:
706n/a return None
707n/a
708n/a
709n/aclass ArgumentError(Exception):
710n/a """An error from creating or using an argument (optional or positional).
711n/a
712n/a The string value of this exception is the message, augmented with
713n/a information about the argument that caused it.
714n/a """
715n/a
716n/a def __init__(self, argument, message):
717n/a self.argument_name = _get_action_name(argument)
718n/a self.message = message
719n/a
720n/a def __str__(self):
721n/a if self.argument_name is None:
722n/a format = '%(message)s'
723n/a else:
724n/a format = 'argument %(argument_name)s: %(message)s'
725n/a return format % dict(message=self.message,
726n/a argument_name=self.argument_name)
727n/a
728n/a
729n/aclass ArgumentTypeError(Exception):
730n/a """An error from trying to convert a command line string to a type."""
731n/a pass
732n/a
733n/a
734n/a# ==============
735n/a# Action classes
736n/a# ==============
737n/a
738n/aclass Action(_AttributeHolder):
739n/a """Information about how to convert command line strings to Python objects.
740n/a
741n/a Action objects are used by an ArgumentParser to represent the information
742n/a needed to parse a single argument from one or more strings from the
743n/a command line. The keyword arguments to the Action constructor are also
744n/a all attributes of Action instances.
745n/a
746n/a Keyword Arguments:
747n/a
748n/a - option_strings -- A list of command-line option strings which
749n/a should be associated with this action.
750n/a
751n/a - dest -- The name of the attribute to hold the created object(s)
752n/a
753n/a - nargs -- The number of command-line arguments that should be
754n/a consumed. By default, one argument will be consumed and a single
755n/a value will be produced. Other values include:
756n/a - N (an integer) consumes N arguments (and produces a list)
757n/a - '?' consumes zero or one arguments
758n/a - '*' consumes zero or more arguments (and produces a list)
759n/a - '+' consumes one or more arguments (and produces a list)
760n/a Note that the difference between the default and nargs=1 is that
761n/a with the default, a single value will be produced, while with
762n/a nargs=1, a list containing a single value will be produced.
763n/a
764n/a - const -- The value to be produced if the option is specified and the
765n/a option uses an action that takes no values.
766n/a
767n/a - default -- The value to be produced if the option is not specified.
768n/a
769n/a - type -- A callable that accepts a single string argument, and
770n/a returns the converted value. The standard Python types str, int,
771n/a float, and complex are useful examples of such callables. If None,
772n/a str is used.
773n/a
774n/a - choices -- A container of values that should be allowed. If not None,
775n/a after a command-line argument has been converted to the appropriate
776n/a type, an exception will be raised if it is not a member of this
777n/a collection.
778n/a
779n/a - required -- True if the action must always be specified at the
780n/a command line. This is only meaningful for optional command-line
781n/a arguments.
782n/a
783n/a - help -- The help string describing the argument.
784n/a
785n/a - metavar -- The name to be used for the option's argument with the
786n/a help string. If None, the 'dest' value will be used as the name.
787n/a """
788n/a
789n/a def __init__(self,
790n/a option_strings,
791n/a dest,
792n/a nargs=None,
793n/a const=None,
794n/a default=None,
795n/a type=None,
796n/a choices=None,
797n/a required=False,
798n/a help=None,
799n/a metavar=None):
800n/a self.option_strings = option_strings
801n/a self.dest = dest
802n/a self.nargs = nargs
803n/a self.const = const
804n/a self.default = default
805n/a self.type = type
806n/a self.choices = choices
807n/a self.required = required
808n/a self.help = help
809n/a self.metavar = metavar
810n/a
811n/a def _get_kwargs(self):
812n/a names = [
813n/a 'option_strings',
814n/a 'dest',
815n/a 'nargs',
816n/a 'const',
817n/a 'default',
818n/a 'type',
819n/a 'choices',
820n/a 'help',
821n/a 'metavar',
822n/a ]
823n/a return [(name, getattr(self, name)) for name in names]
824n/a
825n/a def __call__(self, parser, namespace, values, option_string=None):
826n/a raise NotImplementedError(_('.__call__() not defined'))
827n/a
828n/a
829n/aclass _StoreAction(Action):
830n/a
831n/a def __init__(self,
832n/a option_strings,
833n/a dest,
834n/a nargs=None,
835n/a const=None,
836n/a default=None,
837n/a type=None,
838n/a choices=None,
839n/a required=False,
840n/a help=None,
841n/a metavar=None):
842n/a if nargs == 0:
843n/a raise ValueError('nargs for store actions must be > 0; if you '
844n/a 'have nothing to store, actions such as store '
845n/a 'true or store const may be more appropriate')
846n/a if const is not None and nargs != OPTIONAL:
847n/a raise ValueError('nargs must be %r to supply const' % OPTIONAL)
848n/a super(_StoreAction, self).__init__(
849n/a option_strings=option_strings,
850n/a dest=dest,
851n/a nargs=nargs,
852n/a const=const,
853n/a default=default,
854n/a type=type,
855n/a choices=choices,
856n/a required=required,
857n/a help=help,
858n/a metavar=metavar)
859n/a
860n/a def __call__(self, parser, namespace, values, option_string=None):
861n/a setattr(namespace, self.dest, values)
862n/a
863n/a
864n/aclass _StoreConstAction(Action):
865n/a
866n/a def __init__(self,
867n/a option_strings,
868n/a dest,
869n/a const,
870n/a default=None,
871n/a required=False,
872n/a help=None,
873n/a metavar=None):
874n/a super(_StoreConstAction, self).__init__(
875n/a option_strings=option_strings,
876n/a dest=dest,
877n/a nargs=0,
878n/a const=const,
879n/a default=default,
880n/a required=required,
881n/a help=help)
882n/a
883n/a def __call__(self, parser, namespace, values, option_string=None):
884n/a setattr(namespace, self.dest, self.const)
885n/a
886n/a
887n/aclass _StoreTrueAction(_StoreConstAction):
888n/a
889n/a def __init__(self,
890n/a option_strings,
891n/a dest,
892n/a default=False,
893n/a required=False,
894n/a help=None):
895n/a super(_StoreTrueAction, self).__init__(
896n/a option_strings=option_strings,
897n/a dest=dest,
898n/a const=True,
899n/a default=default,
900n/a required=required,
901n/a help=help)
902n/a
903n/a
904n/aclass _StoreFalseAction(_StoreConstAction):
905n/a
906n/a def __init__(self,
907n/a option_strings,
908n/a dest,
909n/a default=True,
910n/a required=False,
911n/a help=None):
912n/a super(_StoreFalseAction, self).__init__(
913n/a option_strings=option_strings,
914n/a dest=dest,
915n/a const=False,
916n/a default=default,
917n/a required=required,
918n/a help=help)
919n/a
920n/a
921n/aclass _AppendAction(Action):
922n/a
923n/a def __init__(self,
924n/a option_strings,
925n/a dest,
926n/a nargs=None,
927n/a const=None,
928n/a default=None,
929n/a type=None,
930n/a choices=None,
931n/a required=False,
932n/a help=None,
933n/a metavar=None):
934n/a if nargs == 0:
935n/a raise ValueError('nargs for append actions must be > 0; if arg '
936n/a 'strings are not supplying the value to append, '
937n/a 'the append const action may be more appropriate')
938n/a if const is not None and nargs != OPTIONAL:
939n/a raise ValueError('nargs must be %r to supply const' % OPTIONAL)
940n/a super(_AppendAction, self).__init__(
941n/a option_strings=option_strings,
942n/a dest=dest,
943n/a nargs=nargs,
944n/a const=const,
945n/a default=default,
946n/a type=type,
947n/a choices=choices,
948n/a required=required,
949n/a help=help,
950n/a metavar=metavar)
951n/a
952n/a def __call__(self, parser, namespace, values, option_string=None):
953n/a items = _copy.copy(_ensure_value(namespace, self.dest, []))
954n/a items.append(values)
955n/a setattr(namespace, self.dest, items)
956n/a
957n/a
958n/aclass _AppendConstAction(Action):
959n/a
960n/a def __init__(self,
961n/a option_strings,
962n/a dest,
963n/a const,
964n/a default=None,
965n/a required=False,
966n/a help=None,
967n/a metavar=None):
968n/a super(_AppendConstAction, self).__init__(
969n/a option_strings=option_strings,
970n/a dest=dest,
971n/a nargs=0,
972n/a const=const,
973n/a default=default,
974n/a required=required,
975n/a help=help,
976n/a metavar=metavar)
977n/a
978n/a def __call__(self, parser, namespace, values, option_string=None):
979n/a items = _copy.copy(_ensure_value(namespace, self.dest, []))
980n/a items.append(self.const)
981n/a setattr(namespace, self.dest, items)
982n/a
983n/a
984n/aclass _CountAction(Action):
985n/a
986n/a def __init__(self,
987n/a option_strings,
988n/a dest,
989n/a default=None,
990n/a required=False,
991n/a help=None):
992n/a super(_CountAction, self).__init__(
993n/a option_strings=option_strings,
994n/a dest=dest,
995n/a nargs=0,
996n/a default=default,
997n/a required=required,
998n/a help=help)
999n/a
1000n/a def __call__(self, parser, namespace, values, option_string=None):
1001n/a new_count = _ensure_value(namespace, self.dest, 0) + 1
1002n/a setattr(namespace, self.dest, new_count)
1003n/a
1004n/a
1005n/aclass _HelpAction(Action):
1006n/a
1007n/a def __init__(self,
1008n/a option_strings,
1009n/a dest=SUPPRESS,
1010n/a default=SUPPRESS,
1011n/a help=None):
1012n/a super(_HelpAction, self).__init__(
1013n/a option_strings=option_strings,
1014n/a dest=dest,
1015n/a default=default,
1016n/a nargs=0,
1017n/a help=help)
1018n/a
1019n/a def __call__(self, parser, namespace, values, option_string=None):
1020n/a parser.print_help()
1021n/a parser.exit()
1022n/a
1023n/a
1024n/aclass _VersionAction(Action):
1025n/a
1026n/a def __init__(self,
1027n/a option_strings,
1028n/a version=None,
1029n/a dest=SUPPRESS,
1030n/a default=SUPPRESS,
1031n/a help="show program's version number and exit"):
1032n/a super(_VersionAction, self).__init__(
1033n/a option_strings=option_strings,
1034n/a dest=dest,
1035n/a default=default,
1036n/a nargs=0,
1037n/a help=help)
1038n/a self.version = version
1039n/a
1040n/a def __call__(self, parser, namespace, values, option_string=None):
1041n/a version = self.version
1042n/a if version is None:
1043n/a version = parser.version
1044n/a formatter = parser._get_formatter()
1045n/a formatter.add_text(version)
1046n/a parser._print_message(formatter.format_help(), _sys.stdout)
1047n/a parser.exit()
1048n/a
1049n/a
1050n/aclass _SubParsersAction(Action):
1051n/a
1052n/a class _ChoicesPseudoAction(Action):
1053n/a
1054n/a def __init__(self, name, aliases, help):
1055n/a metavar = dest = name
1056n/a if aliases:
1057n/a metavar += ' (%s)' % ', '.join(aliases)
1058n/a sup = super(_SubParsersAction._ChoicesPseudoAction, self)
1059n/a sup.__init__(option_strings=[], dest=dest, help=help,
1060n/a metavar=metavar)
1061n/a
1062n/a def __init__(self,
1063n/a option_strings,
1064n/a prog,
1065n/a parser_class,
1066n/a dest=SUPPRESS,
1067n/a help=None,
1068n/a metavar=None):
1069n/a
1070n/a self._prog_prefix = prog
1071n/a self._parser_class = parser_class
1072n/a self._name_parser_map = _collections.OrderedDict()
1073n/a self._choices_actions = []
1074n/a
1075n/a super(_SubParsersAction, self).__init__(
1076n/a option_strings=option_strings,
1077n/a dest=dest,
1078n/a nargs=PARSER,
1079n/a choices=self._name_parser_map,
1080n/a help=help,
1081n/a metavar=metavar)
1082n/a
1083n/a def add_parser(self, name, **kwargs):
1084n/a # set prog from the existing prefix
1085n/a if kwargs.get('prog') is None:
1086n/a kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
1087n/a
1088n/a aliases = kwargs.pop('aliases', ())
1089n/a
1090n/a # create a pseudo-action to hold the choice help
1091n/a if 'help' in kwargs:
1092n/a help = kwargs.pop('help')
1093n/a choice_action = self._ChoicesPseudoAction(name, aliases, help)
1094n/a self._choices_actions.append(choice_action)
1095n/a
1096n/a # create the parser and add it to the map
1097n/a parser = self._parser_class(**kwargs)
1098n/a self._name_parser_map[name] = parser
1099n/a
1100n/a # make parser available under aliases also
1101n/a for alias in aliases:
1102n/a self._name_parser_map[alias] = parser
1103n/a
1104n/a return parser
1105n/a
1106n/a def _get_subactions(self):
1107n/a return self._choices_actions
1108n/a
1109n/a def __call__(self, parser, namespace, values, option_string=None):
1110n/a parser_name = values[0]
1111n/a arg_strings = values[1:]
1112n/a
1113n/a # set the parser name if requested
1114n/a if self.dest is not SUPPRESS:
1115n/a setattr(namespace, self.dest, parser_name)
1116n/a
1117n/a # select the parser
1118n/a try:
1119n/a parser = self._name_parser_map[parser_name]
1120n/a except KeyError:
1121n/a args = {'parser_name': parser_name,
1122n/a 'choices': ', '.join(self._name_parser_map)}
1123n/a msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
1124n/a raise ArgumentError(self, msg)
1125n/a
1126n/a # parse all the remaining options into the namespace
1127n/a # store any unrecognized options on the object, so that the top
1128n/a # level parser can decide what to do with them
1129n/a
1130n/a # In case this subparser defines new defaults, we parse them
1131n/a # in a new namespace object and then update the original
1132n/a # namespace for the relevant parts.
1133n/a subnamespace, arg_strings = parser.parse_known_args(arg_strings, None)
1134n/a for key, value in vars(subnamespace).items():
1135n/a setattr(namespace, key, value)
1136n/a
1137n/a if arg_strings:
1138n/a vars(namespace).setdefault(_UNRECOGNIZED_ARGS_ATTR, [])
1139n/a getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).extend(arg_strings)
1140n/a
1141n/a
1142n/a# ==============
1143n/a# Type classes
1144n/a# ==============
1145n/a
1146n/aclass FileType(object):
1147n/a """Factory for creating file object types
1148n/a
1149n/a Instances of FileType are typically passed as type= arguments to the
1150n/a ArgumentParser add_argument() method.
1151n/a
1152n/a Keyword Arguments:
1153n/a - mode -- A string indicating how the file is to be opened. Accepts the
1154n/a same values as the builtin open() function.
1155n/a - bufsize -- The file's desired buffer size. Accepts the same values as
1156n/a the builtin open() function.
1157n/a - encoding -- The file's encoding. Accepts the same values as the
1158n/a builtin open() function.
1159n/a - errors -- A string indicating how encoding and decoding errors are to
1160n/a be handled. Accepts the same value as the builtin open() function.
1161n/a """
1162n/a
1163n/a def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None):
1164n/a self._mode = mode
1165n/a self._bufsize = bufsize
1166n/a self._encoding = encoding
1167n/a self._errors = errors
1168n/a
1169n/a def __call__(self, string):
1170n/a # the special argument "-" means sys.std{in,out}
1171n/a if string == '-':
1172n/a if 'r' in self._mode:
1173n/a return _sys.stdin
1174n/a elif 'w' in self._mode:
1175n/a return _sys.stdout
1176n/a else:
1177n/a msg = _('argument "-" with mode %r') % self._mode
1178n/a raise ValueError(msg)
1179n/a
1180n/a # all other arguments are used as file names
1181n/a try:
1182n/a return open(string, self._mode, self._bufsize, self._encoding,
1183n/a self._errors)
1184n/a except OSError as e:
1185n/a message = _("can't open '%s': %s")
1186n/a raise ArgumentTypeError(message % (string, e))
1187n/a
1188n/a def __repr__(self):
1189n/a args = self._mode, self._bufsize
1190n/a kwargs = [('encoding', self._encoding), ('errors', self._errors)]
1191n/a args_str = ', '.join([repr(arg) for arg in args if arg != -1] +
1192n/a ['%s=%r' % (kw, arg) for kw, arg in kwargs
1193n/a if arg is not None])
1194n/a return '%s(%s)' % (type(self).__name__, args_str)
1195n/a
1196n/a# ===========================
1197n/a# Optional and Positional Parsing
1198n/a# ===========================
1199n/a
1200n/aclass Namespace(_AttributeHolder):
1201n/a """Simple object for storing attributes.
1202n/a
1203n/a Implements equality by attribute names and values, and provides a simple
1204n/a string representation.
1205n/a """
1206n/a
1207n/a def __init__(self, **kwargs):
1208n/a for name in kwargs:
1209n/a setattr(self, name, kwargs[name])
1210n/a
1211n/a def __eq__(self, other):
1212n/a if not isinstance(other, Namespace):
1213n/a return NotImplemented
1214n/a return vars(self) == vars(other)
1215n/a
1216n/a def __contains__(self, key):
1217n/a return key in self.__dict__
1218n/a
1219n/a
1220n/aclass _ActionsContainer(object):
1221n/a
1222n/a def __init__(self,
1223n/a description,
1224n/a prefix_chars,
1225n/a argument_default,
1226n/a conflict_handler):
1227n/a super(_ActionsContainer, self).__init__()
1228n/a
1229n/a self.description = description
1230n/a self.argument_default = argument_default
1231n/a self.prefix_chars = prefix_chars
1232n/a self.conflict_handler = conflict_handler
1233n/a
1234n/a # set up registries
1235n/a self._registries = {}
1236n/a
1237n/a # register actions
1238n/a self.register('action', None, _StoreAction)
1239n/a self.register('action', 'store', _StoreAction)
1240n/a self.register('action', 'store_const', _StoreConstAction)
1241n/a self.register('action', 'store_true', _StoreTrueAction)
1242n/a self.register('action', 'store_false', _StoreFalseAction)
1243n/a self.register('action', 'append', _AppendAction)
1244n/a self.register('action', 'append_const', _AppendConstAction)
1245n/a self.register('action', 'count', _CountAction)
1246n/a self.register('action', 'help', _HelpAction)
1247n/a self.register('action', 'version', _VersionAction)
1248n/a self.register('action', 'parsers', _SubParsersAction)
1249n/a
1250n/a # raise an exception if the conflict handler is invalid
1251n/a self._get_handler()
1252n/a
1253n/a # action storage
1254n/a self._actions = []
1255n/a self._option_string_actions = {}
1256n/a
1257n/a # groups
1258n/a self._action_groups = []
1259n/a self._mutually_exclusive_groups = []
1260n/a
1261n/a # defaults storage
1262n/a self._defaults = {}
1263n/a
1264n/a # determines whether an "option" looks like a negative number
1265n/a self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')
1266n/a
1267n/a # whether or not there are any optionals that look like negative
1268n/a # numbers -- uses a list so it can be shared and edited
1269n/a self._has_negative_number_optionals = []
1270n/a
1271n/a # ====================
1272n/a # Registration methods
1273n/a # ====================
1274n/a def register(self, registry_name, value, object):
1275n/a registry = self._registries.setdefault(registry_name, {})
1276n/a registry[value] = object
1277n/a
1278n/a def _registry_get(self, registry_name, value, default=None):
1279n/a return self._registries[registry_name].get(value, default)
1280n/a
1281n/a # ==================================
1282n/a # Namespace default accessor methods
1283n/a # ==================================
1284n/a def set_defaults(self, **kwargs):
1285n/a self._defaults.update(kwargs)
1286n/a
1287n/a # if these defaults match any existing arguments, replace
1288n/a # the previous default on the object with the new one
1289n/a for action in self._actions:
1290n/a if action.dest in kwargs:
1291n/a action.default = kwargs[action.dest]
1292n/a
1293n/a def get_default(self, dest):
1294n/a for action in self._actions:
1295n/a if action.dest == dest and action.default is not None:
1296n/a return action.default
1297n/a return self._defaults.get(dest, None)
1298n/a
1299n/a
1300n/a # =======================
1301n/a # Adding argument actions
1302n/a # =======================
1303n/a def add_argument(self, *args, **kwargs):
1304n/a """
1305n/a add_argument(dest, ..., name=value, ...)
1306n/a add_argument(option_string, option_string, ..., name=value, ...)
1307n/a """
1308n/a
1309n/a # if no positional args are supplied or only one is supplied and
1310n/a # it doesn't look like an option string, parse a positional
1311n/a # argument
1312n/a chars = self.prefix_chars
1313n/a if not args or len(args) == 1 and args[0][0] not in chars:
1314n/a if args and 'dest' in kwargs:
1315n/a raise ValueError('dest supplied twice for positional argument')
1316n/a kwargs = self._get_positional_kwargs(*args, **kwargs)
1317n/a
1318n/a # otherwise, we're adding an optional argument
1319n/a else:
1320n/a kwargs = self._get_optional_kwargs(*args, **kwargs)
1321n/a
1322n/a # if no default was supplied, use the parser-level default
1323n/a if 'default' not in kwargs:
1324n/a dest = kwargs['dest']
1325n/a if dest in self._defaults:
1326n/a kwargs['default'] = self._defaults[dest]
1327n/a elif self.argument_default is not None:
1328n/a kwargs['default'] = self.argument_default
1329n/a
1330n/a # create the action object, and add it to the parser
1331n/a action_class = self._pop_action_class(kwargs)
1332n/a if not callable(action_class):
1333n/a raise ValueError('unknown action "%s"' % (action_class,))
1334n/a action = action_class(**kwargs)
1335n/a
1336n/a # raise an error if the action type is not callable
1337n/a type_func = self._registry_get('type', action.type, action.type)
1338n/a if not callable(type_func):
1339n/a raise ValueError('%r is not callable' % (type_func,))
1340n/a
1341n/a # raise an error if the metavar does not match the type
1342n/a if hasattr(self, "_get_formatter"):
1343n/a try:
1344n/a self._get_formatter()._format_args(action, None)
1345n/a except TypeError:
1346n/a raise ValueError("length of metavar tuple does not match nargs")
1347n/a
1348n/a return self._add_action(action)
1349n/a
1350n/a def add_argument_group(self, *args, **kwargs):
1351n/a group = _ArgumentGroup(self, *args, **kwargs)
1352n/a self._action_groups.append(group)
1353n/a return group
1354n/a
1355n/a def add_mutually_exclusive_group(self, **kwargs):
1356n/a group = _MutuallyExclusiveGroup(self, **kwargs)
1357n/a self._mutually_exclusive_groups.append(group)
1358n/a return group
1359n/a
1360n/a def _add_action(self, action):
1361n/a # resolve any conflicts
1362n/a self._check_conflict(action)
1363n/a
1364n/a # add to actions list
1365n/a self._actions.append(action)
1366n/a action.container = self
1367n/a
1368n/a # index the action by any option strings it has
1369n/a for option_string in action.option_strings:
1370n/a self._option_string_actions[option_string] = action
1371n/a
1372n/a # set the flag if any option strings look like negative numbers
1373n/a for option_string in action.option_strings:
1374n/a if self._negative_number_matcher.match(option_string):
1375n/a if not self._has_negative_number_optionals:
1376n/a self._has_negative_number_optionals.append(True)
1377n/a
1378n/a # return the created action
1379n/a return action
1380n/a
1381n/a def _remove_action(self, action):
1382n/a self._actions.remove(action)
1383n/a
1384n/a def _add_container_actions(self, container):
1385n/a # collect groups by titles
1386n/a title_group_map = {}
1387n/a for group in self._action_groups:
1388n/a if group.title in title_group_map:
1389n/a msg = _('cannot merge actions - two groups are named %r')
1390n/a raise ValueError(msg % (group.title))
1391n/a title_group_map[group.title] = group
1392n/a
1393n/a # map each action to its group
1394n/a group_map = {}
1395n/a for group in container._action_groups:
1396n/a
1397n/a # if a group with the title exists, use that, otherwise
1398n/a # create a new group matching the container's group
1399n/a if group.title not in title_group_map:
1400n/a title_group_map[group.title] = self.add_argument_group(
1401n/a title=group.title,
1402n/a description=group.description,
1403n/a conflict_handler=group.conflict_handler)
1404n/a
1405n/a # map the actions to their new group
1406n/a for action in group._group_actions:
1407n/a group_map[action] = title_group_map[group.title]
1408n/a
1409n/a # add container's mutually exclusive groups
1410n/a # NOTE: if add_mutually_exclusive_group ever gains title= and
1411n/a # description= then this code will need to be expanded as above
1412n/a for group in container._mutually_exclusive_groups:
1413n/a mutex_group = self.add_mutually_exclusive_group(
1414n/a required=group.required)
1415n/a
1416n/a # map the actions to their new mutex group
1417n/a for action in group._group_actions:
1418n/a group_map[action] = mutex_group
1419n/a
1420n/a # add all actions to this container or their group
1421n/a for action in container._actions:
1422n/a group_map.get(action, self)._add_action(action)
1423n/a
1424n/a def _get_positional_kwargs(self, dest, **kwargs):
1425n/a # make sure required is not specified
1426n/a if 'required' in kwargs:
1427n/a msg = _("'required' is an invalid argument for positionals")
1428n/a raise TypeError(msg)
1429n/a
1430n/a # mark positional arguments as required if at least one is
1431n/a # always required
1432n/a if kwargs.get('nargs') not in [OPTIONAL, ZERO_OR_MORE]:
1433n/a kwargs['required'] = True
1434n/a if kwargs.get('nargs') == ZERO_OR_MORE and 'default' not in kwargs:
1435n/a kwargs['required'] = True
1436n/a
1437n/a # return the keyword arguments with no option strings
1438n/a return dict(kwargs, dest=dest, option_strings=[])
1439n/a
1440n/a def _get_optional_kwargs(self, *args, **kwargs):
1441n/a # determine short and long option strings
1442n/a option_strings = []
1443n/a long_option_strings = []
1444n/a for option_string in args:
1445n/a # error on strings that don't start with an appropriate prefix
1446n/a if not option_string[0] in self.prefix_chars:
1447n/a args = {'option': option_string,
1448n/a 'prefix_chars': self.prefix_chars}
1449n/a msg = _('invalid option string %(option)r: '
1450n/a 'must start with a character %(prefix_chars)r')
1451n/a raise ValueError(msg % args)
1452n/a
1453n/a # strings starting with two prefix characters are long options
1454n/a option_strings.append(option_string)
1455n/a if option_string[0] in self.prefix_chars:
1456n/a if len(option_string) > 1:
1457n/a if option_string[1] in self.prefix_chars:
1458n/a long_option_strings.append(option_string)
1459n/a
1460n/a # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x'
1461n/a dest = kwargs.pop('dest', None)
1462n/a if dest is None:
1463n/a if long_option_strings:
1464n/a dest_option_string = long_option_strings[0]
1465n/a else:
1466n/a dest_option_string = option_strings[0]
1467n/a dest = dest_option_string.lstrip(self.prefix_chars)
1468n/a if not dest:
1469n/a msg = _('dest= is required for options like %r')
1470n/a raise ValueError(msg % option_string)
1471n/a dest = dest.replace('-', '_')
1472n/a
1473n/a # return the updated keyword arguments
1474n/a return dict(kwargs, dest=dest, option_strings=option_strings)
1475n/a
1476n/a def _pop_action_class(self, kwargs, default=None):
1477n/a action = kwargs.pop('action', default)
1478n/a return self._registry_get('action', action, action)
1479n/a
1480n/a def _get_handler(self):
1481n/a # determine function from conflict handler string
1482n/a handler_func_name = '_handle_conflict_%s' % self.conflict_handler
1483n/a try:
1484n/a return getattr(self, handler_func_name)
1485n/a except AttributeError:
1486n/a msg = _('invalid conflict_resolution value: %r')
1487n/a raise ValueError(msg % self.conflict_handler)
1488n/a
1489n/a def _check_conflict(self, action):
1490n/a
1491n/a # find all options that conflict with this option
1492n/a confl_optionals = []
1493n/a for option_string in action.option_strings:
1494n/a if option_string in self._option_string_actions:
1495n/a confl_optional = self._option_string_actions[option_string]
1496n/a confl_optionals.append((option_string, confl_optional))
1497n/a
1498n/a # resolve any conflicts
1499n/a if confl_optionals:
1500n/a conflict_handler = self._get_handler()
1501n/a conflict_handler(action, confl_optionals)
1502n/a
1503n/a def _handle_conflict_error(self, action, conflicting_actions):
1504n/a message = ngettext('conflicting option string: %s',
1505n/a 'conflicting option strings: %s',
1506n/a len(conflicting_actions))
1507n/a conflict_string = ', '.join([option_string
1508n/a for option_string, action
1509n/a in conflicting_actions])
1510n/a raise ArgumentError(action, message % conflict_string)
1511n/a
1512n/a def _handle_conflict_resolve(self, action, conflicting_actions):
1513n/a
1514n/a # remove all conflicting options
1515n/a for option_string, action in conflicting_actions:
1516n/a
1517n/a # remove the conflicting option
1518n/a action.option_strings.remove(option_string)
1519n/a self._option_string_actions.pop(option_string, None)
1520n/a
1521n/a # if the option now has no option string, remove it from the
1522n/a # container holding it
1523n/a if not action.option_strings:
1524n/a action.container._remove_action(action)
1525n/a
1526n/a
1527n/aclass _ArgumentGroup(_ActionsContainer):
1528n/a
1529n/a def __init__(self, container, title=None, description=None, **kwargs):
1530n/a # add any missing keyword arguments by checking the container
1531n/a update = kwargs.setdefault
1532n/a update('conflict_handler', container.conflict_handler)
1533n/a update('prefix_chars', container.prefix_chars)
1534n/a update('argument_default', container.argument_default)
1535n/a super_init = super(_ArgumentGroup, self).__init__
1536n/a super_init(description=description, **kwargs)
1537n/a
1538n/a # group attributes
1539n/a self.title = title
1540n/a self._group_actions = []
1541n/a
1542n/a # share most attributes with the container
1543n/a self._registries = container._registries
1544n/a self._actions = container._actions
1545n/a self._option_string_actions = container._option_string_actions
1546n/a self._defaults = container._defaults
1547n/a self._has_negative_number_optionals = \
1548n/a container._has_negative_number_optionals
1549n/a self._mutually_exclusive_groups = container._mutually_exclusive_groups
1550n/a
1551n/a def _add_action(self, action):
1552n/a action = super(_ArgumentGroup, self)._add_action(action)
1553n/a self._group_actions.append(action)
1554n/a return action
1555n/a
1556n/a def _remove_action(self, action):
1557n/a super(_ArgumentGroup, self)._remove_action(action)
1558n/a self._group_actions.remove(action)
1559n/a
1560n/a
1561n/aclass _MutuallyExclusiveGroup(_ArgumentGroup):
1562n/a
1563n/a def __init__(self, container, required=False):
1564n/a super(_MutuallyExclusiveGroup, self).__init__(container)
1565n/a self.required = required
1566n/a self._container = container
1567n/a
1568n/a def _add_action(self, action):
1569n/a if action.required:
1570n/a msg = _('mutually exclusive arguments must be optional')
1571n/a raise ValueError(msg)
1572n/a action = self._container._add_action(action)
1573n/a self._group_actions.append(action)
1574n/a return action
1575n/a
1576n/a def _remove_action(self, action):
1577n/a self._container._remove_action(action)
1578n/a self._group_actions.remove(action)
1579n/a
1580n/a
1581n/aclass ArgumentParser(_AttributeHolder, _ActionsContainer):
1582n/a """Object for parsing command line strings into Python objects.
1583n/a
1584n/a Keyword Arguments:
1585n/a - prog -- The name of the program (default: sys.argv[0])
1586n/a - usage -- A usage message (default: auto-generated from arguments)
1587n/a - description -- A description of what the program does
1588n/a - epilog -- Text following the argument descriptions
1589n/a - parents -- Parsers whose arguments should be copied into this one
1590n/a - formatter_class -- HelpFormatter class for printing help messages
1591n/a - prefix_chars -- Characters that prefix optional arguments
1592n/a - fromfile_prefix_chars -- Characters that prefix files containing
1593n/a additional arguments
1594n/a - argument_default -- The default value for all arguments
1595n/a - conflict_handler -- String indicating how to handle conflicts
1596n/a - add_help -- Add a -h/-help option
1597n/a - allow_abbrev -- Allow long options to be abbreviated unambiguously
1598n/a """
1599n/a
1600n/a def __init__(self,
1601n/a prog=None,
1602n/a usage=None,
1603n/a description=None,
1604n/a epilog=None,
1605n/a parents=[],
1606n/a formatter_class=HelpFormatter,
1607n/a prefix_chars='-',
1608n/a fromfile_prefix_chars=None,
1609n/a argument_default=None,
1610n/a conflict_handler='error',
1611n/a add_help=True,
1612n/a allow_abbrev=True):
1613n/a
1614n/a superinit = super(ArgumentParser, self).__init__
1615n/a superinit(description=description,
1616n/a prefix_chars=prefix_chars,
1617n/a argument_default=argument_default,
1618n/a conflict_handler=conflict_handler)
1619n/a
1620n/a # default setting for prog
1621n/a if prog is None:
1622n/a prog = _os.path.basename(_sys.argv[0])
1623n/a
1624n/a self.prog = prog
1625n/a self.usage = usage
1626n/a self.epilog = epilog
1627n/a self.formatter_class = formatter_class
1628n/a self.fromfile_prefix_chars = fromfile_prefix_chars
1629n/a self.add_help = add_help
1630n/a self.allow_abbrev = allow_abbrev
1631n/a
1632n/a add_group = self.add_argument_group
1633n/a self._positionals = add_group(_('positional arguments'))
1634n/a self._optionals = add_group(_('optional arguments'))
1635n/a self._subparsers = None
1636n/a
1637n/a # register types
1638n/a def identity(string):
1639n/a return string
1640n/a self.register('type', None, identity)
1641n/a
1642n/a # add help argument if necessary
1643n/a # (using explicit default to override global argument_default)
1644n/a default_prefix = '-' if '-' in prefix_chars else prefix_chars[0]
1645n/a if self.add_help:
1646n/a self.add_argument(
1647n/a default_prefix+'h', default_prefix*2+'help',
1648n/a action='help', default=SUPPRESS,
1649n/a help=_('show this help message and exit'))
1650n/a
1651n/a # add parent arguments and defaults
1652n/a for parent in parents:
1653n/a self._add_container_actions(parent)
1654n/a try:
1655n/a defaults = parent._defaults
1656n/a except AttributeError:
1657n/a pass
1658n/a else:
1659n/a self._defaults.update(defaults)
1660n/a
1661n/a # =======================
1662n/a # Pretty __repr__ methods
1663n/a # =======================
1664n/a def _get_kwargs(self):
1665n/a names = [
1666n/a 'prog',
1667n/a 'usage',
1668n/a 'description',
1669n/a 'formatter_class',
1670n/a 'conflict_handler',
1671n/a 'add_help',
1672n/a ]
1673n/a return [(name, getattr(self, name)) for name in names]
1674n/a
1675n/a # ==================================
1676n/a # Optional/Positional adding methods
1677n/a # ==================================
1678n/a def add_subparsers(self, **kwargs):
1679n/a if self._subparsers is not None:
1680n/a self.error(_('cannot have multiple subparser arguments'))
1681n/a
1682n/a # add the parser class to the arguments if it's not present
1683n/a kwargs.setdefault('parser_class', type(self))
1684n/a
1685n/a if 'title' in kwargs or 'description' in kwargs:
1686n/a title = _(kwargs.pop('title', 'subcommands'))
1687n/a description = _(kwargs.pop('description', None))
1688n/a self._subparsers = self.add_argument_group(title, description)
1689n/a else:
1690n/a self._subparsers = self._positionals
1691n/a
1692n/a # prog defaults to the usage message of this parser, skipping
1693n/a # optional arguments and with no "usage:" prefix
1694n/a if kwargs.get('prog') is None:
1695n/a formatter = self._get_formatter()
1696n/a positionals = self._get_positional_actions()
1697n/a groups = self._mutually_exclusive_groups
1698n/a formatter.add_usage(self.usage, positionals, groups, '')
1699n/a kwargs['prog'] = formatter.format_help().strip()
1700n/a
1701n/a # create the parsers action and add it to the positionals list
1702n/a parsers_class = self._pop_action_class(kwargs, 'parsers')
1703n/a action = parsers_class(option_strings=[], **kwargs)
1704n/a self._subparsers._add_action(action)
1705n/a
1706n/a # return the created parsers action
1707n/a return action
1708n/a
1709n/a def _add_action(self, action):
1710n/a if action.option_strings:
1711n/a self._optionals._add_action(action)
1712n/a else:
1713n/a self._positionals._add_action(action)
1714n/a return action
1715n/a
1716n/a def _get_optional_actions(self):
1717n/a return [action
1718n/a for action in self._actions
1719n/a if action.option_strings]
1720n/a
1721n/a def _get_positional_actions(self):
1722n/a return [action
1723n/a for action in self._actions
1724n/a if not action.option_strings]
1725n/a
1726n/a # =====================================
1727n/a # Command line argument parsing methods
1728n/a # =====================================
1729n/a def parse_args(self, args=None, namespace=None):
1730n/a args, argv = self.parse_known_args(args, namespace)
1731n/a if argv:
1732n/a msg = _('unrecognized arguments: %s')
1733n/a self.error(msg % ' '.join(argv))
1734n/a return args
1735n/a
1736n/a def parse_known_args(self, args=None, namespace=None):
1737n/a if args is None:
1738n/a # args default to the system args
1739n/a args = _sys.argv[1:]
1740n/a else:
1741n/a # make sure that args are mutable
1742n/a args = list(args)
1743n/a
1744n/a # default Namespace built from parser defaults
1745n/a if namespace is None:
1746n/a namespace = Namespace()
1747n/a
1748n/a # add any action defaults that aren't present
1749n/a for action in self._actions:
1750n/a if action.dest is not SUPPRESS:
1751n/a if not hasattr(namespace, action.dest):
1752n/a if action.default is not SUPPRESS:
1753n/a setattr(namespace, action.dest, action.default)
1754n/a
1755n/a # add any parser defaults that aren't present
1756n/a for dest in self._defaults:
1757n/a if not hasattr(namespace, dest):
1758n/a setattr(namespace, dest, self._defaults[dest])
1759n/a
1760n/a # parse the arguments and exit if there are any errors
1761n/a try:
1762n/a namespace, args = self._parse_known_args(args, namespace)
1763n/a if hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR):
1764n/a args.extend(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR))
1765n/a delattr(namespace, _UNRECOGNIZED_ARGS_ATTR)
1766n/a return namespace, args
1767n/a except ArgumentError:
1768n/a err = _sys.exc_info()[1]
1769n/a self.error(str(err))
1770n/a
1771n/a def _parse_known_args(self, arg_strings, namespace):
1772n/a # replace arg strings that are file references
1773n/a if self.fromfile_prefix_chars is not None:
1774n/a arg_strings = self._read_args_from_files(arg_strings)
1775n/a
1776n/a # map all mutually exclusive arguments to the other arguments
1777n/a # they can't occur with
1778n/a action_conflicts = {}
1779n/a for mutex_group in self._mutually_exclusive_groups:
1780n/a group_actions = mutex_group._group_actions
1781n/a for i, mutex_action in enumerate(mutex_group._group_actions):
1782n/a conflicts = action_conflicts.setdefault(mutex_action, [])
1783n/a conflicts.extend(group_actions[:i])
1784n/a conflicts.extend(group_actions[i + 1:])
1785n/a
1786n/a # find all option indices, and determine the arg_string_pattern
1787n/a # which has an 'O' if there is an option at an index,
1788n/a # an 'A' if there is an argument, or a '-' if there is a '--'
1789n/a option_string_indices = {}
1790n/a arg_string_pattern_parts = []
1791n/a arg_strings_iter = iter(arg_strings)
1792n/a for i, arg_string in enumerate(arg_strings_iter):
1793n/a
1794n/a # all args after -- are non-options
1795n/a if arg_string == '--':
1796n/a arg_string_pattern_parts.append('-')
1797n/a for arg_string in arg_strings_iter:
1798n/a arg_string_pattern_parts.append('A')
1799n/a
1800n/a # otherwise, add the arg to the arg strings
1801n/a # and note the index if it was an option
1802n/a else:
1803n/a option_tuple = self._parse_optional(arg_string)
1804n/a if option_tuple is None:
1805n/a pattern = 'A'
1806n/a else:
1807n/a option_string_indices[i] = option_tuple
1808n/a pattern = 'O'
1809n/a arg_string_pattern_parts.append(pattern)
1810n/a
1811n/a # join the pieces together to form the pattern
1812n/a arg_strings_pattern = ''.join(arg_string_pattern_parts)
1813n/a
1814n/a # converts arg strings to the appropriate and then takes the action
1815n/a seen_actions = set()
1816n/a seen_non_default_actions = set()
1817n/a
1818n/a def take_action(action, argument_strings, option_string=None):
1819n/a seen_actions.add(action)
1820n/a argument_values = self._get_values(action, argument_strings)
1821n/a
1822n/a # error if this argument is not allowed with other previously
1823n/a # seen arguments, assuming that actions that use the default
1824n/a # value don't really count as "present"
1825n/a if argument_values is not action.default:
1826n/a seen_non_default_actions.add(action)
1827n/a for conflict_action in action_conflicts.get(action, []):
1828n/a if conflict_action in seen_non_default_actions:
1829n/a msg = _('not allowed with argument %s')
1830n/a action_name = _get_action_name(conflict_action)
1831n/a raise ArgumentError(action, msg % action_name)
1832n/a
1833n/a # take the action if we didn't receive a SUPPRESS value
1834n/a # (e.g. from a default)
1835n/a if argument_values is not SUPPRESS:
1836n/a action(self, namespace, argument_values, option_string)
1837n/a
1838n/a # function to convert arg_strings into an optional action
1839n/a def consume_optional(start_index):
1840n/a
1841n/a # get the optional identified at this index
1842n/a option_tuple = option_string_indices[start_index]
1843n/a action, option_string, explicit_arg = option_tuple
1844n/a
1845n/a # identify additional optionals in the same arg string
1846n/a # (e.g. -xyz is the same as -x -y -z if no args are required)
1847n/a match_argument = self._match_argument
1848n/a action_tuples = []
1849n/a while True:
1850n/a
1851n/a # if we found no optional action, skip it
1852n/a if action is None:
1853n/a extras.append(arg_strings[start_index])
1854n/a return start_index + 1
1855n/a
1856n/a # if there is an explicit argument, try to match the
1857n/a # optional's string arguments to only this
1858n/a if explicit_arg is not None:
1859n/a arg_count = match_argument(action, 'A')
1860n/a
1861n/a # if the action is a single-dash option and takes no
1862n/a # arguments, try to parse more single-dash options out
1863n/a # of the tail of the option string
1864n/a chars = self.prefix_chars
1865n/a if arg_count == 0 and option_string[1] not in chars:
1866n/a action_tuples.append((action, [], option_string))
1867n/a char = option_string[0]
1868n/a option_string = char + explicit_arg[0]
1869n/a new_explicit_arg = explicit_arg[1:] or None
1870n/a optionals_map = self._option_string_actions
1871n/a if option_string in optionals_map:
1872n/a action = optionals_map[option_string]
1873n/a explicit_arg = new_explicit_arg
1874n/a else:
1875n/a msg = _('ignored explicit argument %r')
1876n/a raise ArgumentError(action, msg % explicit_arg)
1877n/a
1878n/a # if the action expect exactly one argument, we've
1879n/a # successfully matched the option; exit the loop
1880n/a elif arg_count == 1:
1881n/a stop = start_index + 1
1882n/a args = [explicit_arg]
1883n/a action_tuples.append((action, args, option_string))
1884n/a break
1885n/a
1886n/a # error if a double-dash option did not use the
1887n/a # explicit argument
1888n/a else:
1889n/a msg = _('ignored explicit argument %r')
1890n/a raise ArgumentError(action, msg % explicit_arg)
1891n/a
1892n/a # if there is no explicit argument, try to match the
1893n/a # optional's string arguments with the following strings
1894n/a # if successful, exit the loop
1895n/a else:
1896n/a start = start_index + 1
1897n/a selected_patterns = arg_strings_pattern[start:]
1898n/a arg_count = match_argument(action, selected_patterns)
1899n/a stop = start + arg_count
1900n/a args = arg_strings[start:stop]
1901n/a action_tuples.append((action, args, option_string))
1902n/a break
1903n/a
1904n/a # add the Optional to the list and return the index at which
1905n/a # the Optional's string args stopped
1906n/a assert action_tuples
1907n/a for action, args, option_string in action_tuples:
1908n/a take_action(action, args, option_string)
1909n/a return stop
1910n/a
1911n/a # the list of Positionals left to be parsed; this is modified
1912n/a # by consume_positionals()
1913n/a positionals = self._get_positional_actions()
1914n/a
1915n/a # function to convert arg_strings into positional actions
1916n/a def consume_positionals(start_index):
1917n/a # match as many Positionals as possible
1918n/a match_partial = self._match_arguments_partial
1919n/a selected_pattern = arg_strings_pattern[start_index:]
1920n/a arg_counts = match_partial(positionals, selected_pattern)
1921n/a
1922n/a # slice off the appropriate arg strings for each Positional
1923n/a # and add the Positional and its args to the list
1924n/a for action, arg_count in zip(positionals, arg_counts):
1925n/a args = arg_strings[start_index: start_index + arg_count]
1926n/a start_index += arg_count
1927n/a take_action(action, args)
1928n/a
1929n/a # slice off the Positionals that we just parsed and return the
1930n/a # index at which the Positionals' string args stopped
1931n/a positionals[:] = positionals[len(arg_counts):]
1932n/a return start_index
1933n/a
1934n/a # consume Positionals and Optionals alternately, until we have
1935n/a # passed the last option string
1936n/a extras = []
1937n/a start_index = 0
1938n/a if option_string_indices:
1939n/a max_option_string_index = max(option_string_indices)
1940n/a else:
1941n/a max_option_string_index = -1
1942n/a while start_index <= max_option_string_index:
1943n/a
1944n/a # consume any Positionals preceding the next option
1945n/a next_option_string_index = min([
1946n/a index
1947n/a for index in option_string_indices
1948n/a if index >= start_index])
1949n/a if start_index != next_option_string_index:
1950n/a positionals_end_index = consume_positionals(start_index)
1951n/a
1952n/a # only try to parse the next optional if we didn't consume
1953n/a # the option string during the positionals parsing
1954n/a if positionals_end_index > start_index:
1955n/a start_index = positionals_end_index
1956n/a continue
1957n/a else:
1958n/a start_index = positionals_end_index
1959n/a
1960n/a # if we consumed all the positionals we could and we're not
1961n/a # at the index of an option string, there were extra arguments
1962n/a if start_index not in option_string_indices:
1963n/a strings = arg_strings[start_index:next_option_string_index]
1964n/a extras.extend(strings)
1965n/a start_index = next_option_string_index
1966n/a
1967n/a # consume the next optional and any arguments for it
1968n/a start_index = consume_optional(start_index)
1969n/a
1970n/a # consume any positionals following the last Optional
1971n/a stop_index = consume_positionals(start_index)
1972n/a
1973n/a # if we didn't consume all the argument strings, there were extras
1974n/a extras.extend(arg_strings[stop_index:])
1975n/a
1976n/a # make sure all required actions were present and also convert
1977n/a # action defaults which were not given as arguments
1978n/a required_actions = []
1979n/a for action in self._actions:
1980n/a if action not in seen_actions:
1981n/a if action.required:
1982n/a required_actions.append(_get_action_name(action))
1983n/a else:
1984n/a # Convert action default now instead of doing it before
1985n/a # parsing arguments to avoid calling convert functions
1986n/a # twice (which may fail) if the argument was given, but
1987n/a # only if it was defined already in the namespace
1988n/a if (action.default is not None and
1989n/a isinstance(action.default, str) and
1990n/a hasattr(namespace, action.dest) and
1991n/a action.default is getattr(namespace, action.dest)):
1992n/a setattr(namespace, action.dest,
1993n/a self._get_value(action, action.default))
1994n/a
1995n/a if required_actions:
1996n/a self.error(_('the following arguments are required: %s') %
1997n/a ', '.join(required_actions))
1998n/a
1999n/a # make sure all required groups had one option present
2000n/a for group in self._mutually_exclusive_groups:
2001n/a if group.required:
2002n/a for action in group._group_actions:
2003n/a if action in seen_non_default_actions:
2004n/a break
2005n/a
2006n/a # if no actions were used, report the error
2007n/a else:
2008n/a names = [_get_action_name(action)
2009n/a for action in group._group_actions
2010n/a if action.help is not SUPPRESS]
2011n/a msg = _('one of the arguments %s is required')
2012n/a self.error(msg % ' '.join(names))
2013n/a
2014n/a # return the updated namespace and the extra arguments
2015n/a return namespace, extras
2016n/a
2017n/a def _read_args_from_files(self, arg_strings):
2018n/a # expand arguments referencing files
2019n/a new_arg_strings = []
2020n/a for arg_string in arg_strings:
2021n/a
2022n/a # for regular arguments, just add them back into the list
2023n/a if not arg_string or arg_string[0] not in self.fromfile_prefix_chars:
2024n/a new_arg_strings.append(arg_string)
2025n/a
2026n/a # replace arguments referencing files with the file content
2027n/a else:
2028n/a try:
2029n/a with open(arg_string[1:]) as args_file:
2030n/a arg_strings = []
2031n/a for arg_line in args_file.read().splitlines():
2032n/a for arg in self.convert_arg_line_to_args(arg_line):
2033n/a arg_strings.append(arg)
2034n/a arg_strings = self._read_args_from_files(arg_strings)
2035n/a new_arg_strings.extend(arg_strings)
2036n/a except OSError:
2037n/a err = _sys.exc_info()[1]
2038n/a self.error(str(err))
2039n/a
2040n/a # return the modified argument list
2041n/a return new_arg_strings
2042n/a
2043n/a def convert_arg_line_to_args(self, arg_line):
2044n/a return [arg_line]
2045n/a
2046n/a def _match_argument(self, action, arg_strings_pattern):
2047n/a # match the pattern for this action to the arg strings
2048n/a nargs_pattern = self._get_nargs_pattern(action)
2049n/a match = _re.match(nargs_pattern, arg_strings_pattern)
2050n/a
2051n/a # raise an exception if we weren't able to find a match
2052n/a if match is None:
2053n/a nargs_errors = {
2054n/a None: _('expected one argument'),
2055n/a OPTIONAL: _('expected at most one argument'),
2056n/a ONE_OR_MORE: _('expected at least one argument'),
2057n/a }
2058n/a default = ngettext('expected %s argument',
2059n/a 'expected %s arguments',
2060n/a action.nargs) % action.nargs
2061n/a msg = nargs_errors.get(action.nargs, default)
2062n/a raise ArgumentError(action, msg)
2063n/a
2064n/a # return the number of arguments matched
2065n/a return len(match.group(1))
2066n/a
2067n/a def _match_arguments_partial(self, actions, arg_strings_pattern):
2068n/a # progressively shorten the actions list by slicing off the
2069n/a # final actions until we find a match
2070n/a result = []
2071n/a for i in range(len(actions), 0, -1):
2072n/a actions_slice = actions[:i]
2073n/a pattern = ''.join([self._get_nargs_pattern(action)
2074n/a for action in actions_slice])
2075n/a match = _re.match(pattern, arg_strings_pattern)
2076n/a if match is not None:
2077n/a result.extend([len(string) for string in match.groups()])
2078n/a break
2079n/a
2080n/a # return the list of arg string counts
2081n/a return result
2082n/a
2083n/a def _parse_optional(self, arg_string):
2084n/a # if it's an empty string, it was meant to be a positional
2085n/a if not arg_string:
2086n/a return None
2087n/a
2088n/a # if it doesn't start with a prefix, it was meant to be positional
2089n/a if not arg_string[0] in self.prefix_chars:
2090n/a return None
2091n/a
2092n/a # if the option string is present in the parser, return the action
2093n/a if arg_string in self._option_string_actions:
2094n/a action = self._option_string_actions[arg_string]
2095n/a return action, arg_string, None
2096n/a
2097n/a # if it's just a single character, it was meant to be positional
2098n/a if len(arg_string) == 1:
2099n/a return None
2100n/a
2101n/a # if the option string before the "=" is present, return the action
2102n/a if '=' in arg_string:
2103n/a option_string, explicit_arg = arg_string.split('=', 1)
2104n/a if option_string in self._option_string_actions:
2105n/a action = self._option_string_actions[option_string]
2106n/a return action, option_string, explicit_arg
2107n/a
2108n/a if self.allow_abbrev:
2109n/a # search through all possible prefixes of the option string
2110n/a # and all actions in the parser for possible interpretations
2111n/a option_tuples = self._get_option_tuples(arg_string)
2112n/a
2113n/a # if multiple actions match, the option string was ambiguous
2114n/a if len(option_tuples) > 1:
2115n/a options = ', '.join([option_string
2116n/a for action, option_string, explicit_arg in option_tuples])
2117n/a args = {'option': arg_string, 'matches': options}
2118n/a msg = _('ambiguous option: %(option)s could match %(matches)s')
2119n/a self.error(msg % args)
2120n/a
2121n/a # if exactly one action matched, this segmentation is good,
2122n/a # so return the parsed action
2123n/a elif len(option_tuples) == 1:
2124n/a option_tuple, = option_tuples
2125n/a return option_tuple
2126n/a
2127n/a # if it was not found as an option, but it looks like a negative
2128n/a # number, it was meant to be positional
2129n/a # unless there are negative-number-like options
2130n/a if self._negative_number_matcher.match(arg_string):
2131n/a if not self._has_negative_number_optionals:
2132n/a return None
2133n/a
2134n/a # if it contains a space, it was meant to be a positional
2135n/a if ' ' in arg_string:
2136n/a return None
2137n/a
2138n/a # it was meant to be an optional but there is no such option
2139n/a # in this parser (though it might be a valid option in a subparser)
2140n/a return None, arg_string, None
2141n/a
2142n/a def _get_option_tuples(self, option_string):
2143n/a result = []
2144n/a
2145n/a # option strings starting with two prefix characters are only
2146n/a # split at the '='
2147n/a chars = self.prefix_chars
2148n/a if option_string[0] in chars and option_string[1] in chars:
2149n/a if '=' in option_string:
2150n/a option_prefix, explicit_arg = option_string.split('=', 1)
2151n/a else:
2152n/a option_prefix = option_string
2153n/a explicit_arg = None
2154n/a for option_string in self._option_string_actions:
2155n/a if option_string.startswith(option_prefix):
2156n/a action = self._option_string_actions[option_string]
2157n/a tup = action, option_string, explicit_arg
2158n/a result.append(tup)
2159n/a
2160n/a # single character options can be concatenated with their arguments
2161n/a # but multiple character options always have to have their argument
2162n/a # separate
2163n/a elif option_string[0] in chars and option_string[1] not in chars:
2164n/a option_prefix = option_string
2165n/a explicit_arg = None
2166n/a short_option_prefix = option_string[:2]
2167n/a short_explicit_arg = option_string[2:]
2168n/a
2169n/a for option_string in self._option_string_actions:
2170n/a if option_string == short_option_prefix:
2171n/a action = self._option_string_actions[option_string]
2172n/a tup = action, option_string, short_explicit_arg
2173n/a result.append(tup)
2174n/a elif option_string.startswith(option_prefix):
2175n/a action = self._option_string_actions[option_string]
2176n/a tup = action, option_string, explicit_arg
2177n/a result.append(tup)
2178n/a
2179n/a # shouldn't ever get here
2180n/a else:
2181n/a self.error(_('unexpected option string: %s') % option_string)
2182n/a
2183n/a # return the collected option tuples
2184n/a return result
2185n/a
2186n/a def _get_nargs_pattern(self, action):
2187n/a # in all examples below, we have to allow for '--' args
2188n/a # which are represented as '-' in the pattern
2189n/a nargs = action.nargs
2190n/a
2191n/a # the default (None) is assumed to be a single argument
2192n/a if nargs is None:
2193n/a nargs_pattern = '(-*A-*)'
2194n/a
2195n/a # allow zero or one arguments
2196n/a elif nargs == OPTIONAL:
2197n/a nargs_pattern = '(-*A?-*)'
2198n/a
2199n/a # allow zero or more arguments
2200n/a elif nargs == ZERO_OR_MORE:
2201n/a nargs_pattern = '(-*[A-]*)'
2202n/a
2203n/a # allow one or more arguments
2204n/a elif nargs == ONE_OR_MORE:
2205n/a nargs_pattern = '(-*A[A-]*)'
2206n/a
2207n/a # allow any number of options or arguments
2208n/a elif nargs == REMAINDER:
2209n/a nargs_pattern = '([-AO]*)'
2210n/a
2211n/a # allow one argument followed by any number of options or arguments
2212n/a elif nargs == PARSER:
2213n/a nargs_pattern = '(-*A[-AO]*)'
2214n/a
2215n/a # all others should be integers
2216n/a else:
2217n/a nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs)
2218n/a
2219n/a # if this is an optional action, -- is not allowed
2220n/a if action.option_strings:
2221n/a nargs_pattern = nargs_pattern.replace('-*', '')
2222n/a nargs_pattern = nargs_pattern.replace('-', '')
2223n/a
2224n/a # return the pattern
2225n/a return nargs_pattern
2226n/a
2227n/a # ========================
2228n/a # Value conversion methods
2229n/a # ========================
2230n/a def _get_values(self, action, arg_strings):
2231n/a # for everything but PARSER, REMAINDER args, strip out first '--'
2232n/a if action.nargs not in [PARSER, REMAINDER]:
2233n/a try:
2234n/a arg_strings.remove('--')
2235n/a except ValueError:
2236n/a pass
2237n/a
2238n/a # optional argument produces a default when not present
2239n/a if not arg_strings and action.nargs == OPTIONAL:
2240n/a if action.option_strings:
2241n/a value = action.const
2242n/a else:
2243n/a value = action.default
2244n/a if isinstance(value, str):
2245n/a value = self._get_value(action, value)
2246n/a self._check_value(action, value)
2247n/a
2248n/a # when nargs='*' on a positional, if there were no command-line
2249n/a # args, use the default if it is anything other than None
2250n/a elif (not arg_strings and action.nargs == ZERO_OR_MORE and
2251n/a not action.option_strings):
2252n/a if action.default is not None:
2253n/a value = action.default
2254n/a else:
2255n/a value = arg_strings
2256n/a self._check_value(action, value)
2257n/a
2258n/a # single argument or optional argument produces a single value
2259n/a elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]:
2260n/a arg_string, = arg_strings
2261n/a value = self._get_value(action, arg_string)
2262n/a self._check_value(action, value)
2263n/a
2264n/a # REMAINDER arguments convert all values, checking none
2265n/a elif action.nargs == REMAINDER:
2266n/a value = [self._get_value(action, v) for v in arg_strings]
2267n/a
2268n/a # PARSER arguments convert all values, but check only the first
2269n/a elif action.nargs == PARSER:
2270n/a value = [self._get_value(action, v) for v in arg_strings]
2271n/a self._check_value(action, value[0])
2272n/a
2273n/a # all other types of nargs produce a list
2274n/a else:
2275n/a value = [self._get_value(action, v) for v in arg_strings]
2276n/a for v in value:
2277n/a self._check_value(action, v)
2278n/a
2279n/a # return the converted value
2280n/a return value
2281n/a
2282n/a def _get_value(self, action, arg_string):
2283n/a type_func = self._registry_get('type', action.type, action.type)
2284n/a if not callable(type_func):
2285n/a msg = _('%r is not callable')
2286n/a raise ArgumentError(action, msg % type_func)
2287n/a
2288n/a # convert the value to the appropriate type
2289n/a try:
2290n/a result = type_func(arg_string)
2291n/a
2292n/a # ArgumentTypeErrors indicate errors
2293n/a except ArgumentTypeError:
2294n/a name = getattr(action.type, '__name__', repr(action.type))
2295n/a msg = str(_sys.exc_info()[1])
2296n/a raise ArgumentError(action, msg)
2297n/a
2298n/a # TypeErrors or ValueErrors also indicate errors
2299n/a except (TypeError, ValueError):
2300n/a name = getattr(action.type, '__name__', repr(action.type))
2301n/a args = {'type': name, 'value': arg_string}
2302n/a msg = _('invalid %(type)s value: %(value)r')
2303n/a raise ArgumentError(action, msg % args)
2304n/a
2305n/a # return the converted value
2306n/a return result
2307n/a
2308n/a def _check_value(self, action, value):
2309n/a # converted value must be one of the choices (if specified)
2310n/a if action.choices is not None and value not in action.choices:
2311n/a args = {'value': value,
2312n/a 'choices': ', '.join(map(repr, action.choices))}
2313n/a msg = _('invalid choice: %(value)r (choose from %(choices)s)')
2314n/a raise ArgumentError(action, msg % args)
2315n/a
2316n/a # =======================
2317n/a # Help-formatting methods
2318n/a # =======================
2319n/a def format_usage(self):
2320n/a formatter = self._get_formatter()
2321n/a formatter.add_usage(self.usage, self._actions,
2322n/a self._mutually_exclusive_groups)
2323n/a return formatter.format_help()
2324n/a
2325n/a def format_help(self):
2326n/a formatter = self._get_formatter()
2327n/a
2328n/a # usage
2329n/a formatter.add_usage(self.usage, self._actions,
2330n/a self._mutually_exclusive_groups)
2331n/a
2332n/a # description
2333n/a formatter.add_text(self.description)
2334n/a
2335n/a # positionals, optionals and user-defined groups
2336n/a for action_group in self._action_groups:
2337n/a formatter.start_section(action_group.title)
2338n/a formatter.add_text(action_group.description)
2339n/a formatter.add_arguments(action_group._group_actions)
2340n/a formatter.end_section()
2341n/a
2342n/a # epilog
2343n/a formatter.add_text(self.epilog)
2344n/a
2345n/a # determine help from format above
2346n/a return formatter.format_help()
2347n/a
2348n/a def _get_formatter(self):
2349n/a return self.formatter_class(prog=self.prog)
2350n/a
2351n/a # =====================
2352n/a # Help-printing methods
2353n/a # =====================
2354n/a def print_usage(self, file=None):
2355n/a if file is None:
2356n/a file = _sys.stdout
2357n/a self._print_message(self.format_usage(), file)
2358n/a
2359n/a def print_help(self, file=None):
2360n/a if file is None:
2361n/a file = _sys.stdout
2362n/a self._print_message(self.format_help(), file)
2363n/a
2364n/a def _print_message(self, message, file=None):
2365n/a if message:
2366n/a if file is None:
2367n/a file = _sys.stderr
2368n/a file.write(message)
2369n/a
2370n/a # ===============
2371n/a # Exiting methods
2372n/a # ===============
2373n/a def exit(self, status=0, message=None):
2374n/a if message:
2375n/a self._print_message(message, _sys.stderr)
2376n/a _sys.exit(status)
2377n/a
2378n/a def error(self, message):
2379n/a """error(message: string)
2380n/a
2381n/a Prints a usage message incorporating the message to stderr and
2382n/a exits.
2383n/a
2384n/a If you override this in a subclass, it should not return -- it
2385n/a should either exit or raise an exception.
2386n/a """
2387n/a self.print_usage(_sys.stderr)
2388n/a args = {'prog': self.prog, 'message': message}
2389n/a self.exit(2, _('%(prog)s: error: %(message)s\n') % args)