optparse.py 59.1 KB
Newer Older
Benjamin Peterson's avatar
Benjamin Peterson committed
1
"""A powerful, extensible, and easy-to-use option parser.
2 3 4

By Greg Ward <gward@python.net>

Benjamin Peterson's avatar
Benjamin Peterson committed
5
Originally distributed as Optik.
6 7 8

For support, use the optik-users@lists.sourceforge.net mailing list
(http://lists.sourceforge.net/lists/listinfo/optik-users).
9 10 11 12 13 14 15 16 17 18 19 20 21

Simple usage example:

   from optparse import OptionParser

   parser = OptionParser()
   parser.add_option("-f", "--file", dest="filename",
                     help="write report to FILE", metavar="FILE")
   parser.add_option("-q", "--quiet",
                     action="store_false", dest="verbose", default=True,
                     help="don't print status messages to stdout")

   (options, args) = parser.parse_args()
22 23
"""

24
__version__ = "1.5.3"
25 26

__all__ = ['Option',
Benjamin Peterson's avatar
Benjamin Peterson committed
27
           'make_option',
28 29 30 31 32 33 34 35 36 37 38 39 40 41
           'SUPPRESS_HELP',
           'SUPPRESS_USAGE',
           'Values',
           'OptionContainer',
           'OptionGroup',
           'OptionParser',
           'HelpFormatter',
           'IndentedHelpFormatter',
           'TitledHelpFormatter',
           'OptParseError',
           'OptionError',
           'OptionConflictError',
           'OptionValueError',
           'BadOptionError']
42

43
__copyright__ = """
44 45
Copyright (c) 2001-2006 Gregory P. Ward.  All rights reserved.
Copyright (c) 2002-2006 Python Software Foundation.  All rights reserved.
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

  * Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

  * Neither the name of the author nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import sys, os
import textwrap
77 78 79 80 81 82

def _repr(self):
    return "<%s at 0x%x: %s>" % (self.__class__.__name__, id(self), self)


# This file was generated from:
83 84 85
#   Id: option_parser.py 527 2006-07-23 15:21:30Z greg
#   Id: option.py 522 2006-06-11 16:22:03Z gward
#   Id: help.py 527 2006-07-23 15:21:30Z greg
86 87 88 89 90 91 92 93 94
#   Id: errors.py 509 2006-04-20 00:58:24Z gward

try:
    from gettext import gettext
except ImportError:
    def gettext(message):
        return message
_ = gettext

95 96

class OptParseError (Exception):
97
    def __init__(self, msg):
98 99
        self.msg = msg

100
    def __str__(self):
101 102
        return self.msg

103

104 105 106 107 108 109
class OptionError (OptParseError):
    """
    Raised if an Option instance is created with invalid or
    inconsistent arguments.
    """

110
    def __init__(self, msg, option):
111 112 113
        self.msg = msg
        self.option_id = str(option)

114
    def __str__(self):
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
        if self.option_id:
            return "option %s: %s" % (self.option_id, self.msg)
        else:
            return self.msg

class OptionConflictError (OptionError):
    """
    Raised if conflicting options are added to an OptionParser.
    """

class OptionValueError (OptParseError):
    """
    Raised if an invalid option value is encountered on the command
    line.
    """

class BadOptionError (OptParseError):
    """
133 134 135 136 137 138 139 140 141 142 143
    Raised if an invalid option is seen on the command line.
    """
    def __init__(self, opt_str):
        self.opt_str = opt_str

    def __str__(self):
        return _("no such option: %s") % self.opt_str

class AmbiguousOptionError (BadOptionError):
    """
    Raised if an ambiguous option is seen on the command line.
144
    """
145 146 147 148 149 150 151
    def __init__(self, opt_str, possibilities):
        BadOptionError.__init__(self, opt_str)
        self.possibilities = possibilities

    def __str__(self):
        return (_("ambiguous option: %s (%s?)")
                % (self.opt_str, ", ".join(self.possibilities)))
152 153


154 155 156 157 158 159 160 161
class HelpFormatter:

    """
    Abstract base class for formatting option help.  OptionParser
    instances should use one of the HelpFormatter subclasses for
    formatting help; by default IndentedHelpFormatter is used.

    Instance attributes:
162 163
      parser : OptionParser
        the controlling OptionParser instance
164 165 166 167 168 169 170 171
      indent_increment : int
        the number of columns to indent per nesting level
      max_help_position : int
        the maximum starting column for option help text
      help_position : int
        the calculated starting column for option help text;
        initially the same as the maximum
      width : int
172 173
        total number of columns for output (pass None to constructor for
        this value to be taken from the $COLUMNS environment variable)
174 175 176 177 178 179
      level : int
        current indentation level
      current_indent : int
        current indentation level (in columns)
      help_width : int
        number of columns available for option help text (calculated)
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
      default_tag : str
        text to replace with each option's default value, "%default"
        by default.  Set to false value to disable default value expansion.
      option_strings : { Option : str }
        maps Option instances to the snippet of help text explaining
        the syntax of that option, e.g. "-h, --help" or
        "-fFILE, --file=FILE"
      _short_opt_fmt : str
        format string controlling how short options with values are
        printed in help text.  Must be either "%s%s" ("-fFILE") or
        "%s %s" ("-f FILE"), because those are the two syntaxes that
        Optik supports.
      _long_opt_fmt : str
        similar but for long options; must be either "%s %s" ("--file FILE")
        or "%s=%s" ("--file=FILE").
