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

Python code coverage for Lib/optparse.py

#countcontent
1n/a"""A powerful, extensible, and easy-to-use option parser.
2n/a
3n/aBy Greg Ward <gward@python.net>
4n/a
5n/aOriginally distributed as Optik.
6n/a
7n/aFor support, use the optik-users@lists.sourceforge.net mailing list
8n/a(http://lists.sourceforge.net/lists/listinfo/optik-users).
9n/a
10n/aSimple usage example:
11n/a
12n/a from optparse import OptionParser
13n/a
14n/a parser = OptionParser()
15n/a parser.add_option("-f", "--file", dest="filename",
16n/a help="write report to FILE", metavar="FILE")
17n/a parser.add_option("-q", "--quiet",
18n/a action="store_false", dest="verbose", default=True,
19n/a help="don't print status messages to stdout")
20n/a
21n/a (options, args) = parser.parse_args()
22n/a"""
23n/a
24n/a__version__ = "1.5.3"
25n/a
26n/a__all__ = ['Option',
27n/a 'make_option',
28n/a 'SUPPRESS_HELP',
29n/a 'SUPPRESS_USAGE',
30n/a 'Values',
31n/a 'OptionContainer',
32n/a 'OptionGroup',
33n/a 'OptionParser',
34n/a 'HelpFormatter',
35n/a 'IndentedHelpFormatter',
36n/a 'TitledHelpFormatter',
37n/a 'OptParseError',
38n/a 'OptionError',
39n/a 'OptionConflictError',
40n/a 'OptionValueError',
41n/a 'BadOptionError',
42n/a 'check_choice']
43n/a
44n/a__copyright__ = """
45n/aCopyright (c) 2001-2006 Gregory P. Ward. All rights reserved.
46n/aCopyright (c) 2002-2006 Python Software Foundation. All rights reserved.
47n/a
48n/aRedistribution and use in source and binary forms, with or without
49n/amodification, are permitted provided that the following conditions are
50n/amet:
51n/a
52n/a * Redistributions of source code must retain the above copyright
53n/a notice, this list of conditions and the following disclaimer.
54n/a
55n/a * Redistributions in binary form must reproduce the above copyright
56n/a notice, this list of conditions and the following disclaimer in the
57n/a documentation and/or other materials provided with the distribution.
58n/a
59n/a * Neither the name of the author nor the names of its
60n/a contributors may be used to endorse or promote products derived from
61n/a this software without specific prior written permission.
62n/a
63n/aTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
64n/aIS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
65n/aTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
66n/aPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
67n/aCONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
68n/aEXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
69n/aPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
70n/aPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
71n/aLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
72n/aNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
73n/aSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
74n/a"""
75n/a
76n/aimport sys, os
77n/aimport textwrap
78n/a
79n/adef _repr(self):
80n/a return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)
81n/a
82n/a
83n/a# This file was generated from:
84n/a# Id: option_parser.py 527 2006-07-23 15:21:30Z greg
85n/a# Id: option.py 522 2006-06-11 16:22:03Z gward
86n/a# Id: help.py 527 2006-07-23 15:21:30Z greg
87n/a# Id: errors.py 509 2006-04-20 00:58:24Z gward
88n/a
89n/atry:
90n/a from gettext import gettext, ngettext
91n/aexcept ImportError:
92n/a def gettext(message):
93n/a return message
94n/a
95n/a def ngettext(singular, plural, n):
96n/a if n == 1:
97n/a return singular
98n/a return plural
99n/a
100n/a_ = gettext
101n/a
102n/a
103n/aclass OptParseError (Exception):
104n/a def __init__(self, msg):
105n/a self.msg = msg
106n/a
107n/a def __str__(self):
108n/a return self.msg
109n/a
110n/a
111n/aclass OptionError (OptParseError):
112n/a """
113n/a Raised if an Option instance is created with invalid or
114n/a inconsistent arguments.
115n/a """
116n/a
117n/a def __init__(self, msg, option):
118n/a self.msg = msg
119n/a self.option_id = str(option)
120n/a
121n/a def __str__(self):
122n/a if self.option_id:
123n/a return "option %s: %s" % (self.option_id, self.msg)
124n/a else:
125n/a return self.msg
126n/a
127n/aclass OptionConflictError (OptionError):
128n/a """
129n/a Raised if conflicting options are added to an OptionParser.
130n/a """
131n/a
132n/aclass OptionValueError (OptParseError):
133n/a """
134n/a Raised if an invalid option value is encountered on the command
135n/a line.
136n/a """
137n/a
138n/aclass BadOptionError (OptParseError):
139n/a """
140n/a Raised if an invalid option is seen on the command line.
141n/a """
142n/a def __init__(self, opt_str):
143n/a self.opt_str = opt_str
144n/a
145n/a def __str__(self):
146n/a return _("no such option: %s") % self.opt_str
147n/a
148n/aclass AmbiguousOptionError (BadOptionError):
149n/a """
150n/a Raised if an ambiguous option is seen on the command line.
151n/a """
152n/a def __init__(self, opt_str, possibilities):
153n/a BadOptionError.__init__(self, opt_str)
154n/a self.possibilities = possibilities
155n/a
156n/a def __str__(self):
157n/a return (_("ambiguous option: %s (%s?)")
158n/a % (self.opt_str, ", ".join(self.possibilities)))
159n/a
160n/a
161n/aclass HelpFormatter:
162n/a
163n/a """
164n/a Abstract base class for formatting option help. OptionParser
165n/a instances should use one of the HelpFormatter subclasses for
166n/a formatting help; by default IndentedHelpFormatter is used.
167n/a
168n/a Instance attributes:
169n/a parser : OptionParser
170n/a the controlling OptionParser instance
171n/a indent_increment : int
172n/a the number of columns to indent per nesting level
173n/a max_help_position : int
174n/a the maximum starting column for option help text
175n/a help_position : int
176n/a the calculated starting column for option help text;
177n/a initially the same as the maximum
178n/a width : int
179n/a total number of columns for output (pass None to constructor for
180n/a this value to be taken from the $COLUMNS environment variable)
181n/a level : int
182n/a current indentation level
183n/a current_indent : int
184n/a current indentation level (in columns)
185n/a help_width : int
186n/a number of columns available for option help text (calculated)
187n/a default_tag : str
188n/a text to replace with each option's default value, "%default"
189n/a by default. Set to false value to disable default value expansion.
190n/a option_strings : { Option : str }
191n/a maps Option instances to the snippet of help text explaining
192n/a the syntax of that option, e.g. "-h, --help" or
193n/a "-fFILE, --file=FILE"
194n/a _short_opt_fmt : str
195n/a format string controlling how short options with values are
196n/a printed in help text. Must be either "%s%s" ("-fFILE") or
197n/a "%s %s" ("-f FILE"), because those are the two syntaxes that
198n/a Optik supports.
199n/a _long_opt_fmt : str
200n/a similar but for long options; must be either "%s %s" ("--file FILE")
201n/a or "%s=%s" ("--file=FILE").
202n/a """
203n/a
204n/a NO_DEFAULT_VALUE = "none"
205n/a
206n/a def __init__(self,
207n/a indent_increment,
208n/a max_help_position,
209n/a width,
210n/a short_first):
211n/a self.parser = None
212n/a self.indent_increment = indent_increment
213n/a if width is None:
214n/a try:
215n/a width = int(os.environ['COLUMNS'])
216n/a except (KeyError, ValueError):
217n/a width = 80
218n/a width -= 2
219n/a self.width = width
220n/a self.help_position = self.max_help_position = \
221n/a min(max_help_position, max(width - 20, indent_increment * 2))
222n/a self.current_indent = 0
223n/a self.level = 0
224n/a self.help_width = None # computed later
225n/a self.short_first = short_first
226n/a self.default_tag = "%default"
227n/a self.option_strings = {}
228n/a self._short_opt_fmt = "%s %s"
229n/a self._long_opt_fmt = "%s=%s"
230n/a
231n/a def set_parser(self, parser):
232n/a self.parser = parser
233n/a
234n/a def set_short_opt_delimiter(self, delim):
235n/a if delim not in ("", " "):
236n/a raise ValueError(
237n/a "invalid metavar delimiter for short options: %r" % delim)
238n/a self._short_opt_fmt = "%s" + delim + "%s"
239n/a
240n/a def set_long_opt_delimiter(self, delim):
241n/a if delim not in ("=", " "):
242n/a raise ValueError(
243n/a "invalid metavar delimiter for long options: %r" % delim)
244n/a self._long_opt_fmt = "%s" + delim + "%s"
245n/a
246n/a def indent(self):
247n/a self.current_indent += self.indent_increment
248n/a self.level += 1
249n/a
250n/a def dedent(self):
251n/a self.current_indent -= self.indent_increment
252n/a assert self.current_indent >= 0, "Indent decreased below 0."
253n/a self.level -= 1
254n/a
255n/a def format_usage(self, usage):
256n/a raise NotImplementedError("subclasses must implement")
257n/a
258n/a def format_heading(self, heading):
259n/a raise NotImplementedError("subclasses must implement")
260n/a
261n/a def _format_text(self, text):
262n/a """
263n/a Format a paragraph of free-form text for inclusion in the
264n/a help output at the current indentation level.
265n/a """
266n/a text_width = max(self.width - self.current_indent, 11)
267n/a indent = " "*self.current_indent
268n/a return textwrap.fill(text,
269n/a text_width,
270n/a initial_indent=indent,
271n/a subsequent_indent=indent)
272n/a
273n/a def format_description(self, description):
274n/a if description:
275n/a return self._format_text(description) + "\n"
276n/a else:
277n/a return ""
278n/a
279n/a def format_epilog(self, epilog):
280n/a if epilog:
281n/a return "\n" + self._format_text(epilog) + "\n"
282n/a else:
283n/a return ""
284n/a
285n/a
286n/a def expand_default(self, option):
287n/a if self.parser is None or not self.default_tag:
288n/a return option.help
289n/a
290n/a default_value = self.parser.defaults.get(option.dest)
291n/a if default_value is NO_DEFAULT or default_value is None:
292n/a default_value = self.NO_DEFAULT_VALUE
293n/a
294n/a return option.help.replace(self.default_tag, str(default_value))
295n/a
296n/a def format_option(self, option):
297n/a # The help for each option consists of two parts:
298n/a # * the opt strings and metavars
299n/a # eg. ("-x", or "-fFILENAME, --file=FILENAME")
300n/a # * the user-supplied help string
301n/a # eg. ("turn on expert mode", "read data from FILENAME")
302n/a #
303n/a # If possible, we write both of these on the same line:
304n/a # -x turn on expert mode
305n/a #
306n/a # But if the opt string list is too long, we put the help
307n/a # string on a second line, indented to the same column it would
308n/a # start in if it fit on the first line.
309n/a # -fFILENAME, --file=FILENAME
310n/a # read data from FILENAME
311n/a result = []
312n/a opts = self.option_strings[option]
313n/a opt_width = self.help_position - self.current_indent - 2
314n/a if len(opts) > opt_width:
315n/a opts = "%*s%s\n" % (self.current_indent, "", opts)
316n/a indent_first = self.help_position
317n/a else: # start help on same line as opts
318n/a opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
319n/a indent_first = 0
320n/a result.append(opts)
321n/a if option.help:
322n/a help_text = self.expand_default(option)
323n/a help_lines = textwrap.wrap(help_text, self.help_width)
324n/a result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
325n/a result.extend(["%*s%s\n" % (self.help_position, "", line)
326n/a for line in help_lines[1:]])
327n/a elif opts[-1] != "\n":
328n/a result.append("\n")
329n/a return "".join(result)
330n/a
331n/a def store_option_strings(self, parser):
332n/a self.indent()
333n/a max_len = 0
334n/a for opt in parser.option_list:
335n/a strings = self.format_option_strings(opt)
336n/a self.option_strings[opt] = strings
337n/a max_len = max(max_len, len(strings) + self.current_indent)
338n/a self.indent()
339n/a for group in parser.option_groups:
340n/a for opt in group.option_list:
341n/a strings = self.format_option_strings(opt)
342n/a self.option_strings[opt] = strings
343n/a max_len = max(max_len, len(strings) + self.current_indent)
344n/a self.dedent()
345n/a self.dedent()
346n/a self.help_position = min(max_len + 2, self.max_help_position)
347n/a self.help_width = max(self.width - self.help_position, 11)
348n/a
349n/a def format_option_strings(self, option):
350n/a """Return a comma-separated list of option strings & metavariables."""
351n/a if option.takes_value():
352n/a metavar = option.metavar or option.dest.upper()
353n/a short_opts = [self._short_opt_fmt % (sopt, metavar)
354n/a for sopt in option._short_opts]
355n/a long_opts = [self._long_opt_fmt % (lopt, metavar)
356n/a for lopt in option._long_opts]
357n/a else:
358n/a short_opts = option._short_opts
359n/a long_opts = option._long_opts
360n/a
361n/a if self.short_first:
362n/a opts = short_opts + long_opts
363n/a else:
364n/a opts = long_opts + short_opts
365n/a
366n/a return ", ".join(opts)
367n/a
368n/aclass IndentedHelpFormatter (HelpFormatter):
369n/a """Format help with indented section bodies.
370n/a """
371n/a
372n/a def __init__(self,
373n/a indent_increment=2,
374n/a max_help_position=24,
375n/a width=None,
376n/a short_first=1):
377n/a HelpFormatter.__init__(
378n/a self, indent_increment, max_help_position, width, short_first)
379n/a
380n/a def format_usage(self, usage):
381n/a return _("Usage: %s\n") % usage
382n/a
383n/a def format_heading(self, heading):
384n/a return "%*s%s:\n" % (self.current_indent, "", heading)
385n/a
386n/a
387n/aclass TitledHelpFormatter (HelpFormatter):
388n/a """Format help with underlined section headers.
389n/a """
390n/a
391n/a def __init__(self,
392n/a indent_increment=0,
393n/a max_help_position=24,
394n/a width=None,
395n/a short_first=0):
396n/a HelpFormatter.__init__ (
397n/a self, indent_increment, max_help_position, width, short_first)
398n/a
399n/a def format_usage(self, usage):
400n/a return "%s %s\n" % (self.format_heading(_("Usage")), usage)
401n/a
402n/a def format_heading(self, heading):
403n/a return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
404n/a
405n/a
406n/adef _parse_num(val, type):
407n/a if val[:2].lower() == "0x": # hexadecimal
408n/a radix = 16
409n/a elif val[:2].lower() == "0b": # binary
410n/a radix = 2
411n/a val = val[2:] or "0" # have to remove "0b" prefix
412n/a elif val[:1] == "0": # octal
413n/a radix = 8
414n/a else: # decimal
415n/a radix = 10
416n/a
417n/a return type(val, radix)
418n/a
419n/adef _parse_int(val):
420n/a return _parse_num(val, int)
421n/a
422n/a_builtin_cvt = { "int" : (_parse_int, _("integer")),
423n/a "long" : (_parse_int, _("integer")),
424n/a "float" : (float, _("floating-point")),
425n/a "complex" : (complex, _("complex")) }
426n/a
427n/adef check_builtin(option, opt, value):
428n/a (cvt, what) = _builtin_cvt[option.type]
429n/a try:
430n/a return cvt(value)
431n/a except ValueError:
432n/a raise OptionValueError(
433n/a _("option %s: invalid %s value: %r") % (opt, what, value))
434n/a
435n/adef check_choice(option, opt, value):
436n/a if value in option.choices:
437n/a return value
438n/a else:
439n/a choices = ", ".join(map(repr, option.choices))
440n/a raise OptionValueError(
441n/a _("option %s: invalid choice: %r (choose from %s)")
442n/a % (opt, value, choices))
443n/a
444n/a# Not supplying a default is different from a default of None,
445n/a# so we need an explicit "not supplied" value.
446n/aNO_DEFAULT = ("NO", "DEFAULT")
447n/a
448n/a
449n/aclass Option:
450n/a """
451n/a Instance attributes:
452n/a _short_opts : [string]
453n/a _long_opts : [string]
454n/a
455n/a action : string
456n/a type : string
457n/a dest : string
458n/a default : any
459n/a nargs : int
460n/a const : any
461n/a choices : [string]
462n/a callback : function
463n/a callback_args : (any*)
464n/a callback_kwargs : { string : any }
465n/a help : string
466n/a metavar : string
467n/a """
468n/a
469n/a # The list of instance attributes that may be set through
470n/a # keyword args to the constructor.
471n/a ATTRS = ['action',
472n/a 'type',
473n/a 'dest',
474n/a 'default',
475n/a 'nargs',
476n/a 'const',
477n/a 'choices',
478n/a 'callback',
479n/a 'callback_args',
480n/a 'callback_kwargs',
481n/a 'help',
482n/a 'metavar']
483n/a
484n/a # The set of actions allowed by option parsers. Explicitly listed
485n/a # here so the constructor can validate its arguments.
486n/a ACTIONS = ("store",
487n/a "store_const",
488n/a "store_true",
489n/a "store_false",
490n/a "append",
491n/a "append_const",
492n/a "count",
493n/a "callback",
494n/a "help",
495n/a "version")
496n/a
497n/a # The set of actions that involve storing a value somewhere;
498n/a # also listed just for constructor argument validation. (If
499n/a # the action is one of these, there must be a destination.)
500n/a STORE_ACTIONS = ("store",
501n/a "store_const",
502n/a "store_true",
503n/a "store_false",
504n/a "append",
505n/a "append_const",
506n/a "count")
507n/a
508n/a # The set of actions for which it makes sense to supply a value
509n/a # type, ie. which may consume an argument from the command line.
510n/a TYPED_ACTIONS = ("store",
511n/a "append",
512n/a "callback")
513n/a
514n/a # The set of actions which *require* a value type, ie. that
515n/a # always consume an argument from the command line.
516n/a ALWAYS_TYPED_ACTIONS = ("store",
517n/a "append")
518n/a
519n/a # The set of actions which take a 'const' attribute.
520n/a CONST_ACTIONS = ("store_const",
521n/a "append_const")
522n/a
523n/a # The set of known types for option parsers. Again, listed here for
524n/a # constructor argument validation.
525n/a TYPES = ("string", "int", "long", "float", "complex", "choice")
526n/a
527n/a # Dictionary of argument checking functions, which convert and
528n/a # validate option arguments according to the option type.
529n/a #
530n/a # Signature of checking functions is:
531n/a # check(option : Option, opt : string, value : string) -> any
532n/a # where
533n/a # option is the Option instance calling the checker
534n/a # opt is the actual option seen on the command-line
535n/a # (eg. "-a", "--file")
536n/a # value is the option argument seen on the command-line
537n/a #
538n/a # The return value should be in the appropriate Python type
539n/a # for option.type -- eg. an integer if option.type == "int".
540n/a #
541n/a # If no checker is defined for a type, arguments will be
542n/a # unchecked and remain strings.
543n/a TYPE_CHECKER = { "int" : check_builtin,
544n/a "long" : check_builtin,
545n/a "float" : check_builtin,
546n/a "complex": check_builtin,
547n/a "choice" : check_choice,
548n/a }
549n/a
550n/a
551n/a # CHECK_METHODS is a list of unbound method objects; they are called
552n/a # by the constructor, in order, after all attributes are
553n/a # initialized. The list is created and filled in later, after all
554n/a # the methods are actually defined. (I just put it here because I
555n/a # like to define and document all class attributes in the same
556n/a # place.) Subclasses that add another _check_*() method should
557n/a # define their own CHECK_METHODS list that adds their check method
558n/a # to those from this class.
559n/a CHECK_METHODS = None
560n/a
561n/a
562n/a # -- Constructor/initialization methods ----------------------------
563n/a
564n/a def __init__(self, *opts, **attrs):
565n/a # Set _short_opts, _long_opts attrs from 'opts' tuple.
566n/a # Have to be set now, in case no option strings are supplied.
567n/a self._short_opts = []
568n/a self._long_opts = []
569n/a opts = self._check_opt_strings(opts)
570n/a self._set_opt_strings(opts)
571n/a
572n/a # Set all other attrs (action, type, etc.) from 'attrs' dict
573n/a self._set_attrs(attrs)
574n/a
575n/a # Check all the attributes we just set. There are lots of
576n/a # complicated interdependencies, but luckily they can be farmed
577n/a # out to the _check_*() methods listed in CHECK_METHODS -- which
578n/a # could be handy for subclasses! The one thing these all share
579n/a # is that they raise OptionError if they discover a problem.
580n/a for checker in self.CHECK_METHODS:
581n/a checker(self)
582n/a
583n/a def _check_opt_strings(self, opts):
584n/a # Filter out None because early versions of Optik had exactly
585n/a # one short option and one long option, either of which
586n/a # could be None.
587n/a opts = [opt for opt in opts if opt]
588n/a if not opts:
589n/a raise TypeError("at least one option string must be supplied")
590n/a return opts
591n/a
592n/a def _set_opt_strings(self, opts):
593n/a for opt in opts:
594n/a if len(opt) < 2:
595n/a raise OptionError(
596n/a "invalid option string %r: "
597n/a "must be at least two characters long" % opt, self)
598n/a elif len(opt) == 2:
599n/a if not (opt[0] == "-" and opt[1] != "-"):
600n/a raise OptionError(
601n/a "invalid short option string %r: "
602n/a "must be of the form -x, (x any non-dash char)" % opt,
603n/a self)
604n/a self._short_opts.append(opt)
605n/a else:
606n/a if not (opt[0:2] == "--" and opt[2] != "-"):
607n/a raise OptionError(
608n/a "invalid long option string %r: "
609n/a "must start with --, followed by non-dash" % opt,
610n/a self)
611n/a self._long_opts.append(opt)
612n/a
613n/a def _set_attrs(self, attrs):
614n/a for attr in self.ATTRS:
615n/a if attr in attrs:
616n/a setattr(self, attr, attrs[attr])
617n/a del attrs[attr]
618n/a else:
619n/a if attr == 'default':
620n/a setattr(self, attr, NO_DEFAULT)
621n/a else:
622n/a setattr(self, attr, None)
623n/a if attrs:
624n/a attrs = sorted(attrs.keys())
625n/a raise OptionError(
626n/a "invalid keyword arguments: %s" % ", ".join(attrs),
627n/a self)
628n/a
629n/a
630n/a # -- Constructor validation methods --------------------------------
631n/a
632n/a def _check_action(self):
633n/a if self.action is None:
634n/a self.action = "store"
635n/a elif self.action not in self.ACTIONS:
636n/a raise OptionError("invalid action: %r" % self.action, self)
637n/a
638n/a def _check_type(self):
639n/a if self.type is None:
640n/a if self.action in self.ALWAYS_TYPED_ACTIONS:
641n/a if self.choices is not None:
642n/a # The "choices" attribute implies "choice" type.
643n/a self.type = "choice"
644n/a else:
645n/a # No type given? "string" is the most sensible default.
646n/a self.type = "string"
647n/a else:
648n/a # Allow type objects or builtin type conversion functions
649n/a # (int, str, etc.) as an alternative to their names.
650n/a if isinstance(self.type, type):
651n/a self.type = self.type.__name__
652n/a
653n/a if self.type == "str":
654n/a self.type = "string"
655n/a
656n/a if self.type not in self.TYPES:
657n/a raise OptionError("invalid option type: %r" % self.type, self)
658n/a if self.action not in self.TYPED_ACTIONS:
659n/a raise OptionError(
660n/a "must not supply a type for action %r" % self.action, self)
661n/a
662n/a def _check_choice(self):
663n/a if self.type == "choice":
664n/a if self.choices is None:
665n/a raise OptionError(
666n/a "must supply a list of choices for type 'choice'", self)
667n/a elif not isinstance(self.choices, (tuple, list)):
668n/a raise OptionError(
669n/a "choices must be a list of strings ('%s' supplied)"
670n/a % str(type(self.choices)).split("'")[1], self)
671n/a elif self.choices is not None:
672n/a raise OptionError(
673n/a "must not supply choices for type %r" % self.type, self)
674n/a
675n/a def _check_dest(self):
676n/a # No destination given, and we need one for this action. The
677n/a # self.type check is for callbacks that take a value.
678n/a takes_value = (self.action in self.STORE_ACTIONS or
679n/a self.type is not None)
680n/a if self.dest is None and takes_value:
681n/a
682n/a # Glean a destination from the first long option string,
683n/a # or from the first short option string if no long options.
684n/a if self._long_opts:
685n/a # eg. "--foo-bar" -> "foo_bar"
686n/a self.dest = self._long_opts[0][2:].replace('-', '_')
687n/a else:
688n/a self.dest = self._short_opts[0][1]
689n/a
690n/a def _check_const(self):
691n/a if self.action not in self.CONST_ACTIONS and self.const is not None:
692n/a raise OptionError(
693n/a "'const' must not be supplied for action %r" % self.action,
694n/a self)
695n/a
696n/a def _check_nargs(self):
697n/a if self.action in self.TYPED_ACTIONS:
698n/a if self.nargs is None:
699n/a self.nargs = 1
700n/a elif self.nargs is not None:
701n/a raise OptionError(
702n/a "'nargs' must not be supplied for action %r" % self.action,
703n/a self)
704n/a
705n/a def _check_callback(self):
706n/a if self.action == "callback":
707n/a if not callable(self.callback):
708n/a raise OptionError(
709n/a "callback not callable: %r" % self.callback, self)
710n/a if (self.callback_args is not None and
711n/a not isinstance(self.callback_args, tuple)):
712n/a raise OptionError(
713n/a "callback_args, if supplied, must be a tuple: not %r"
714n/a % self.callback_args, self)
715n/a if (self.callback_kwargs is not None and
716n/a not isinstance(self.callback_kwargs, dict)):
717n/a raise OptionError(
718n/a "callback_kwargs, if supplied, must be a dict: not %r"
719n/a % self.callback_kwargs, self)
720n/a else:
721n/a if self.callback is not None:
722n/a raise OptionError(
723n/a "callback supplied (%r) for non-callback option"
724n/a % self.callback, self)
725n/a if self.callback_args is not None:
726n/a raise OptionError(
727n/a "callback_args supplied for non-callback option", self)
728n/a if self.callback_kwargs is not None:
729n/a raise OptionError(
730n/a "callback_kwargs supplied for non-callback option", self)
731n/a
732n/a
733n/a CHECK_METHODS = [_check_action,
734n/a _check_type,
735n/a _check_choice,
736n/a _check_dest,
737n/a _check_const,
738n/a _check_nargs,
739n/a _check_callback]
740n/a
741n/a
742n/a # -- Miscellaneous methods -----------------------------------------
743n/a
744n/a def __str__(self):
745n/a return "/".join(self._short_opts + self._long_opts)
746n/a
747n/a __repr__ = _repr
748n/a
749n/a def takes_value(self):
750n/a return self.type is not None
751n/a
752n/a def get_opt_string(self):
753n/a if self._long_opts:
754n/a return self._long_opts[0]
755n/a else:
756n/a return self._short_opts[0]
757n/a
758n/a
759n/a # -- Processing methods --------------------------------------------
760n/a
761n/a def check_value(self, opt, value):
762n/a checker = self.TYPE_CHECKER.get(self.type)
763n/a if checker is None:
764n/a return value
765n/a else:
766n/a return checker(self, opt, value)
767n/a
768n/a def convert_value(self, opt, value):
769n/a if value is not None:
770n/a if self.nargs == 1:
771n/a return self.check_value(opt, value)
772n/a else:
773n/a return tuple([self.check_value(opt, v) for v in value])
774n/a
775n/a def process(self, opt, value, values, parser):
776n/a
777n/a # First, convert the value(s) to the right type. Howl if any
778n/a # value(s) are bogus.
779n/a value = self.convert_value(opt, value)
780n/a
781n/a # And then take whatever action is expected of us.
782n/a # This is a separate method to make life easier for
783n/a # subclasses to add new actions.
784n/a return self.take_action(
785n/a self.action, self.dest, opt, value, values, parser)
786n/a
787n/a def take_action(self, action, dest, opt, value, values, parser):
788n/a if action == "store":
789n/a setattr(values, dest, value)
790n/a elif action == "store_const":
791n/a setattr(values, dest, self.const)
792n/a elif action == "store_true":
793n/a setattr(values, dest, True)
794n/a elif action == "store_false":
795n/a setattr(values, dest, False)
796n/a elif action == "append":
797n/a values.ensure_value(dest, []).append(value)
798n/a elif action == "append_const":
799n/a values.ensure_value(dest, []).append(self.const)
800n/a elif action == "count":
801n/a setattr(values, dest, values.ensure_value(dest, 0) + 1)
802n/a elif action == "callback":
803n/a args = self.callback_args or ()
804n/a kwargs = self.callback_kwargs or {}
805n/a self.callback(self, opt, value, parser, *args, **kwargs)
806n/a elif action == "help":
807n/a parser.print_help()
808n/a parser.exit()
809n/a elif action == "version":
810n/a parser.print_version()
811n/a parser.exit()
812n/a else:
813n/a raise ValueError("unknown action %r" % self.action)
814n/a
815n/a return 1
816n/a
817n/a# class Option
818n/a
819n/a
820n/aSUPPRESS_HELP = "SUPPRESS"+"HELP"
821n/aSUPPRESS_USAGE = "SUPPRESS"+"USAGE"
822n/a
823n/aclass Values:
824n/a
825n/a def __init__(self, defaults=None):
826n/a if defaults:
827n/a for (attr, val) in defaults.items():
828n/a setattr(self, attr, val)
829n/a
830n/a def __str__(self):
831n/a return str(self.__dict__)
832n/a
833n/a __repr__ = _repr
834n/a
835n/a def __eq__(self, other):
836n/a if isinstance(other, Values):
837n/a return self.__dict__ == other.__dict__
838n/a elif isinstance(other, dict):
839n/a return self.__dict__ == other
840n/a else:
841n/a return NotImplemented
842n/a
843n/a def _update_careful(self, dict):
844n/a """
845n/a Update the option values from an arbitrary dictionary, but only
846n/a use keys from dict that already have a corresponding attribute
847n/a in self. Any keys in dict without a corresponding attribute
848n/a are silently ignored.
849n/a """
850n/a for attr in dir(self):
851n/a if attr in dict:
852n/a dval = dict[attr]
853n/a if dval is not None:
854n/a setattr(self, attr, dval)
855n/a
856n/a def _update_loose(self, dict):
857n/a """
858n/a Update the option values from an arbitrary dictionary,
859n/a using all keys from the dictionary regardless of whether
860n/a they have a corresponding attribute in self or not.
861n/a """
862n/a self.__dict__.update(dict)
863n/a
864n/a def _update(self, dict, mode):
865n/a if mode == "careful":
866n/a self._update_careful(dict)
867n/a elif mode == "loose":
868n/a self._update_loose(dict)
869n/a else:
870n/a raise ValueError("invalid update mode: %r" % mode)
871n/a
872n/a def read_module(self, modname, mode="careful"):
873n/a __import__(modname)
874n/a mod = sys.modules[modname]
875n/a self._update(vars(mod), mode)
876n/a
877n/a def read_file(self, filename, mode="careful"):
878n/a vars = {}
879n/a exec(open(filename).read(), vars)
880n/a self._update(vars, mode)
881n/a
882n/a def ensure_value(self, attr, value):
883n/a if not hasattr(self, attr) or getattr(self, attr) is None:
884n/a setattr(self, attr, value)
885n/a return getattr(self, attr)
886n/a
887n/a
888n/aclass OptionContainer:
889n/a
890n/a """
891n/a Abstract base class.
892n/a
893n/a Class attributes:
894n/a standard_option_list : [Option]
895n/a list of standard options that will be accepted by all instances
896n/a of this parser class (intended to be overridden by subclasses).
897n/a
898n/a Instance attributes:
899n/a option_list : [Option]
900n/a the list of Option objects contained by this OptionContainer
901n/a _short_opt : { string : Option }
902n/a dictionary mapping short option strings, eg. "-f" or "-X",
903n/a to the Option instances that implement them. If an Option
904n/a has multiple short option strings, it will appear in this
905n/a dictionary multiple times. [1]
906n/a _long_opt : { string : Option }
907n/a dictionary mapping long option strings, eg. "--file" or
908n/a "--exclude", to the Option instances that implement them.
909n/a Again, a given Option can occur multiple times in this
910n/a dictionary. [1]
911n/a defaults : { string : any }
912n/a dictionary mapping option destination names to default
913n/a values for each destination [1]
914n/a
915n/a [1] These mappings are common to (shared by) all components of the
916n/a controlling OptionParser, where they are initially created.
917n/a
918n/a """
919n/a
920n/a def __init__(self, option_class, conflict_handler, description):
921n/a # Initialize the option list and related data structures.
922n/a # This method must be provided by subclasses, and it must
923n/a # initialize at least the following instance attributes:
924n/a # option_list, _short_opt, _long_opt, defaults.
925n/a self._create_option_list()
926n/a
927n/a self.option_class = option_class
928n/a self.set_conflict_handler(conflict_handler)
929n/a self.set_description(description)
930n/a
931n/a def _create_option_mappings(self):
932n/a # For use by OptionParser constructor -- create the master
933n/a # option mappings used by this OptionParser and all
934n/a # OptionGroups that it owns.
935n/a self._short_opt = {} # single letter -> Option instance
936n/a self._long_opt = {} # long option -> Option instance
937n/a self.defaults = {} # maps option dest -> default value
938n/a
939n/a
940n/a def _share_option_mappings(self, parser):
941n/a # For use by OptionGroup constructor -- use shared option
942n/a # mappings from the OptionParser that owns this OptionGroup.
943n/a self._short_opt = parser._short_opt
944n/a self._long_opt = parser._long_opt
945n/a self.defaults = parser.defaults
946n/a
947n/a def set_conflict_handler(self, handler):
948n/a if handler not in ("error", "resolve"):
949n/a raise ValueError("invalid conflict_resolution value %r" % handler)
950n/a self.conflict_handler = handler
951n/a
952n/a def set_description(self, description):
953n/a self.description = description
954n/a
955n/a def get_description(self):
956n/a return self.description
957n/a
958n/a
959n/a def destroy(self):
960n/a """see OptionParser.destroy()."""
961n/a del self._short_opt
962n/a del self._long_opt
963n/a del self.defaults
964n/a
965n/a
966n/a # -- Option-adding methods -----------------------------------------
967n/a
968n/a def _check_conflict(self, option):
969n/a conflict_opts = []
970n/a for opt in option._short_opts:
971n/a if opt in self._short_opt:
972n/a conflict_opts.append((opt, self._short_opt[opt]))
973n/a for opt in option._long_opts:
974n/a if opt in self._long_opt:
975n/a conflict_opts.append((opt, self._long_opt[opt]))
976n/a
977n/a if conflict_opts:
978n/a handler = self.conflict_handler
979n/a if handler == "error":
980n/a raise OptionConflictError(
981n/a "conflicting option string(s): %s"
982n/a % ", ".join([co[0] for co in conflict_opts]),
983n/a option)
984n/a elif handler == "resolve":
985n/a for (opt, c_option) in conflict_opts:
986n/a if opt.startswith("--"):
987n/a c_option._long_opts.remove(opt)
988n/a del self._long_opt[opt]
989n/a else:
990n/a c_option._short_opts.remove(opt)
991n/a del self._short_opt[opt]
992n/a if not (c_option._short_opts or c_option._long_opts):
993n/a c_option.container.option_list.remove(c_option)
994n/a
995n/a def add_option(self, *args, **kwargs):
996n/a """add_option(Option)
997n/a add_option(opt_str, ..., kwarg=val, ...)
998n/a """
999n/a if isinstance(args[0], str):
1000n/a option = self.option_class(*args, **kwargs)
1001n/a elif len(args) == 1 and not kwargs:
1002n/a option = args[0]
1003n/a if not isinstance(option, Option):
1004n/a raise TypeError("not an Option instance: %r" % option)
1005n/a else:
1006n/a raise TypeError("invalid arguments")
1007n/a
1008n/a self._check_conflict(option)
1009n/a
1010n/a self.option_list.append(option)
1011n/a option.container = self
1012n/a for opt in option._short_opts:
1013n/a self._short_opt[opt] = option
1014n/a for opt in option._long_opts:
1015n/a self._long_opt[opt] = option
1016n/a
1017n/a if option.dest is not None: # option has a dest, we need a default
1018n/a if option.default is not NO_DEFAULT:
1019n/a self.defaults[option.dest] = option.default
1020n/a elif option.dest not in self.defaults:
1021n/a self.defaults[option.dest] = None
1022n/a
1023n/a return option
1024n/a
1025n/a def add_options(self, option_list):
1026n/a for option in option_list:
1027n/a self.add_option(option)
1028n/a
1029n/a # -- Option query/removal methods ----------------------------------
1030n/a
1031n/a def get_option(self, opt_str):
1032n/a return (self._short_opt.get(opt_str) or
1033n/a self._long_opt.get(opt_str))
1034n/a
1035n/a def has_option(self, opt_str):
1036n/a return (opt_str in self._short_opt or
1037n/a opt_str in self._long_opt)
1038n/a
1039n/a def remove_option(self, opt_str):
1040n/a option = self._short_opt.get(opt_str)
1041n/a if option is None:
1042n/a option = self._long_opt.get(opt_str)
1043n/a if option is None:
1044n/a raise ValueError("no such option %r" % opt_str)
1045n/a
1046n/a for opt in option._short_opts:
1047n/a del self._short_opt[opt]
1048n/a for opt in option._long_opts:
1049n/a del self._long_opt[opt]
1050n/a option.container.option_list.remove(option)
1051n/a
1052n/a
1053n/a # -- Help-formatting methods ---------------------------------------
1054n/a
1055n/a def format_option_help(self, formatter):
1056n/a if not self.option_list:
1057n/a return ""
1058n/a result = []
1059n/a for option in self.option_list:
1060n/a if not option.help is SUPPRESS_HELP:
1061n/a result.append(formatter.format_option(option))
1062n/a return "".join(result)
1063n/a
1064n/a def format_description(self, formatter):
1065n/a return formatter.format_description(self.get_description())
1066n/a
1067n/a def format_help(self, formatter):
1068n/a result = []
1069n/a if self.description:
1070n/a result.append(self.format_description(formatter))
1071n/a if self.option_list:
1072n/a result.append(self.format_option_help(formatter))
1073n/a return "\n".join(result)
1074n/a
1075n/a
1076n/aclass OptionGroup (OptionContainer):
1077n/a
1078n/a def __init__(self, parser, title, description=None):
1079n/a self.parser = parser
1080n/a OptionContainer.__init__(
1081n/a self, parser.option_class, parser.conflict_handler, description)
1082n/a self.title = title
1083n/a
1084n/a def _create_option_list(self):
1085n/a self.option_list = []
1086n/a self._share_option_mappings(self.parser)
1087n/a
1088n/a def set_title(self, title):
1089n/a self.title = title
1090n/a
1091n/a def destroy(self):
1092n/a """see OptionParser.destroy()."""
1093n/a OptionContainer.destroy(self)
1094n/a del self.option_list
1095n/a
1096n/a # -- Help-formatting methods ---------------------------------------
1097n/a
1098n/a def format_help(self, formatter):
1099n/a result = formatter.format_heading(self.title)
1100n/a formatter.indent()
1101n/a result += OptionContainer.format_help(self, formatter)
1102n/a formatter.dedent()
1103n/a return result
1104n/a
1105n/a
1106n/aclass OptionParser (OptionContainer):
1107n/a
1108n/a """
1109n/a Class attributes:
1110n/a standard_option_list : [Option]
1111n/a list of standard options that will be accepted by all instances
1112n/a of this parser class (intended to be overridden by subclasses).
1113n/a
1114n/a Instance attributes:
1115n/a usage : string
1116n/a a usage string for your program. Before it is displayed
1117n/a to the user, "%prog" will be expanded to the name of
1118n/a your program (self.prog or os.path.basename(sys.argv[0])).
1119n/a prog : string
1120n/a the name of the current program (to override
1121n/a os.path.basename(sys.argv[0])).
1122n/a description : string
1123n/a A paragraph of text giving a brief overview of your program.
1124n/a optparse reformats this paragraph to fit the current terminal
1125n/a width and prints it when the user requests help (after usage,
1126n/a but before the list of options).
1127n/a epilog : string
1128n/a paragraph of help text to print after option help
1129n/a
1130n/a option_groups : [OptionGroup]
1131n/a list of option groups in this parser (option groups are
1132n/a irrelevant for parsing the command-line, but very useful
1133n/a for generating help)
1134n/a
1135n/a allow_interspersed_args : bool = true
1136n/a if true, positional arguments may be interspersed with options.
1137n/a Assuming -a and -b each take a single argument, the command-line
1138n/a -ablah foo bar -bboo baz
1139n/a will be interpreted the same as
1140n/a -ablah -bboo -- foo bar baz
1141n/a If this flag were false, that command line would be interpreted as
1142n/a -ablah -- foo bar -bboo baz
1143n/a -- ie. we stop processing options as soon as we see the first
1144n/a non-option argument. (This is the tradition followed by
1145n/a Python's getopt module, Perl's Getopt::Std, and other argument-
1146n/a parsing libraries, but it is generally annoying to users.)
1147n/a
1148n/a process_default_values : bool = true
1149n/a if true, option default values are processed similarly to option
1150n/a values from the command line: that is, they are passed to the
1151n/a type-checking function for the option's type (as long as the
1152n/a default value is a string). (This really only matters if you
1153n/a have defined custom types; see SF bug #955889.) Set it to false
1154n/a to restore the behaviour of Optik 1.4.1 and earlier.
1155n/a
1156n/a rargs : [string]
1157n/a the argument list currently being parsed. Only set when
1158n/a parse_args() is active, and continually trimmed down as
1159n/a we consume arguments. Mainly there for the benefit of
1160n/a callback options.
1161n/a largs : [string]
1162n/a the list of leftover arguments that we have skipped while
1163n/a parsing options. If allow_interspersed_args is false, this
1164n/a list is always empty.
1165n/a values : Values
1166n/a the set of option values currently being accumulated. Only
1167n/a set when parse_args() is active. Also mainly for callbacks.
1168n/a
1169n/a Because of the 'rargs', 'largs', and 'values' attributes,
1170n/a OptionParser is not thread-safe. If, for some perverse reason, you
1171n/a need to parse command-line arguments simultaneously in different
1172n/a threads, use different OptionParser instances.
1173n/a
1174n/a """
1175n/a
1176n/a standard_option_list = []
1177n/a
1178n/a def __init__(self,
1179n/a usage=None,
1180n/a option_list=None,
1181n/a option_class=Option,
1182n/a version=None,
1183n/a conflict_handler="error",
1184n/a description=None,
1185n/a formatter=None,
1186n/a add_help_option=True,
1187n/a prog=None,
1188n/a epilog=None):
1189n/a OptionContainer.__init__(
1190n/a self, option_class, conflict_handler, description)
1191n/a self.set_usage(usage)
1192n/a self.prog = prog
1193n/a self.version = version
1194n/a self.allow_interspersed_args = True
1195n/a self.process_default_values = True
1196n/a if formatter is None:
1197n/a formatter = IndentedHelpFormatter()
1198n/a self.formatter = formatter
1199n/a self.formatter.set_parser(self)
1200n/a self.epilog = epilog
1201n/a
1202n/a # Populate the option list; initial sources are the
1203n/a # standard_option_list class attribute, the 'option_list'
1204n/a # argument, and (if applicable) the _add_version_option() and
1205n/a # _add_help_option() methods.
1206n/a self._populate_option_list(option_list,
1207n/a add_help=add_help_option)
1208n/a
1209n/a self._init_parsing_state()
1210n/a
1211n/a
1212n/a def destroy(self):
1213n/a """
1214n/a Declare that you are done with this OptionParser. This cleans up
1215n/a reference cycles so the OptionParser (and all objects referenced by
1216n/a it) can be garbage-collected promptly. After calling destroy(), the
1217n/a OptionParser is unusable.
1218n/a """
1219n/a OptionContainer.destroy(self)
1220n/a for group in self.option_groups:
1221n/a group.destroy()
1222n/a del self.option_list
1223n/a del self.option_groups
1224n/a del self.formatter
1225n/a
1226n/a
1227n/a # -- Private methods -----------------------------------------------
1228n/a # (used by our or OptionContainer's constructor)
1229n/a
1230n/a def _create_option_list(self):
1231n/a self.option_list = []
1232n/a self.option_groups = []
1233n/a self._create_option_mappings()
1234n/a
1235n/a def _add_help_option(self):
1236n/a self.add_option("-h", "--help",
1237n/a action="help",
1238n/a help=_("show this help message and exit"))
1239n/a
1240n/a def _add_version_option(self):
1241n/a self.add_option("--version",
1242n/a action="version",
1243n/a help=_("show program's version number and exit"))
1244n/a
1245n/a def _populate_option_list(self, option_list, add_help=True):
1246n/a if self.standard_option_list:
1247n/a self.add_options(self.standard_option_list)
1248n/a if option_list:
1249n/a self.add_options(option_list)
1250n/a if self.version:
1251n/a self._add_version_option()
1252n/a if add_help:
1253n/a self._add_help_option()
1254n/a
1255n/a def _init_parsing_state(self):
1256n/a # These are set in parse_args() for the convenience of callbacks.
1257n/a self.rargs = None
1258n/a self.largs = None
1259n/a self.values = None
1260n/a
1261n/a
1262n/a # -- Simple modifier methods ---------------------------------------
1263n/a
1264n/a def set_usage(self, usage):
1265n/a if usage is None:
1266n/a self.usage = _("%prog [options]")
1267n/a elif usage is SUPPRESS_USAGE:
1268n/a self.usage = None
1269n/a # For backwards compatibility with Optik 1.3 and earlier.
1270n/a elif usage.lower().startswith("usage: "):
1271n/a self.usage = usage[7:]
1272n/a else:
1273n/a self.usage = usage
1274n/a
1275n/a def enable_interspersed_args(self):
1276n/a """Set parsing to not stop on the first non-option, allowing
1277n/a interspersing switches with command arguments. This is the
1278n/a default behavior. See also disable_interspersed_args() and the
1279n/a class documentation description of the attribute
1280n/a allow_interspersed_args."""
1281n/a self.allow_interspersed_args = True
1282n/a
1283n/a def disable_interspersed_args(self):
1284n/a """Set parsing to stop on the first non-option. Use this if
1285n/a you have a command processor which runs another command that
1286n/a has options of its own and you want to make sure these options
1287n/a don't get confused.
1288n/a """
1289n/a self.allow_interspersed_args = False
1290n/a
1291n/a def set_process_default_values(self, process):
1292n/a self.process_default_values = process
1293n/a
1294n/a def set_default(self, dest, value):
1295n/a self.defaults[dest] = value
1296n/a
1297n/a def set_defaults(self, **kwargs):
1298n/a self.defaults.update(kwargs)
1299n/a
1300n/a def _get_all_options(self):
1301n/a options = self.option_list[:]
1302n/a for group in self.option_groups:
1303n/a options.extend(group.option_list)
1304n/a return options
1305n/a
1306n/a def get_default_values(self):
1307n/a if not self.process_default_values:
1308n/a # Old, pre-Optik 1.5 behaviour.
1309n/a return Values(self.defaults)
1310n/a
1311n/a defaults = self.defaults.copy()
1312n/a for option in self._get_all_options():
1313n/a default = defaults.get(option.dest)
1314n/a if isinstance(default, str):
1315n/a opt_str = option.get_opt_string()
1316n/a defaults[option.dest] = option.check_value(opt_str, default)
1317n/a
1318n/a return Values(defaults)
1319n/a
1320n/a
1321n/a # -- OptionGroup methods -------------------------------------------
1322n/a
1323n/a def add_option_group(self, *args, **kwargs):
1324n/a # XXX lots of overlap with OptionContainer.add_option()
1325n/a if isinstance(args[0], str):
1326n/a group = OptionGroup(self, *args, **kwargs)
1327n/a elif len(args) == 1 and not kwargs:
1328n/a group = args[0]
1329n/a if not isinstance(group, OptionGroup):
1330n/a raise TypeError("not an OptionGroup instance: %r" % group)
1331n/a if group.parser is not self:
1332n/a raise ValueError("invalid OptionGroup (wrong parser)")
1333n/a else:
1334n/a raise TypeError("invalid arguments")
1335n/a
1336n/a self.option_groups.append(group)
1337n/a return group
1338n/a
1339n/a def get_option_group(self, opt_str):
1340n/a option = (self._short_opt.get(opt_str) or
1341n/a self._long_opt.get(opt_str))
1342n/a if option and option.container is not self:
1343n/a return option.container
1344n/a return None
1345n/a
1346n/a
1347n/a # -- Option-parsing methods ----------------------------------------
1348n/a
1349n/a def _get_args(self, args):
1350n/a if args is None:
1351n/a return sys.argv[1:]
1352n/a else:
1353n/a return args[:] # don't modify caller's list
1354n/a
1355n/a def parse_args(self, args=None, values=None):
1356n/a """
1357n/a parse_args(args : [string] = sys.argv[1:],
1358n/a values : Values = None)
1359n/a -> (values : Values, args : [string])
1360n/a
1361n/a Parse the command-line options found in 'args' (default:
1362n/a sys.argv[1:]). Any errors result in a call to 'error()', which
1363n/a by default prints the usage message to stderr and calls
1364n/a sys.exit() with an error message. On success returns a pair
1365n/a (values, args) where 'values' is a Values instance (with all
1366n/a your option values) and 'args' is the list of arguments left
1367n/a over after parsing options.
1368n/a """
1369n/a rargs = self._get_args(args)
1370n/a if values is None:
1371n/a values = self.get_default_values()
1372n/a
1373n/a # Store the halves of the argument list as attributes for the
1374n/a # convenience of callbacks:
1375n/a # rargs
1376n/a # the rest of the command-line (the "r" stands for
1377n/a # "remaining" or "right-hand")
1378n/a # largs
1379n/a # the leftover arguments -- ie. what's left after removing
1380n/a # options and their arguments (the "l" stands for "leftover"
1381n/a # or "left-hand")
1382n/a self.rargs = rargs
1383n/a self.largs = largs = []
1384n/a self.values = values
1385n/a
1386n/a try:
1387n/a stop = self._process_args(largs, rargs, values)
1388n/a except (BadOptionError, OptionValueError) as err:
1389n/a self.error(str(err))
1390n/a
1391n/a args = largs + rargs
1392n/a return self.check_values(values, args)
1393n/a
1394n/a def check_values(self, values, args):
1395n/a """
1396n/a check_values(values : Values, args : [string])
1397n/a -> (values : Values, args : [string])
1398n/a
1399n/a Check that the supplied option values and leftover arguments are
1400n/a valid. Returns the option values and leftover arguments
1401n/a (possibly adjusted, possibly completely new -- whatever you
1402n/a like). Default implementation just returns the passed-in
1403n/a values; subclasses may override as desired.
1404n/a """
1405n/a return (values, args)
1406n/a
1407n/a def _process_args(self, largs, rargs, values):
1408n/a """_process_args(largs : [string],
1409n/a rargs : [string],
1410n/a values : Values)
1411n/a
1412n/a Process command-line arguments and populate 'values', consuming
1413n/a options and arguments from 'rargs'. If 'allow_interspersed_args' is
1414n/a false, stop at the first non-option argument. If true, accumulate any
1415n/a interspersed non-option arguments in 'largs'.
1416n/a """
1417n/a while rargs:
1418n/a arg = rargs[0]
1419n/a # We handle bare "--" explicitly, and bare "-" is handled by the
1420n/a # standard arg handler since the short arg case ensures that the
1421n/a # len of the opt string is greater than 1.
1422n/a if arg == "--":
1423n/a del rargs[0]
1424n/a return
1425n/a elif arg[0:2] == "--":
1426n/a # process a single long option (possibly with value(s))
1427n/a self._process_long_opt(rargs, values)
1428n/a elif arg[:1] == "-" and len(arg) > 1:
1429n/a # process a cluster of short options (possibly with
1430n/a # value(s) for the last one only)
1431n/a self._process_short_opts(rargs, values)
1432n/a elif self.allow_interspersed_args:
1433n/a largs.append(arg)
1434n/a del rargs[0]
1435n/a else:
1436n/a return # stop now, leave this arg in rargs
1437n/a
1438n/a # Say this is the original argument list:
1439n/a # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
1440n/a # ^
1441n/a # (we are about to process arg(i)).
1442n/a #
1443n/a # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
1444n/a # [arg0, ..., arg(i-1)] (any options and their arguments will have
1445n/a # been removed from largs).
1446n/a #
1447n/a # The while loop will usually consume 1 or more arguments per pass.
1448n/a # If it consumes 1 (eg. arg is an option that takes no arguments),
1449n/a # then after _process_arg() is done the situation is:
1450n/a #
1451n/a # largs = subset of [arg0, ..., arg(i)]
1452n/a # rargs = [arg(i+1), ..., arg(N-1)]
1453n/a #
1454n/a # If allow_interspersed_args is false, largs will always be
1455n/a # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
1456n/a # not a very interesting subset!
1457n/a
1458n/a def _match_long_opt(self, opt):
1459n/a """_match_long_opt(opt : string) -> string
1460n/a
1461n/a Determine which long option string 'opt' matches, ie. which one
1462n/a it is an unambiguous abbreviation for. Raises BadOptionError if
1463n/a 'opt' doesn't unambiguously match any long option string.
1464n/a """
1465n/a return _match_abbrev(opt, self._long_opt)
1466n/a
1467n/a def _process_long_opt(self, rargs, values):
1468n/a arg = rargs.pop(0)
1469n/a
1470n/a # Value explicitly attached to arg? Pretend it's the next
1471n/a # argument.
1472n/a if "=" in arg:
1473n/a (opt, next_arg) = arg.split("=", 1)
1474n/a rargs.insert(0, next_arg)
1475n/a had_explicit_value = True
1476n/a else:
1477n/a opt = arg
1478n/a had_explicit_value = False
1479n/a
1480n/a opt = self._match_long_opt(opt)
1481n/a option = self._long_opt[opt]
1482n/a if option.takes_value():
1483n/a nargs = option.nargs
1484n/a if len(rargs) < nargs:
1485n/a self.error(ngettext(
1486n/a "%(option)s option requires %(number)d argument",
1487n/a "%(option)s option requires %(number)d arguments",
1488n/a nargs) % {"option": opt, "number": nargs})
1489n/a elif nargs == 1:
1490n/a value = rargs.pop(0)
1491n/a else:
1492n/a value = tuple(rargs[0:nargs])
1493n/a del rargs[0:nargs]
1494n/a
1495n/a elif had_explicit_value:
1496n/a self.error(_("%s option does not take a value") % opt)
1497n/a
1498n/a else:
1499n/a value = None
1500n/a
1501n/a option.process(opt, value, values, self)
1502n/a
1503n/a def _process_short_opts(self, rargs, values):
1504n/a arg = rargs.pop(0)
1505n/a stop = False
1506n/a i = 1
1507n/a for ch in arg[1:]:
1508n/a opt = "-" + ch
1509n/a option = self._short_opt.get(opt)
1510n/a i += 1 # we have consumed a character
1511n/a
1512n/a if not option:
1513n/a raise BadOptionError(opt)
1514n/a if option.takes_value():
1515n/a # Any characters left in arg? Pretend they're the
1516n/a # next arg, and stop consuming characters of arg.
1517n/a if i < len(arg):
1518n/a rargs.insert(0, arg[i:])
1519n/a stop = True
1520n/a
1521n/a nargs = option.nargs
1522n/a if len(rargs) < nargs:
1523n/a self.error(ngettext(
1524n/a "%(option)s option requires %(number)d argument",
1525n/a "%(option)s option requires %(number)d arguments",
1526n/a nargs) % {"option": opt, "number": nargs})
1527n/a elif nargs == 1:
1528n/a value = rargs.pop(0)
1529n/a else:
1530n/a value = tuple(rargs[0:nargs])
1531n/a del rargs[0:nargs]
1532n/a
1533n/a else: # option doesn't take a value
1534n/a value = None
1535n/a
1536n/a option.process(opt, value, values, self)
1537n/a
1538n/a if stop:
1539n/a break
1540n/a
1541n/a
1542n/a # -- Feedback methods ----------------------------------------------
1543n/a
1544n/a def get_prog_name(self):
1545n/a if self.prog is None:
1546n/a return os.path.basename(sys.argv[0])
1547n/a else:
1548n/a return self.prog
1549n/a
1550n/a def expand_prog_name(self, s):
1551n/a return s.replace("%prog", self.get_prog_name())
1552n/a
1553n/a def get_description(self):
1554n/a return self.expand_prog_name(self.description)
1555n/a
1556n/a def exit(self, status=0, msg=None):
1557n/a if msg:
1558n/a sys.stderr.write(msg)
1559n/a sys.exit(status)
1560n/a
1561n/a def error(self, msg):
1562n/a """error(msg : string)
1563n/a
1564n/a Print a usage message incorporating 'msg' to stderr and exit.
1565n/a If you override this in a subclass, it should not return -- it
1566n/a should either exit or raise an exception.
1567n/a """
1568n/a self.print_usage(sys.stderr)
1569n/a self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
1570n/a
1571n/a def get_usage(self):
1572n/a if self.usage:
1573n/a return self.formatter.format_usage(
1574n/a self.expand_prog_name(self.usage))
1575n/a else:
1576n/a return ""
1577n/a
1578n/a def print_usage(self, file=None):
1579n/a """print_usage(file : file = stdout)
1580n/a
1581n/a Print the usage message for the current program (self.usage) to
1582n/a 'file' (default stdout). Any occurrence of the string "%prog" in
1583n/a self.usage is replaced with the name of the current program
1584n/a (basename of sys.argv[0]). Does nothing if self.usage is empty
1585n/a or not defined.
1586n/a """
1587n/a if self.usage:
1588n/a print(self.get_usage(), file=file)
1589n/a
1590n/a def get_version(self):
1591n/a if self.version:
1592n/a return self.expand_prog_name(self.version)
1593n/a else:
1594n/a return ""
1595n/a
1596n/a def print_version(self, file=None):
1597n/a """print_version(file : file = stdout)
1598n/a
1599n/a Print the version message for this program (self.version) to
1600n/a 'file' (default stdout). As with print_usage(), any occurrence
1601n/a of "%prog" in self.version is replaced by the current program's
1602n/a name. Does nothing if self.version is empty or undefined.
1603n/a """
1604n/a if self.version:
1605n/a print(self.get_version(), file=file)
1606n/a
1607n/a def format_option_help(self, formatter=None):
1608n/a if formatter is None:
1609n/a formatter = self.formatter
1610n/a formatter.store_option_strings(self)
1611n/a result = []
1612n/a result.append(formatter.format_heading(_("Options")))
1613n/a formatter.indent()
1614n/a if self.option_list:
1615n/a result.append(OptionContainer.format_option_help(self, formatter))
1616n/a result.append("\n")
1617n/a for group in self.option_groups:
1618n/a result.append(group.format_help(formatter))
1619n/a result.append("\n")
1620n/a formatter.dedent()
1621n/a # Drop the last "\n", or the header if no options or option groups:
1622n/a return "".join(result[:-1])
1623n/a
1624n/a def format_epilog(self, formatter):
1625n/a return formatter.format_epilog(self.epilog)
1626n/a
1627n/a def format_help(self, formatter=None):
1628n/a if formatter is None:
1629n/a formatter = self.formatter
1630n/a result = []
1631n/a if self.usage:
1632n/a result.append(self.get_usage() + "\n")
1633n/a if self.description:
1634n/a result.append(self.format_description(formatter) + "\n")
1635n/a result.append(self.format_option_help(formatter))
1636n/a result.append(self.format_epilog(formatter))
1637n/a return "".join(result)
1638n/a
1639n/a def print_help(self, file=None):
1640n/a """print_help(file : file = stdout)
1641n/a
1642n/a Print an extended help message, listing all options and any
1643n/a help text provided with them, to 'file' (default stdout).
1644n/a """
1645n/a if file is None:
1646n/a file = sys.stdout
1647n/a file.write(self.format_help())
1648n/a
1649n/a# class OptionParser
1650n/a
1651n/a
1652n/adef _match_abbrev(s, wordmap):
1653n/a """_match_abbrev(s : string, wordmap : {string : Option}) -> string
1654n/a
1655n/a Return the string key in 'wordmap' for which 's' is an unambiguous
1656n/a abbreviation. If 's' is found to be ambiguous or doesn't match any of
1657n/a 'words', raise BadOptionError.
1658n/a """
1659n/a # Is there an exact match?
1660n/a if s in wordmap:
1661n/a return s
1662n/a else:
1663n/a # Isolate all words with s as a prefix.
1664n/a possibilities = [word for word in wordmap.keys()
1665n/a if word.startswith(s)]
1666n/a # No exact match, so there had better be just one possibility.
1667n/a if len(possibilities) == 1:
1668n/a return possibilities[0]
1669n/a elif not possibilities:
1670n/a raise BadOptionError(s)
1671n/a else:
1672n/a # More than one possible completion: ambiguous prefix.
1673n/a possibilities.sort()
1674n/a raise AmbiguousOptionError(s, possibilities)
1675n/a
1676n/a
1677n/a# Some day, there might be many Option classes. As of Optik 1.3, the
1678n/a# preferred way to instantiate Options is indirectly, via make_option(),
1679n/a# which will become a factory function when there are many Option
1680n/a# classes.
1681n/amake_option = Option