195 196
    """

197 198 199 200 201 202 203 204
    NO_DEFAULT_VALUE = "none"

    def __init__(self,
                 indent_increment,
                 max_help_position,
                 width,
                 short_first):
        self.parser = None
205 206
        self.indent_increment = indent_increment
        self.help_position = self.max_help_position = max_help_position
207 208 209 210 211 212
        if width is None:
            try:
                width = int(os.environ['COLUMNS'])
            except (KeyError, ValueError):
                width = 80
            width -= 2
213 214 215
        self.width = width
        self.current_indent = 0
        self.level = 0
216
        self.help_width = None          # computed later
217
        self.short_first = short_first
218 219 220 221 222 223 224 225 226 227 228 229 230
        self.default_tag = "%default"
        self.option_strings = {}
        self._short_opt_fmt = "%s %s"
        self._long_opt_fmt = "%s=%s"

    def set_parser(self, parser):
        self.parser = parser

    def set_short_opt_delimiter(self, delim):
        if delim not in ("", " "):
            raise ValueError(
                "invalid metavar delimiter for short options: %r" % delim)
        self._short_opt_fmt = "%s" + delim + "%s"
231

232 233 234 235 236 237 238
    def set_long_opt_delimiter(self, delim):
        if delim not in ("=", " "):
            raise ValueError(
                "invalid metavar delimiter for long options: %r" % delim)
        self._long_opt_fmt = "%s" + delim + "%s"

    def indent(self):
239 240 241
        self.current_indent += self.indent_increment
        self.level += 1

242
    def dedent(self):
243 244 245 246
        self.current_indent -= self.indent_increment
        assert self.current_indent >= 0, "Indent decreased below 0."
        self.level -= 1

247
    def format_usage(self, usage):
248
        raise NotImplementedError("subclasses must implement")
249

250
    def format_heading(self, heading):
251
        raise NotImplementedError("subclasses must implement")
252

253 254 255 256 257 258
    def _format_text(self, text):
        """
        Format a paragraph of free-form text for inclusion in the
        help output at the current indentation level.
        """
        text_width = self.width - self.current_indent
259
        indent = " "*self.current_indent
260 261
        return textwrap.fill(text,
                             text_width,
262
                             initial_indent=indent,
263 264 265 266 267 268 269 270 271 272 273 274 275 276
                             subsequent_indent=indent)

    def format_description(self, description):
        if description:
            return self._format_text(description) + "\n"
        else:
            return ""

    def format_epilog(self, epilog):
        if epilog:
            return "\n" + self._format_text(epilog) + "\n"
        else:
            return ""

277 278 279 280 281 282 283 284

    def expand_default(self, option):
        if self.parser is None or not self.default_tag:
            return option.help

        default_value = self.parser.defaults.get(option.dest)
        if default_value is NO_DEFAULT or default_value is None:
            default_value = self.NO_DEFAULT_VALUE
285

286 287 288
        return option.help.replace(self.default_tag, str(default_value))

    def format_option(self, option):
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
        # The help for each option consists of two parts:
        #   * the opt strings and metavars
        #     eg. ("-x", or "-fFILENAME, --file=FILENAME")
        #   * the user-supplied help string
        #     eg. ("turn on expert mode", "read data from FILENAME")
        #
        # If possible, we write both of these on the same line:
        #   -x      turn on expert mode
        #
        # But if the opt string list is too long, we put the help
        # string on a second line, indented to the same column it would
        # start in if it fit on the first line.
        #   -fFILENAME, --file=FILENAME
        #           read data from FILENAME
        result = []
304
        opts = self.option_strings[option]
305 306 307 308 309 310 311 312 313
        opt_width = self.help_position - self.current_indent - 2
        if len(opts) > opt_width:
            opts = "%*s%s\n" % (self.current_indent, "", opts)
            indent_first = self.help_position
        else:                       # start help on same line as opts
            opts = "%*s%-*s  " % (self.current_indent, "", opt_width, opts)
            indent_first = 0
        result.append(opts)
        if option.help:
314 315
            help_text = self.expand_default(option)
            help_lines = textwrap.wrap(help_text, self.help_width)
316 317 318 319 320 321 322
            result.append("%*s%s\n" % (indent_first, "", help_lines[0]))
            result.extend(["%*s%s\n" % (self.help_position, "", line)
                           for line in help_lines[1:]])
        elif opts[-1] != "\n":
            result.append("\n")
        return "".join(result)

323
    def store_option_strings(self, parser):
324 325 326 327
        self.indent()
        max_len = 0
        for opt in parser.option_list:
            strings = self.format_option_strings(opt)
328
            self.option_strings[opt] = strings
329 330 331 332 333
            max_len = max(max_len, len(strings) + self.current_indent)
        self.indent()
        for group in parser.option_groups:
            for opt in group.option_list:
                strings = self.format_option_strings(opt)
334
                self.option_strings[opt] = strings
335 336 337 338
                max_len = max(max_len, len(strings) + self.current_indent)
        self.dedent()
        self.dedent()
        self.help_position = min(max_len + 2, self.max_help_position)
339
        self.help_width = self.width - self.help_position
340

341
    def format_option_strings(self, option):
342
        """Return a comma-separated list of option strings & metavariables."""
343
        if option.takes_value():
344
            metavar = option.metavar or option.dest.upper()
345 346 347 348
            short_opts = [self._short_opt_fmt % (sopt, metavar)
                          for sopt in option._short_opts]
            long_opts = [self._long_opt_fmt % (lopt, metavar)
                         for lopt in option._long_opts]
349
        else:
350 351
            short_opts = option._short_opts
            long_opts = option._long_opts
352

353 354
        if self.short_first:
            opts = short_opts + long_opts
355
        else:
356
            opts = long_opts + short_opts
357

358
        return ", ".join(opts)
359 360 361 362 363

class IndentedHelpFormatter (HelpFormatter):
    """Format help with indented section bodies.
    """

364 365 366 367 368
    def __init__(self,
                 indent_increment=2,
                 max_help_position=24,
                 width=None,
                 short_first=1):
369 370 371
        HelpFormatter.__init__(
            self, indent_increment, max_help_position, width, short_first)

372
    def format_usage(self, usage):
373
        return _("Usage: %s\n") % usage
374

375
    def format_heading(self, heading):
376 377 378 379 380 381 382
        return "%*s%s:\n" % (self.current_indent, "", heading)


class TitledHelpFormatter (HelpFormatter):
    """Format help with underlined section headers.
    """

383 384 385 386 387
    def __init__(self,
                 indent_increment=0,
                 max_help_position=24,
                 width=None,
                 short_first=0):
388 389 390
        HelpFormatter.__init__ (
            self, indent_increment, max_help_position, width, short_first)

391 392
    def format_usage(self, usage):
        return "%s  %s\n" % (self.format_heading(_("Usage")), usage)
393

394
    def format_heading(self, heading):
395
        return "%s\n%s\n" % (heading, "=-"[self.level] * len(heading))
396 397


398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
def _parse_num(val, type):
    if val[:2].lower() == "0x":         # hexadecimal
        radix = 16
    elif val[:2].lower() == "0b":       # binary
        radix = 2
        val = val[2:] or "0"            # have to remove "0b" prefix
    elif val[:1] == "0":                # octal
        radix = 8
    else:                               # decimal
        radix = 10

    return type(val, radix)

def _parse_int(val):
    return _parse_num(val, int)

def _parse_long(val):
415
    return _parse_num(val, int)
416 417 418

_builtin_cvt = { "int" : (_parse_int, _("integer")),
                 "long" : (_parse_long, _("long integer")),
419 420
                 "float" : (float, _("floating-point")),
                 "complex" : (complex, _("complex")) }
421

422
def check_builtin(option, opt, value):
423 424 425 426 427
    (cvt, what) = _builtin_cvt[option.type]
    try:
        return cvt(value)
    except ValueError:
        raise OptionValueError(
428
            _("option %s: invalid %s value: %r") % (opt, what, value))
429 430 431 432 433 434 435

def check_choice(option, opt, value):
    if value in option.choices:
        return value
    else:
        choices = ", ".join(map(repr, option.choices))
        raise OptionValueError(
436
            _("option %s: invalid choice: %r (choose from %s)")
437 438 439 440
            % (opt, value, choices))

# Not supplying a default is different from a default of None,
# so we need an explicit "not supplied" value.
441
NO_DEFAULT = ("NO", "DEFAULT")
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485


class Option:
    """
    Instance attributes:
      _short_opts : [string]
      _long_opts : [string]

      action : string
      type : string
      dest : string
      default : any
      nargs : int
      const : any
      choices : [string]
      callback : function
      callback_args : (any*)
      callback_kwargs : { string : any }
      help : string
      metavar : string
    """

    # The list of instance attributes that may be set through
    # keyword args to the constructor.
    ATTRS = ['action',
             'type',
             'dest',
             'default',
             'nargs',
             'const',
             'choices',
             'callback',
             'callback_args',
             'callback_kwargs',
             'help',
             'metavar']

    # The set of actions allowed by option parsers.  Explicitly listed
    # here so the constructor can validate its arguments.
    ACTIONS = ("store",
               "store_const",
               "store_true",
               "store_false",
               "append",
486
               "append_const",
487 488 489 490 491 492 493 494 495 496 497 498 499
               "count",
               "callback",
               "help",
               "version")

    # The set of actions that involve storing a value somewhere;
    # also listed just for constructor argument validation.  (If
    # the action is one of these, there must be a destination.)
    STORE_ACTIONS = ("store",
                     "store_const",
                     "store_true",
                     "store_false",
                     "append",
500
                     "append_const",
501 502 503
                     "count")

    # The set of actions for which it makes sense to supply a value
504
    # type, ie. which may consume an argument from the command line.
505 506 507 508
    TYPED_ACTIONS = ("store",
                     "append",
                     "callback")

509 510 511 512 513
    # The set of actions which *require* a value type, ie. that
    # always consume an argument from the command line.
    ALWAYS_TYPED_ACTIONS = ("store",
                            "append")

514 515 516 517
    # The set of actions which take a 'const' attribute.
    CONST_ACTIONS = ("store_const",
                     "append_const")

518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    # The set of known types for option parsers.  Again, listed here for
    # constructor argument validation.
    TYPES = ("string", "int", "long", "float", "complex", "choice")

    # Dictionary of argument checking functions, which convert and
    # validate option arguments according to the option type.
    #
    # Signature of checking functions is:
    #   check(option : Option, opt : string, value : string) -> any
    # where
    #   option is the Option instance calling the checker
    #   opt is the actual option seen on the command-line
    #     (eg. "-a", "--file")
    #   value is the option argument seen on the command-line
    #
    # The return value should be in the appropriate Python type
    # for option.type -- eg. an integer if option.type == "int".
    #
    # If no checker is defined for a type, arguments will be
    # unchecked and remain strings.
    TYPE_CHECKER = { "int"    : check_builtin,
                     "long"   : check_builtin,
                     "float"  : check_builtin,
541
                     "complex": check_builtin,
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
                     "choice" : check_choice,
                   }


    # CHECK_METHODS is a list of unbound method objects; they are called
    # by the constructor, in order, after all attributes are
    # initialized.  The list is created and filled in later, after all
    # the methods are actually defined.  (I just put it here because I
    # like to define and document all class attributes in the same
    # place.)  Subclasses that add another _check_*() method should
    # define their own CHECK_METHODS list that adds their check method
    # to those from this class.
    CHECK_METHODS = None


    # -- Constructor/initialization methods ----------------------------

559
    def __init__(self, *opts, **attrs):
560 561 562 563
        # Set _short_opts, _long_opts attrs from 'opts' tuple.
        # Have to be set now, in case no option strings are supplied.
        self._short_opts = []
        self._long_opts = []
564 565 566 567 568 569 570 571 572 573 574 575 576 577
        opts = self._check_opt_strings(opts)
        self._set_opt_strings(opts)

        # Set all other attrs (action, type, etc.) from 'attrs' dict
        self._set_attrs(attrs)

        # Check all the attributes we just set.  There are lots of
        # complicated interdependencies, but luckily they can be farmed
        # out to the _check_*() methods listed in CHECK_METHODS -- which
        # could be handy for subclasses!  The one thing these all share
        # is that they raise OptionError if they discover a problem.
        for checker in self.CHECK_METHODS:
            checker(self)

578
    def _check_opt_strings(self, opts):
579 580 581
        # Filter out None because early versions of Optik had exactly
        # one short option and one long option, either of which
        # could be None.
582
        opts = [opt for opt in opts if opt]
583
        if not opts:
584
            raise TypeError("at least one option string must be supplied")
585 586
        return opts

587
    def _set_opt_strings(self, opts):
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
        for opt in opts:
            if len(opt) < 2:
                raise OptionError(
                    "invalid option string %r: "
                    "must be at least two characters long" % opt, self)
            elif len(opt) == 2:
                if not (opt[0] == "-" and opt[1] != "-"):
                    raise OptionError(
                        "invalid short option string %r: "
                        "must be of the form -x, (x any non-dash char)" % opt,
                        self)
                self._short_opts.append(opt)
            else:
                if not (opt[0:2] == "--" and opt[2] != "-"):
                    raise OptionError(
                        "invalid long option string %r: "
                        "must start with --, followed by non-dash" % opt,
                        self)
                self._long_opts.append(opt)

608
    def _set_attrs(self, attrs):
609
        for attr in self.ATTRS:
610
            if attr in attrs:
611 612 613 614 615 616 617 618
                setattr(self, attr, attrs[attr])
                del attrs[attr]
            else:
                if attr == 'default':
                    setattr(self, attr, NO_DEFAULT)
                else:
                    setattr(self, attr, None)
        if attrs:
619
            attrs = sorted(attrs.keys())
620
            raise OptionError(
621
                "invalid keyword arguments: %s" % ", ".join(attrs),
622 623 624 625 626
                self)


    # -- Constructor validation methods --------------------------------

627
    def _check_action(self):
628 629 630 631 632
        if self.action is None:
            self.action = "store"
        elif self.action not in self.ACTIONS:
            raise OptionError("invalid action: %r" % self.action, self)

633
    def _check_type(self):
634
        if self.type is None:
635
            if self.action in self.ALWAYS_TYPED_ACTIONS:
636 637 638 639 640 641 642
                if self.choices is not None:
                    # The "choices" attribute implies "choice" type.
                    self.type = "choice"
                else:
                    # No type given?  "string" is the most sensible default.
                    self.type = "string"
        else:
643 644
            # Allow type objects or builtin type conversion functions
            # (int, str, etc.) as an alternative to their names.  (The
645
            # complicated check of builtins is only necessary for
646 647
            # Python 2.1 and earlier, and is short-circuited by the
            # first check on modern Pythons.)
648
            import builtins
649
            if ( isinstance(self.type, type) or
650
                 (hasattr(self.type, "__name__") and
651
                  getattr(builtins, self.type.__name__, None) is self.type) ):
652
                self.type = self.type.__name__
653

654 655 656
            if self.type == "str":
                self.type = "string"

657 658 659 660 661 662 663 664 665 666 667
            if self.type not in self.TYPES:
                raise OptionError("invalid option type: %r" % self.type, self)
            if self.action not in self.TYPED_ACTIONS:
                raise OptionError(
                    "must not supply a type for action %r" % self.action, self)

    def _check_choice(self):
        if self.type == "choice":
            if self.choices is None:
                raise OptionError(
                    "must supply a list of choices for type 'choice'", self)
668
            elif not isinstance(self.choices, (tuple, list)):
669 670 671 672 673 674 675
                raise OptionError(
                    "choices must be a list of strings ('%s' supplied)"
                    % str(type(self.choices)).split("'")[1], self)
        elif self.choices is not None:
            raise OptionError(
                "must not supply choices for type %r" % self.type, self)

676 677 678 679 680 681 682
    def _check_dest(self):
        # No destination given, and we need one for this action.  The
        # self.type check is for callbacks that take a value.
        takes_value = (self.action in self.STORE_ACTIONS or
                       self.type is not None)
        if self.dest is None and takes_value:

683 684 685 686 687 688 689 690
            # Glean a destination from the first long option string,
            # or from the first short option string if no long options.
            if self._long_opts:
                # eg. "--foo-bar" -> "foo_bar"
                self.dest = self._long_opts[0][2:].replace('-', '_')
            else:
                self.dest = self._short_opts[0][1]

691
    def _check_const(self):
692
        if self.action not in self.CONST_ACTIONS and self.const is not None:
693 694 695 696
            raise OptionError(
                "'const' must not be supplied for action %r" % self.action,
                self)

697
    def _check_nargs(self):
698 699 700 701 702 703 704 705
        if self.action in self.TYPED_ACTIONS:
            if self.nargs is None:
                self.nargs = 1
        elif self.nargs is not None:
            raise OptionError(
                "'nargs' must not be supplied for action %r" % self.action,
                self)

706
    def _check_callback(self):
707
        if self.action == "callback":
708
            if not callable(self.callback):
709 710 711
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
712
                not isinstance(self.callback_args, tuple)):
713 714 715 716
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
717
                not isinstance(self.callback_kwargs, dict)):
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self)


    CHECK_METHODS = [_check_action,
                     _check_type,
                     _check_choice,
                     _check_dest,
                     _check_const,
                     _check_nargs,
                     _check_callback]


    # -- Miscellaneous methods -----------------------------------------

745
    def __str__(self):
746
        return "/".join(self._short_opts + self._long_opts)
747

748 749 750
    __repr__ = _repr

    def takes_value(self):
751 752
        return self.type is not None

753 754 755 756 757 758
    def get_opt_string(self):
        if self._long_opts:
            return self._long_opts[0]
        else:
            return self._short_opts[0]

759 760 761

    # -- Processing methods --------------------------------------------

762
    def check_value(self, opt, value):
763 764 765 766 767 768
        checker = self.TYPE_CHECKER.get(self.type)
        if checker is None:
            return value
        else:
            return checker(self, opt, value)

769
    def convert_value(self, opt, value):
770 771
        if value is not None:
            if self.nargs == 1:
772
                return self.check_value(opt, value)
773
            else:
774 775 776 777 778 779 780
                return tuple([self.check_value(opt, v) for v in value])

    def process(self, opt, value, values, parser):

        # First, convert the value(s) to the right type.  Howl if any
        # value(s) are bogus.
        value = self.convert_value(opt, value)
781 782 783 784 785 786 787

        # And then take whatever action is expected of us.
        # This is a separate method to make life easier for
        # subclasses to add new actions.
        return self.take_action(
            self.action, self.dest, opt, value, values, parser)

788
    def take_action(self, action, dest, opt, value, values, parser):
789 790 791 792 793
        if action == "store":
            setattr(values, dest, value)
        elif action == "store_const":
            setattr(values, dest, self.const)
        elif action == "store_true":
794
            setattr(values, dest, True)
795
        elif action == "store_false":
796
            setattr(values, dest, False)
797 798
        elif action == "append":
            values.ensure_value(dest, []).append(value)
799 800
        elif action == "append_const":
            values.ensure_value(dest, []).append(self.const)
801 802 803 804 805 806 807 808
        elif action == "count":
            setattr(values, dest, values.ensure_value(dest, 0) + 1)
        elif action == "callback":
            args = self.callback_args or ()
            kwargs = self.callback_kwargs or {}
            self.callback(self, opt, value, parser, *args, **kwargs)
        elif action == "help":
            parser.print_help()
809
            parser.exit()
810 811
        elif action == "version":
            parser.print_version()
812
            parser.exit()
813
        else:
Benjamin Peterson's avatar
Benjamin Peterson committed
814
            raise ValueError("unknown action %r" % self.action)
815 816 817 818

        return 1

# class Option
819 820


821 822 823 824 825
SUPPRESS_HELP = "SUPPRESS"+"HELP"
SUPPRESS_USAGE = "SUPPRESS"+"USAGE"

class Values:

826
    def __init__(self, defaults=None):
827 828 829 830
        if defaults:
            for (attr, val) in defaults.items():
                setattr(self, attr, val)

831 832 833 834
    def __str__(self):
        return str(self.__dict__)

    __repr__ = _repr
835

836
    def __eq__(self, other):
837
        if isinstance(other, Values):
838
            return self.__dict__ == other.__dict__
839
        elif isinstance(other, dict):
840
            return self.__dict__ == other
841
        else:
842
            return NotImplemented
843 844

    def _update_careful(self, dict):
845 846 847 848 849 850 851
        """
        Update the option values from an arbitrary dictionary, but only
        use keys from dict that already have a corresponding attribute
        in self.  Any keys in dict without a corresponding attribute
        are silently ignored.
        """
        for attr in dir(self):
852
            if attr in dict:
853 854 855 856
                dval = dict[attr]
                if dval is not None:
                    setattr(self, attr, dval)

857
    def _update_loose(self, dict):
858 859 860 861 862 863 864
        """
        Update the option values from an arbitrary dictionary,
        using all keys from the dictionary regardless of whether
        they have a corresponding attribute in self or not.
        """
        self.__dict__.update(dict)

865
    def _update(self, dict, mode):
866 867 868 869 870
        if mode == "careful":
            self._update_careful(dict)
        elif mode == "loose":
            self._update_loose(dict)
        else:
871
            raise ValueError("invalid update mode: %r" % mode)
872

873
    def read_module(self, modname, mode="careful"):
874 875 876 877
        __import__(modname)
        mod = sys.modules[modname]
        self._update(vars(mod), mode)

878
    def read_file(self, filename, mode="careful"):
879
        vars = {}
880
        exec(open(filename).read(), vars)
881 882
        self._update(vars, mode)

883
    def ensure_value(self, attr, value):
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
        if not hasattr(self, attr) or getattr(self, attr) is None:
            setattr(self, attr, value)
        return getattr(self, attr)


class OptionContainer:

    """
    Abstract base class.

    Class attributes:
      standard_option_list : [Option]
        list of standard options that will be accepted by all instances
        of this parser class (intended to be overridden by subclasses).

    Instance attributes:
      option_list : [Option]
        the list of Option objects contained by this OptionContainer
      _short_opt : { string : Option }
        dictionary mapping short option strings, eg. "-f" or "-X",
        to the Option instances that implement them.  If an Option
        has multiple short option strings, it will appears in this
        dictionary multiple times. [1]
      _long_opt : { string : Option }
        dictionary mapping long option strings, eg. "--file" or
        "--exclude", to the Option instances that implement them.
        Again, a given Option can occur multiple times in this
        dictionary. [1]
      defaults : { string : any }
        dictionary mapping option destination names to default
        values for each destination [1]

    [1] These mappings are common to (shared by) all components of the
        controlling OptionParser, where they are initially created.

    """

921
    def __init__(self, option_class, conflict_handler, description):
922 923 924 925 926 927 928 929 930 931
        # Initialize the option list and related data structures.
        # This method must be provided by subclasses, and it must
        # initialize at least the following instance attributes:
        # option_list, _short_opt, _long_opt, defaults.
        self._create_option_list()

        self.option_class = option_class
        self.set_conflict_handler(conflict_handler)
        self.set_description(description)

932
    def _create_option_mappings(self):
933 934 935 936 937 938 939 940
        # For use by OptionParser constructor -- create the master
        # option mappings used by this OptionParser and all
        # OptionGroups that it owns.
        self._short_opt = {}            # single letter -> Option instance
        self._long_opt = {}             # long option -> Option instance
        self.defaults = {}              # maps option dest -> default value


941
    def _share_option_mappings(self, parser):
942 943 944 945 946 947
        # For use by OptionGroup constructor -- use shared option
        # mappings from the OptionParser that owns this OptionGroup.
        self._short_opt = parser._short_opt
        self._long_opt = parser._long_opt
        self.defaults = parser.defaults

948
    def set_conflict_handler(self, handler):
949
        if handler not in ("error", "resolve"):
950
            raise ValueError("invalid conflict_resolution value %r" % handler)
951 952
        self.conflict_handler = handler

953
    def set_description(self, description):
954 955
        self.description = description

956 957 958
    def get_description(self):
        return self.description

959

960 961 962 963 964 965 966
    def destroy(self):
        """see OptionParser.destroy()."""
        del self._short_opt
        del self._long_opt
        del self.defaults


967 968
    # -- Option-adding methods -----------------------------------------

969
    def _check_conflict(self, option):
970 971
        conflict_opts = []
        for opt in option._short_opts:
972
            if opt in self._short_opt:
973 974
                conflict_opts.append((opt, self._short_opt[opt]))
        for opt in option._long_opts:
975
            if opt in self._long_opt:
976 977 978 979
                conflict_opts.append((opt, self._long_opt[opt]))

        if conflict_opts:
            handler = self.conflict_handler
980
            if handler == "error":
981 982 983 984
                raise OptionConflictError(
                    "conflicting option string(s): %s"
                    % ", ".join([co[0] for co in conflict_opts]),
                    option)
985
            elif handler == "resolve":
986 987 988 989 990 991 992 993 994 995
                for (opt, c_option) in conflict_opts:
                    if opt.startswith("--"):
                        c_option._long_opts.remove(opt)
                        del self._long_opt[opt]
                    else:
                        c_option._short_opts.remove(opt)
                        del self._short_opt[opt]
                    if not (c_option._short_opts or c_option._long_opts):
                        c_option.container.option_list.remove(c_option)

996
    def add_option(self, *args, **kwargs):
997 998 999
        """add_option(Option)
           add_option(opt_str, ..., kwarg=val, ...)
        """
1000
        if isinstance(args[0], str):
1001 1002 1003 1004
            option = self.option_class(*args, **kwargs)
        elif len(args) == 1 and not kwargs:
            option = args[0]
            if not isinstance(option, Option):
1005
                raise TypeError("not an Option instance: %r" % option)
1006
        else:
1007
            raise TypeError("invalid arguments")
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

        self._check_conflict(option)

        self.option_list.append(option)
        option.container = self
        for opt in option._short_opts:
            self._short_opt[opt] = option
        for opt in option._long_opts:
            self._long_opt[opt] = option

        if option.dest is not None:     # option has a dest, we need a default
            if option.default is not NO_DEFAULT:
                self.defaults[option.dest] = option.default
1021
            elif option.dest not in self.defaults:
1022 1023 1024 1025
                self.defaults[option.dest] = None

        return option

1026
    def add_options(self, option_list):
1027 1028 1029 1030 1031
        for option in option_list:
            self.add_option(option)

    # -- Option query/removal methods ----------------------------------

1032
    def get_option(self, opt_str):
1033 1034 1035
        return (self._short_opt.get(opt_str) or
                self._long_opt.get(opt_str))

1036
    def has_option(self, opt_str):
1037
        return (opt_str in self._short_opt or
Guido van Rossum's avatar
Guido van Rossum committed
1038
                opt_str in self._long_opt)
1039

1040
    def remove_option(self, opt_str):
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
        option = self._short_opt.get(opt_str)
        if option is None:
            option = self._long_opt.get(opt_str)
        if option is None:
            raise ValueError("no such option %r" % opt_str)

        for opt in option._short_opts:
            del self._short_opt[opt]
        for opt in option._long_opts:
            del self._long_opt[opt]
        option.container.option_list.remove(option)


    # -- Help-formatting methods ---------------------------------------

1056
    def format_option_help(self, formatter):
1057 1058 1059 1060 1061 1062 1063 1064
        if not self.option_list:
            return ""
        result = []
        for option in self.option_list:
            if not option.help is SUPPRESS_HELP:
                result.append(formatter.format_option(option))
        return "".join(result)

1065 1066
    def format_description(self, formatter):
        return formatter.format_description(self.get_description())
1067

1068 1069
    def format_help(self, formatter):
        result = []
1070
        if self.description:
1071 1072 1073 1074
            result.append(self.format_description(formatter))
        if self.option_list:
            result.append(self.format_option_help(formatter))
        return "\n".join(result)
1075 1076 1077 1078


class OptionGroup (OptionContainer):

1079
    def __init__(self, parser, title, description=None):
1080 1081 1082 1083 1084
        self.parser = parser
        OptionContainer.__init__(
            self, parser.option_class, parser.conflict_handler, description)
        self.title = title

1085
    def _create_option_list(self):
1086 1087 1088
        self.option_list = []
        self._share_option_mappings(self.parser)

1089
    def set_title(self, title):
1090 1091
        self.title = title

1092 1093 1094 1095 1096
    def destroy(self):
        """see OptionParser.destroy()."""
        OptionContainer.destroy(self)
        del self.option_list

1097 1098
    # -- Help-formatting methods ---------------------------------------

1099
    def format_help(self, formatter):
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
        result = formatter.format_heading(self.title)
        formatter.indent()
        result += OptionContainer.format_help(self, formatter)
        formatter.dedent()
        return result


class OptionParser (OptionContainer):

    """
    Class attributes:
      standard_option_list : [Option]
        list of standard options that will be accepted by all instances
        of this parser class (intended to be overridden by subclasses).

    Instance attributes:
      usage : string
        a usage string for your program.  Before it is displayed
        to the user, "%prog" will be expanded to the name of
1119 1120 1121 1122
        your program (self.prog or os.path.basename(sys.argv[0])).
      prog : string
        the name of the current program (to override
        os.path.basename(sys.argv[0])).
1123 1124 1125 1126 1127
      description : string
        A paragraph of text giving a brief overview of your program.
        optparse reformats this paragraph to fit the current terminal
        width and prints it when the user requests help (after usage,
        but before the list of options).
1128 1129
      epilog : string
        paragraph of help text to print after option help
1130

1131 1132 1133 1134 1135 1136
      option_groups : [OptionGroup]
        list of option groups in this parser (option groups are
        irrelevant for parsing the command-line, but very useful
        for generating help)

      allow_interspersed_args : bool = true
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
        if true, positional arguments may be interspersed with options.
        Assuming -a and -b each take a single argument, the command-line
          -ablah foo bar -bboo baz
        will be interpreted the same as
          -ablah -bboo -- foo bar baz
        If this flag were false, that command line would be interpreted as
          -ablah -- foo bar -bboo baz
        -- ie. we stop processing options as soon as we see the first
        non-option argument.  (This is the tradition followed by
        Python's getopt module, Perl's Getopt::Std, and other argument-
        parsing libraries, but it is generally annoying to users.)

1149 1150 1151 1152 1153 1154 1155 1156
      process_default_values : bool = true
        if true, option default values are processed similarly to option
        values from the command line: that is, they are passed to the
        type-checking function for the option's type (as long as the
        default value is a string).  (This really only matters if you
        have defined custom types; see SF bug #955889.)  Set it to false
        to restore the behaviour of Optik 1.4.1 and earlier.

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
      rargs : [string]
        the argument list currently being parsed.  Only set when
        parse_args() is active, and continually trimmed down as
        we consume arguments.  Mainly there for the benefit of
        callback options.
      largs : [string]
        the list of leftover arguments that we have skipped while
        parsing options.  If allow_interspersed_args is false, this
        list is always empty.
      values : Values
        the set of option values currently being accumulated.  Only
        set when parse_args() is active.  Also mainly for callbacks.

    Because of the 'rargs', 'largs', and 'values' attributes,
    OptionParser is not thread-safe.  If, for some perverse reason, you
    need to parse command-line arguments simultaneously in different
    threads, use different OptionParser instances.

    """

    standard_option_list = []

1179 1180 1181 1182 1183 1184 1185 1186 1187
    def __init__(self,
                 usage=None,
                 option_list=None,
                 option_class=Option,
                 version=None,
                 conflict_handler="error",
                 description=None,
                 formatter=None,
                 add_help_option=True,
1188 1189
                 prog=None,
                 epilog=None):
1190 1191 1192
        OptionContainer.__init__(
            self, option_class, conflict_handler, description)
        self.set_usage(usage)
1193
        self.prog = prog
1194
        self.version = version
1195 1196
        self.allow_interspersed_args = True
        self.process_default_values = True
1197 1198 1199
        if formatter is None:
            formatter = IndentedHelpFormatter()
        self.formatter = formatter
1200
        self.formatter.set_parser(self)
1201
        self.epilog = epilog
1202 1203 1204

        # Populate the option list; initial sources are the
        # standard_option_list class attribute, the 'option_list'
1205 1206
        # argument, and (if applicable) the _add_version_option() and
        # _add_help_option() methods.
1207 1208 1209 1210 1211
        self._populate_option_list(option_list,
                                   add_help=add_help_option)

        self._init_parsing_state()

1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227

    def destroy(self):
        """
        Declare that you are done with this OptionParser.  This cleans up
        reference cycles so the OptionParser (and all objects referenced by
        it) can be garbage-collected promptly.  After calling destroy(), the
        OptionParser is unusable.
        """
        OptionContainer.destroy(self)
        for group in self.option_groups:
            group.destroy()
        del self.option_list
        del self.option_groups
        del self.formatter


1228 1229 1230
    # -- Private methods -----------------------------------------------
    # (used by our or OptionContainer's constructor)

1231
    def _create_option_list(self):
1232 1233 1234 1235
        self.option_list = []
        self.option_groups = []
        self._create_option_mappings()

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    def _add_help_option(self):
        self.add_option("-h", "--help",
                        action="help",
                        help=_("show this help message and exit"))

    def _add_version_option(self):
        self.add_option("--version",
                        action="version",
                        help=_("show program's version number and exit"))

    def _populate_option_list(self, option_list, add_help=True):
1247 1248 1249 1250 1251
        if self.standard_option_list:
            self.add_options(self.standard_option_list)
        if option_list:
            self.add_options(option_list)
        if self.version:
1252
            self._add_version_option()
1253
        if add_help:
1254
            self._add_help_option()
1255

1256
    def _init_parsing_state(self):
1257 1258 1259 1260 1261 1262 1263 1264
        # These are set in parse_args() for the convenience of callbacks.
        self.rargs = None
        self.largs = None
        self.values = None


    # -- Simple modifier methods ---------------------------------------

1265
    def set_usage(self, usage):
1266
        if usage is None:
1267
            self.usage = _("%prog [options]")
1268 1269
        elif usage is SUPPRESS_USAGE:
            self.usage = None
1270
        # For backwards compatibility with Optik 1.3 and earlier.
1271
        elif usage.lower().startswith("usage: "):
1272 1273 1274 1275
            self.usage = usage[7:]
        else:
            self.usage = usage

1276
    def enable_interspersed_args(self):
Benjamin Peterson's avatar
Benjamin Peterson committed
1277 1278 1279 1280 1281
        """Set parsing to not stop on the first non-option, allowing
        interspersing switches with command arguments. This is the
        default behavior. See also disable_interspersed_args() and the
        class documentation description of the attribute
        allow_interspersed_args."""
1282 1283 1284
        self.allow_interspersed_args = True

    def disable_interspersed_args(self):
Benjamin Peterson's avatar
Benjamin Peterson committed
1285 1286 1287 1288 1289
        """Set parsing to stop on the first non-option. Use this if
        you have a command processor which runs another command that
        has options of its own and you want to make sure these options
        don't get confused.
        """
1290
        self.allow_interspersed_args = False
1291

1292 1293
    def set_process_default_values(self, process):
        self.process_default_values = process
1294

1295
    def set_default(self, dest, value):
1296 1297
        self.defaults[dest] = value

1298
    def set_defaults(self, **kwargs):
1299 1300
        self.defaults.update(kwargs)

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
    def _get_all_options(self):
        options = self.option_list[:]
        for group in self.option_groups:
            options.extend(group.option_list)
        return options

    def get_default_values(self):
        if not self.process_default_values:
            # Old, pre-Optik 1.5 behaviour.
            return Values(self.defaults)

        defaults = self.defaults.copy()
        for option in self._get_all_options():
            default = defaults.get(option.dest)
1315
            if isinstance(default, str):
1316 1317 1318 1319
                opt_str = option.get_opt_string()
                defaults[option.dest] = option.check_value(opt_str, default)

        return Values(defaults)
1320 1321 1322 1323


    # -- OptionGroup methods -------------------------------------------

1324
    def add_option_group(self, *args, **kwargs):
1325
        # XXX lots of overlap with OptionContainer.add_option()
1326
        if isinstance(args[0], str):
1327 1328 1329 1330
            group = OptionGroup(self, *args, **kwargs)
        elif len(args) == 1 and not kwargs:
            group = args[0]
            if not isinstance(group, OptionGroup):
1331
                raise TypeError("not an OptionGroup instance: %r" % group)
1332
            if group.parser is not self:
1333
                raise ValueError("invalid OptionGroup (wrong parser)")
1334
        else:
1335
            raise TypeError("invalid arguments")
1336 1337 1338 1339

        self.option_groups.append(group)
        return group

1340
    def get_option_group(self, opt_str):
1341 1342 1343 1344 1345 1346 1347 1348 1349
        option = (self._short_opt.get(opt_str) or
                  self._long_opt.get(opt_str))
        if option and option.container is not self:
            return option.container
        return None


    # -- Option-parsing methods ----------------------------------------

1350
    def _get_args(self, args):
1351 1352 1353 1354 1355
        if args is None:
            return sys.argv[1:]
        else:
            return args[:]              # don't modify caller's list

1356
    def parse_args(self, args=None, values=None):
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
        """
        parse_args(args : [string] = sys.argv[1:],
                   values : Values = None)
        -> (values : Values, args : [string])

        Parse the command-line options found in 'args' (default:
        sys.argv[1:]).  Any errors result in a call to 'error()', which
        by default prints the usage message to stderr and calls
        sys.exit() with an error message.  On success returns a pair
        (values, args) where 'values' is an Values instance (with all
        your option values) and 'args' is the list of arguments left
        over after parsing options.
        """
        rargs = self._get_args(args)
        if values is None:
            values = self.get_default_values()

        # Store the halves of the argument list as attributes for the
        # convenience of callbacks:
        #   rargs
        #     the rest of the command-line (the "r" stands for
        #     "remaining" or "right-hand")
        #   largs
        #     the leftover arguments -- ie. what's left after removing
        #     options and their arguments (the "l" stands for "leftover"
        #     or "left-hand")
        self.rargs = rargs
        self.largs = largs = []
        self.values = values

        try:
            stop = self._process_args(largs, rargs, values)
1389
        except (BadOptionError, OptionValueError) as err:
1390
            self.error(str(err))
1391 1392 1393 1394

        args = largs + rargs
        return self.check_values(values, args)

1395
    def check_values(self, values, args):
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
        """
        check_values(values : Values, args : [string])
        -> (values : Values, args : [string])

        Check that the supplied option values and leftover arguments are
        valid.  Returns the option values and leftover arguments
        (possibly adjusted, possibly completely new -- whatever you
        like).  Default implementation just returns the passed-in
        values; subclasses may override as desired.
        """
        return (values, args)

1408
    def _process_args(self, largs, rargs, values):
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
        """_process_args(largs : [string],
                         rargs : [string],
                         values : Values)

        Process command-line arguments and populate 'values', consuming
        options and arguments from 'rargs'.  If 'allow_interspersed_args' is
        false, stop at the first non-option argument.  If true, accumulate any
        interspersed non-option arguments in 'largs'.
        """
        while rargs:
            arg = rargs[0]
            # We handle bare "--" explicitly, and bare "-" is handled by the
            # standard arg handler since the short arg case ensures that the
            # len of the opt string is greater than 1.
            if arg == "--":
                del rargs[0]
                return
            elif arg[0:2] == "--":
                # process a single long option (possibly with value(s))
                self._process_long_opt(rargs, values)
            elif arg[:1] == "-" and len(arg) > 1:
                # process a cluster of short options (possibly with
                # value(s) for the last one only)
                self._process_short_opts(rargs, values)
            elif self.allow_interspersed_args:
                largs.append(arg)
                del rargs[0]
            else:
                return                  # stop now, leave this arg in rargs

        # Say this is the original argument list:
        # [arg0, arg1, ..., arg(i-1), arg(i), arg(i+1), ..., arg(N-1)]
        #                            ^
        # (we are about to process arg(i)).
        #
        # Then rargs is [arg(i), ..., arg(N-1)] and largs is a *subset* of
        # [arg0, ..., arg(i-1)] (any options and their arguments will have
        # been removed from largs).
        #
        # The while loop will usually consume 1 or more arguments per pass.
        # If it consumes 1 (eg. arg is an option that takes no arguments),
        # then after _process_arg() is done the situation is:
        #
        #   largs = subset of [arg0, ..., arg(i)]
        #   rargs = [arg(i+1), ..., arg(N-1)]
        #
        # If allow_interspersed_args is false, largs will always be
        # *empty* -- still a subset of [arg0, ..., arg(i-1)], but
        # not a very interesting subset!

1459
    def _match_long_opt(self, opt):
1460 1461 1462 1463 1464 1465 1466 1467
        """_match_long_opt(opt : string) -> string

        Determine which long option string 'opt' matches, ie. which one
        it is an unambiguous abbrevation for.  Raises BadOptionError if
        'opt' doesn't unambiguously match any long option string.
        """
        return _match_abbrev(opt, self._long_opt)

1468
    def _process_long_opt(self, rargs, values):
1469 1470 1471 1472 1473 1474 1475
        arg = rargs.pop(0)

        # Value explicitly attached to arg?  Pretend it's the next
        # argument.
        if "=" in arg:
            (opt, next_arg) = arg.split("=", 1)
            rargs.insert(0, next_arg)
1476
            had_explicit_value = True
1477 1478
        else:
            opt = arg
1479
            had_explicit_value = False
1480 1481 1482 1483 1484 1485 1486

        opt = self._match_long_opt(opt)
        option = self._long_opt[opt]
        if option.takes_value():
            nargs = option.nargs
            if len(rargs) < nargs:
                if nargs == 1:
1487
                    self.error(_("%s option requires an argument") % opt)
1488
                else:
1489
                    self.error(_("%s option requires %d arguments")
1490 1491 1492 1493 1494 1495 1496 1497
                               % (opt, nargs))
            elif nargs == 1:
                value = rargs.pop(0)
            else:
                value = tuple(rargs[0:nargs])
                del rargs[0:nargs]

        elif had_explicit_value:
1498
            self.error(_("%s option does not take a value") % opt)
1499 1500 1501 1502 1503 1504

        else:
            value = None

        option.process(opt, value, values, self)

1505
    def _process_short_opts(self, rargs, values):
1506
        arg = rargs.pop(0)
1507
        stop = False
1508 1509 1510 1511 1512 1513 1514
        i = 1
        for ch in arg[1:]:
            opt = "-" + ch
            option = self._short_opt.get(opt)
            i += 1                      # we have consumed a character

            if not option:
1515
                raise BadOptionError(opt)
1516 1517 1518 1519 1520
            if option.takes_value():
                # Any characters left in arg?  Pretend they're the
                # next arg, and stop consuming characters of arg.
                if i < len(arg):
                    rargs.insert(0, arg[i:])
1521
                    stop = True
1522 1523 1524 1525

                nargs = option.nargs
                if len(rargs) < nargs:
                    if nargs == 1:
1526
                        self.error(_("%s option requires an argument") % opt)
1527
                    else:
1528
                        self.error(_("%s option requires %d arguments")
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
                                   % (opt, nargs))
                elif nargs == 1:
                    value = rargs.pop(0)
                else:
                    value = tuple(rargs[0:nargs])
                    del rargs[0:nargs]

            else:                       # option doesn't take a value
                value = None

            option.process(opt, value, values, self)

            if stop:
                break


    # -- Feedback methods ----------------------------------------------

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
    def get_prog_name(self):
        if self.prog is None:
            return os.path.basename(sys.argv[0])
        else:
            return self.prog

    def expand_prog_name(self, s):
        return s.replace("%prog", self.get_prog_name())

    def get_description(self):
        return self.expand_prog_name(self.description)

1559 1560 1561 1562 1563
    def exit(self, status=0, msg=None):
        if msg:
            sys.stderr.write(msg)
        sys.exit(status)

1564
    def error(self, msg):
1565 1566 1567 1568 1569 1570 1571
        """error(msg : string)

        Print a usage message incorporating 'msg' to stderr and exit.
        If you override this in a subclass, it should not return -- it
        should either exit or raise an exception.
        """
        self.print_usage(sys.stderr)
1572
        self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
1573

1574
    def get_usage(self):
1575 1576
        if self.usage:
            return self.formatter.format_usage(
1577
                self.expand_prog_name(self.usage))
1578 1579 1580
        else:
            return ""

1581
    def print_usage(self, file=None):
1582 1583 1584
        """print_usage(file : file = stdout)

        Print the usage message for the current program (self.usage) to
1585
        'file' (default stdout).  Any occurrence of the string "%prog" in
1586 1587 1588 1589 1590
        self.usage is replaced with the name of the current program
        (basename of sys.argv[0]).  Does nothing if self.usage is empty
        or not defined.
        """
        if self.usage:
1591
            print(self.get_usage(), file=file)
1592

1593
    def get_version(self):
1594
        if self.version:
1595
            return self.expand_prog_name(self.version)
1596 1597 1598
        else:
            return ""

1599
    def print_version(self, file=None):
1600 1601 1602
        """print_version(file : file = stdout)

        Print the version message for this program (self.version) to
1603
        'file' (default stdout).  As with print_usage(), any occurrence
1604 1605 1606 1607
        of "%prog" in self.version is replaced by the current program's
        name.  Does nothing if self.version is empty or undefined.
        """
        if self.version:
1608
            print(self.get_version(), file=file)
1609

1610
    def format_option_help(self, formatter=None):
1611 1612 1613 1614
        if formatter is None:
            formatter = self.formatter
        formatter.store_option_strings(self)
        result = []
1615
        result.append(formatter.format_heading(_("Options")))
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
        formatter.indent()
        if self.option_list:
            result.append(OptionContainer.format_option_help(self, formatter))
            result.append("\n")
        for group in self.option_groups:
            result.append(group.format_help(formatter))
            result.append("\n")
        formatter.dedent()
        # Drop the last "\n", or the header if no options or option groups:
        return "".join(result[:-1])

1627 1628 1629
    def format_epilog(self, formatter):
        return formatter.format_epilog(self.epilog)

1630
    def format_help(self, formatter=None):
1631 1632 1633 1634 1635 1636 1637 1638
        if formatter is None:
            formatter = self.formatter
        result = []
        if self.usage:
            result.append(self.get_usage() + "\n")
        if self.description:
            result.append(self.format_description(formatter) + "\n")
        result.append(self.format_option_help(formatter))
1639
        result.append(self.format_epilog(formatter))
1640 1641
        return "".join(result)

1642
    def print_help(self, file=None):
1643 1644 1645 1646 1647 1648 1649
        """print_help(file : file = stdout)

        Print an extended help message, listing all options and any
        help text provided with them, to 'file' (default stdout).
        """
        if file is None:
            file = sys.stdout
1650
        file.write(self.format_help())
1651 1652 1653 1654

# class OptionParser


1655
def _match_abbrev(s, wordmap):
1656 1657 1658 1659 1660 1661 1662
    """_match_abbrev(s : string, wordmap : {string : Option}) -> string

    Return the string key in 'wordmap' for which 's' is an unambiguous
    abbreviation.  If 's' is found to be ambiguous or doesn't match any of
    'words', raise BadOptionError.
    """
    # Is there an exact match?
1663
    if s in wordmap:
1664 1665 1666 1667 1668 1669 1670 1671 1672
        return s
    else:
        # Isolate all words with s as a prefix.
        possibilities = [word for word in wordmap.keys()
                         if word.startswith(s)]
        # No exact match, so there had better be just one possibility.
        if len(possibilities) == 1:
            return possibilities[0]
        elif not possibilities:
1673
            raise BadOptionError(s)
1674 1675
        else:
            # More than one possible completion: ambiguous prefix.
1676
            possibilities.sort()
1677
            raise AmbiguousOptionError(s, possibilities)
1678 1679 1680 1681 1682 1683 1684


# Some day, there might be many Option classes.  As of Optik 1.3, the
# preferred way to instantiate Options is indirectly, via make_option(),
# which will become a factory function when there are many Option
# classes.
make_option = Option