PageRenderTime 121ms CodeModel.GetById 39ms app.highlight 41ms RepoModel.GetById 1ms app.codeStats 8ms

/Doc/library/optparse.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 1901 lines | 1329 code | 572 blank | 0 comment | 0 complexity | a6c36a60dbbd380640ea5143f1d14569 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1:mod:`optparse` --- More powerful command line option parser
   2============================================================
   3
   4.. module:: optparse
   5   :synopsis: More convenient, flexible, and powerful command-line parsing library.
   6.. moduleauthor:: Greg Ward <gward@python.net>
   7
   8
   9.. versionadded:: 2.3
  10
  11.. sectionauthor:: Greg Ward <gward@python.net>
  12
  13
  14:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
  15command-line options than the old :mod:`getopt` module.  :mod:`optparse` uses a
  16more declarative style of command-line parsing: you create an instance of
  17:class:`OptionParser`, populate it with options, and parse the command
  18line. :mod:`optparse` allows users to specify options in the conventional
  19GNU/POSIX syntax, and additionally generates usage and help messages for you.
  20
  21Here's an example of using :mod:`optparse` in a simple script::
  22
  23   from optparse import OptionParser
  24   [...]
  25   parser = OptionParser()
  26   parser.add_option("-f", "--file", dest="filename",
  27                     help="write report to FILE", metavar="FILE")
  28   parser.add_option("-q", "--quiet",
  29                     action="store_false", dest="verbose", default=True,
  30                     help="don't print status messages to stdout")
  31
  32   (options, args) = parser.parse_args()
  33
  34With these few lines of code, users of your script can now do the "usual thing"
  35on the command-line, for example::
  36
  37   <yourscript> --file=outfile -q
  38
  39As it parses the command line, :mod:`optparse` sets attributes of the
  40``options`` object returned by :meth:`parse_args` based on user-supplied
  41command-line values.  When :meth:`parse_args` returns from parsing this command
  42line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
  43``False``.  :mod:`optparse` supports both long and short options, allows short
  44options to be merged together, and allows options to be associated with their
  45arguments in a variety of ways.  Thus, the following command lines are all
  46equivalent to the above example::
  47
  48   <yourscript> -f outfile --quiet
  49   <yourscript> --quiet --file outfile
  50   <yourscript> -q -foutfile
  51   <yourscript> -qfoutfile
  52
  53Additionally, users can run one of  ::
  54
  55   <yourscript> -h
  56   <yourscript> --help
  57
  58and :mod:`optparse` will print out a brief summary of your script's options::
  59
  60   usage: <yourscript> [options]
  61
  62   options:
  63     -h, --help            show this help message and exit
  64     -f FILE, --file=FILE  write report to FILE
  65     -q, --quiet           don't print status messages to stdout
  66
  67where the value of *yourscript* is determined at runtime (normally from
  68``sys.argv[0]``).
  69
  70
  71.. _optparse-background:
  72
  73Background
  74----------
  75
  76:mod:`optparse` was explicitly designed to encourage the creation of programs
  77with straightforward, conventional command-line interfaces.  To that end, it
  78supports only the most common command-line syntax and semantics conventionally
  79used under Unix.  If you are unfamiliar with these conventions, read this
  80section to acquaint yourself with them.
  81
  82
  83.. _optparse-terminology:
  84
  85Terminology
  86^^^^^^^^^^^
  87
  88argument
  89   a string entered on the command-line, and passed by the shell to ``execl()``
  90   or ``execv()``.  In Python, arguments are elements of ``sys.argv[1:]``
  91   (``sys.argv[0]`` is the name of the program being executed).  Unix shells
  92   also use the term "word".
  93
  94   It is occasionally desirable to substitute an argument list other than
  95   ``sys.argv[1:]``, so you should read "argument" as "an element of
  96   ``sys.argv[1:]``, or of some other list provided as a substitute for
  97   ``sys.argv[1:]``".
  98
  99option
 100   an argument used to supply extra information to guide or customize the
 101   execution of a program.  There are many different syntaxes for options; the
 102   traditional Unix syntax is a hyphen ("-") followed by a single letter,
 103   e.g. ``"-x"`` or ``"-F"``.  Also, traditional Unix syntax allows multiple
 104   options to be merged into a single argument, e.g.  ``"-x -F"`` is equivalent
 105   to ``"-xF"``.  The GNU project introduced ``"--"`` followed by a series of
 106   hyphen-separated words, e.g.  ``"--file"`` or ``"--dry-run"``.  These are the
 107   only two option syntaxes provided by :mod:`optparse`.
 108
 109   Some other option syntaxes that the world has seen include:
 110
 111   * a hyphen followed by a few letters, e.g. ``"-pf"`` (this is *not* the same
 112     as multiple options merged into a single argument)
 113
 114   * a hyphen followed by a whole word, e.g. ``"-file"`` (this is technically
 115     equivalent to the previous syntax, but they aren't usually seen in the same
 116     program)
 117
 118   * a plus sign followed by a single letter, or a few letters, or a word, e.g.
 119     ``"+f"``, ``"+rgb"``
 120
 121   * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
 122     ``"/file"``
 123
 124   These option syntaxes are not supported by :mod:`optparse`, and they never
 125   will be.  This is deliberate: the first three are non-standard on any
 126   environment, and the last only makes sense if you're exclusively targeting
 127   VMS, MS-DOS, and/or Windows.
 128
 129option argument
 130   an argument that follows an option, is closely associated with that option,
 131   and is consumed from the argument list when that option is. With
 132   :mod:`optparse`, option arguments may either be in a separate argument from
 133   their option::
 134
 135      -f foo
 136      --file foo
 137
 138   or included in the same argument::
 139
 140      -ffoo
 141      --file=foo
 142
 143   Typically, a given option either takes an argument or it doesn't. Lots of
 144   people want an "optional option arguments" feature, meaning that some options
 145   will take an argument if they see it, and won't if they don't.  This is
 146   somewhat controversial, because it makes parsing ambiguous: if ``"-a"`` takes
 147   an optional argument and ``"-b"`` is another option entirely, how do we
 148   interpret ``"-ab"``?  Because of this ambiguity, :mod:`optparse` does not
 149   support this feature.
 150
 151positional argument
 152   something leftover in the argument list after options have been parsed, i.e.
 153   after options and their arguments have been parsed and removed from the
 154   argument list.
 155
 156required option
 157   an option that must be supplied on the command-line; note that the phrase
 158   "required option" is self-contradictory in English.  :mod:`optparse` doesn't
 159   prevent you from implementing required options, but doesn't give you much
 160   help at it either.  See ``examples/required_1.py`` and
 161   ``examples/required_2.py`` in the :mod:`optparse` source distribution for two
 162   ways to implement required options with :mod:`optparse`.
 163
 164For example, consider this hypothetical command-line::
 165
 166   prog -v --report /tmp/report.txt foo bar
 167
 168``"-v"`` and ``"--report"`` are both options.  Assuming that :option:`--report`
 169takes one argument, ``"/tmp/report.txt"`` is an option argument.  ``"foo"`` and
 170``"bar"`` are positional arguments.
 171
 172
 173.. _optparse-what-options-for:
 174
 175What are options for?
 176^^^^^^^^^^^^^^^^^^^^^
 177
 178Options are used to provide extra information to tune or customize the execution
 179of a program.  In case it wasn't clear, options are usually *optional*.  A
 180program should be able to run just fine with no options whatsoever.  (Pick a
 181random program from the Unix or GNU toolsets.  Can it run without any options at
 182all and still make sense?  The main exceptions are ``find``, ``tar``, and
 183``dd``\ ---all of which are mutant oddballs that have been rightly criticized
 184for their non-standard syntax and confusing interfaces.)
 185
 186Lots of people want their programs to have "required options".  Think about it.
 187If it's required, then it's *not optional*!  If there is a piece of information
 188that your program absolutely requires in order to run successfully, that's what
 189positional arguments are for.
 190
 191As an example of good command-line interface design, consider the humble ``cp``
 192utility, for copying files.  It doesn't make much sense to try to copy files
 193without supplying a destination and at least one source. Hence, ``cp`` fails if
 194you run it with no arguments.  However, it has a flexible, useful syntax that
 195does not require any options at all::
 196
 197   cp SOURCE DEST
 198   cp SOURCE ... DEST-DIR
 199
 200You can get pretty far with just that.  Most ``cp`` implementations provide a
 201bunch of options to tweak exactly how the files are copied: you can preserve
 202mode and modification time, avoid following symlinks, ask before clobbering
 203existing files, etc.  But none of this distracts from the core mission of
 204``cp``, which is to copy either one file to another, or several files to another
 205directory.
 206
 207
 208.. _optparse-what-positional-arguments-for:
 209
 210What are positional arguments for?
 211^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 212
 213Positional arguments are for those pieces of information that your program
 214absolutely, positively requires to run.
 215
 216A good user interface should have as few absolute requirements as possible.  If
 217your program requires 17 distinct pieces of information in order to run
 218successfully, it doesn't much matter *how* you get that information from the
 219user---most people will give up and walk away before they successfully run the
 220program.  This applies whether the user interface is a command-line, a
 221configuration file, or a GUI: if you make that many demands on your users, most
 222of them will simply give up.
 223
 224In short, try to minimize the amount of information that users are absolutely
 225required to supply---use sensible defaults whenever possible.  Of course, you
 226also want to make your programs reasonably flexible.  That's what options are
 227for.  Again, it doesn't matter if they are entries in a config file, widgets in
 228the "Preferences" dialog of a GUI, or command-line options---the more options
 229you implement, the more flexible your program is, and the more complicated its
 230implementation becomes.  Too much flexibility has drawbacks as well, of course;
 231too many options can overwhelm users and make your code much harder to maintain.
 232
 233
 234.. _optparse-tutorial:
 235
 236Tutorial
 237--------
 238
 239While :mod:`optparse` is quite flexible and powerful, it's also straightforward
 240to use in most cases.  This section covers the code patterns that are common to
 241any :mod:`optparse`\ -based program.
 242
 243First, you need to import the OptionParser class; then, early in the main
 244program, create an OptionParser instance::
 245
 246   from optparse import OptionParser
 247   [...]
 248   parser = OptionParser()
 249
 250Then you can start defining options.  The basic syntax is::
 251
 252   parser.add_option(opt_str, ...,
 253                     attr=value, ...)
 254
 255Each option has one or more option strings, such as ``"-f"`` or ``"--file"``,
 256and several option attributes that tell :mod:`optparse` what to expect and what
 257to do when it encounters that option on the command line.
 258
 259Typically, each option will have one short option string and one long option
 260string, e.g.::
 261
 262   parser.add_option("-f", "--file", ...)
 263
 264You're free to define as many short option strings and as many long option
 265strings as you like (including zero), as long as there is at least one option
 266string overall.
 267
 268The option strings passed to :meth:`add_option` are effectively labels for the
 269option defined by that call.  For brevity, we will frequently refer to
 270*encountering an option* on the command line; in reality, :mod:`optparse`
 271encounters *option strings* and looks up options from them.
 272
 273Once all of your options are defined, instruct :mod:`optparse` to parse your
 274program's command line::
 275
 276   (options, args) = parser.parse_args()
 277
 278(If you like, you can pass a custom argument list to :meth:`parse_args`, but
 279that's rarely necessary: by default it uses ``sys.argv[1:]``.)
 280
 281:meth:`parse_args` returns two values:
 282
 283* ``options``, an object containing values for all of your options---e.g. if
 284  ``"--file"`` takes a single string argument, then ``options.file`` will be the
 285  filename supplied by the user, or ``None`` if the user did not supply that
 286  option
 287
 288* ``args``, the list of positional arguments leftover after parsing options
 289
 290This tutorial section only covers the four most important option attributes:
 291:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
 292(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
 293most fundamental.
 294
 295
 296.. _optparse-understanding-option-actions:
 297
 298Understanding option actions
 299^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 300
 301Actions tell :mod:`optparse` what to do when it encounters an option on the
 302command line.  There is a fixed set of actions hard-coded into :mod:`optparse`;
 303adding new actions is an advanced topic covered in section
 304:ref:`optparse-extending-optparse`.  Most actions tell :mod:`optparse` to store
 305a value in some variable---for example, take a string from the command line and
 306store it in an attribute of ``options``.
 307
 308If you don't specify an option action, :mod:`optparse` defaults to ``store``.
 309
 310
 311.. _optparse-store-action:
 312
 313The store action
 314^^^^^^^^^^^^^^^^
 315
 316The most common option action is ``store``, which tells :mod:`optparse` to take
 317the next argument (or the remainder of the current argument), ensure that it is
 318of the correct type, and store it to your chosen destination.
 319
 320For example::
 321
 322   parser.add_option("-f", "--file",
 323                     action="store", type="string", dest="filename")
 324
 325Now let's make up a fake command line and ask :mod:`optparse` to parse it::
 326
 327   args = ["-f", "foo.txt"]
 328   (options, args) = parser.parse_args(args)
 329
 330When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
 331argument, ``"foo.txt"``, and stores it in ``options.filename``.  So, after this
 332call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
 333
 334Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
 335Here's an option that expects an integer argument::
 336
 337   parser.add_option("-n", type="int", dest="num")
 338
 339Note that this option has no long option string, which is perfectly acceptable.
 340Also, there's no explicit action, since the default is ``store``.
 341
 342Let's parse another fake command-line.  This time, we'll jam the option argument
 343right up against the option: since ``"-n42"`` (one argument) is equivalent to
 344``"-n 42"`` (two arguments), the code ::
 345
 346   (options, args) = parser.parse_args(["-n42"])
 347   print options.num
 348
 349will print ``"42"``.
 350
 351If you don't specify a type, :mod:`optparse` assumes ``string``.  Combined with
 352the fact that the default action is ``store``, that means our first example can
 353be a lot shorter::
 354
 355   parser.add_option("-f", "--file", dest="filename")
 356
 357If you don't supply a destination, :mod:`optparse` figures out a sensible
 358default from the option strings: if the first long option string is
 359``"--foo-bar"``, then the default destination is ``foo_bar``.  If there are no
 360long option strings, :mod:`optparse` looks at the first short option string: the
 361default destination for ``"-f"`` is ``f``.
 362
 363:mod:`optparse` also includes built-in ``long`` and ``complex`` types.  Adding
 364types is covered in section :ref:`optparse-extending-optparse`.
 365
 366
 367.. _optparse-handling-boolean-options:
 368
 369Handling boolean (flag) options
 370^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 371
 372Flag options---set a variable to true or false when a particular option is seen
 373---are quite common.  :mod:`optparse` supports them with two separate actions,
 374``store_true`` and ``store_false``.  For example, you might have a ``verbose``
 375flag that is turned on with ``"-v"`` and off with ``"-q"``::
 376
 377   parser.add_option("-v", action="store_true", dest="verbose")
 378   parser.add_option("-q", action="store_false", dest="verbose")
 379
 380Here we have two different options with the same destination, which is perfectly
 381OK.  (It just means you have to be a bit careful when setting default values---
 382see below.)
 383
 384When :mod:`optparse` encounters ``"-v"`` on the command line, it sets
 385``options.verbose`` to ``True``; when it encounters ``"-q"``,
 386``options.verbose`` is set to ``False``.
 387
 388
 389.. _optparse-other-actions:
 390
 391Other actions
 392^^^^^^^^^^^^^
 393
 394Some other actions supported by :mod:`optparse` are:
 395
 396``"store_const"``
 397   store a constant value
 398
 399``"append"``
 400   append this option's argument to a list
 401
 402``"count"``
 403   increment a counter by one
 404
 405``"callback"``
 406   call a specified function
 407
 408These are covered in section :ref:`optparse-reference-guide`, Reference Guide
 409and section :ref:`optparse-option-callbacks`.
 410
 411
 412.. _optparse-default-values:
 413
 414Default values
 415^^^^^^^^^^^^^^
 416
 417All of the above examples involve setting some variable (the "destination") when
 418certain command-line options are seen.  What happens if those options are never
 419seen?  Since we didn't supply any defaults, they are all set to ``None``.  This
 420is usually fine, but sometimes you want more control.  :mod:`optparse` lets you
 421supply a default value for each destination, which is assigned before the
 422command line is parsed.
 423
 424First, consider the verbose/quiet example.  If we want :mod:`optparse` to set
 425``verbose`` to ``True`` unless ``"-q"`` is seen, then we can do this::
 426
 427   parser.add_option("-v", action="store_true", dest="verbose", default=True)
 428   parser.add_option("-q", action="store_false", dest="verbose")
 429
 430Since default values apply to the *destination* rather than to any particular
 431option, and these two options happen to have the same destination, this is
 432exactly equivalent::
 433
 434   parser.add_option("-v", action="store_true", dest="verbose")
 435   parser.add_option("-q", action="store_false", dest="verbose", default=True)
 436
 437Consider this::
 438
 439   parser.add_option("-v", action="store_true", dest="verbose", default=False)
 440   parser.add_option("-q", action="store_false", dest="verbose", default=True)
 441
 442Again, the default value for ``verbose`` will be ``True``: the last default
 443value supplied for any particular destination is the one that counts.
 444
 445A clearer way to specify default values is the :meth:`set_defaults` method of
 446OptionParser, which you can call at any time before calling :meth:`parse_args`::
 447
 448   parser.set_defaults(verbose=True)
 449   parser.add_option(...)
 450   (options, args) = parser.parse_args()
 451
 452As before, the last value specified for a given option destination is the one
 453that counts.  For clarity, try to use one method or the other of setting default
 454values, not both.
 455
 456
 457.. _optparse-generating-help:
 458
 459Generating help
 460^^^^^^^^^^^^^^^
 461
 462:mod:`optparse`'s ability to generate help and usage text automatically is
 463useful for creating user-friendly command-line interfaces.  All you have to do
 464is supply a :attr:`~Option.help` value for each option, and optionally a short
 465usage message for your whole program.  Here's an OptionParser populated with
 466user-friendly (documented) options::
 467
 468   usage = "usage: %prog [options] arg1 arg2"
 469   parser = OptionParser(usage=usage)
 470   parser.add_option("-v", "--verbose",
 471                     action="store_true", dest="verbose", default=True,
 472                     help="make lots of noise [default]")
 473   parser.add_option("-q", "--quiet",
 474                     action="store_false", dest="verbose",
 475                     help="be vewwy quiet (I'm hunting wabbits)")
 476   parser.add_option("-f", "--filename",
 477                     metavar="FILE", help="write output to FILE")
 478   parser.add_option("-m", "--mode",
 479                     default="intermediate",
 480                     help="interaction mode: novice, intermediate, "
 481                          "or expert [default: %default]")
 482
 483If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
 484command-line, or if you just call :meth:`parser.print_help`, it prints the
 485following to standard output::
 486
 487   usage: <yourscript> [options] arg1 arg2
 488
 489   options:
 490     -h, --help            show this help message and exit
 491     -v, --verbose         make lots of noise [default]
 492     -q, --quiet           be vewwy quiet (I'm hunting wabbits)
 493     -f FILE, --filename=FILE
 494                           write output to FILE
 495     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
 496                           expert [default: intermediate]
 497
 498(If the help output is triggered by a help option, :mod:`optparse` exits after
 499printing the help text.)
 500
 501There's a lot going on here to help :mod:`optparse` generate the best possible
 502help message:
 503
 504* the script defines its own usage message::
 505
 506     usage = "usage: %prog [options] arg1 arg2"
 507
 508  :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
 509  current program, i.e. ``os.path.basename(sys.argv[0])``.  The expanded string
 510  is then printed before the detailed option help.
 511
 512  If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
 513  default: ``"usage: %prog [options]"``, which is fine if your script doesn't
 514  take any positional arguments.
 515
 516* every option defines a help string, and doesn't worry about line-wrapping---
 517  :mod:`optparse` takes care of wrapping lines and making the help output look
 518  good.
 519
 520* options that take a value indicate this fact in their automatically-generated
 521  help message, e.g. for the "mode" option::
 522
 523     -m MODE, --mode=MODE
 524
 525  Here, "MODE" is called the meta-variable: it stands for the argument that the
 526  user is expected to supply to :option:`-m`/:option:`--mode`.  By default,
 527  :mod:`optparse` converts the destination variable name to uppercase and uses
 528  that for the meta-variable.  Sometimes, that's not what you want---for
 529  example, the :option:`--filename` option explicitly sets ``metavar="FILE"``,
 530  resulting in this automatically-generated option description::
 531
 532     -f FILE, --filename=FILE
 533
 534  This is important for more than just saving space, though: the manually
 535  written help text uses the meta-variable "FILE" to clue the user in that
 536  there's a connection between the semi-formal syntax "-f FILE" and the informal
 537  semantic description "write output to FILE". This is a simple but effective
 538  way to make your help text a lot clearer and more useful for end users.
 539
 540.. versionadded:: 2.4
 541   Options that have a default value can include ``%default`` in the help
 542   string---\ :mod:`optparse` will replace it with :func:`str` of the option's
 543   default value.  If an option has no default value (or the default value is
 544   ``None``), ``%default`` expands to ``none``.
 545
 546When dealing with many options, it is convenient to group these options for
 547better help output.  An :class:`OptionParser` can contain several option groups,
 548each of which can contain several options.
 549
 550Continuing with the parser defined above, adding an :class:`OptionGroup` to a
 551parser is easy::
 552
 553    group = OptionGroup(parser, "Dangerous Options",
 554                        "Caution: use these options at your own risk.  "
 555                        "It is believed that some of them bite.")
 556    group.add_option("-g", action="store_true", help="Group option.")
 557    parser.add_option_group(group)
 558
 559This would result in the following help output::
 560
 561    usage:  [options] arg1 arg2
 562
 563    options:
 564      -h, --help           show this help message and exit
 565      -v, --verbose        make lots of noise [default]
 566      -q, --quiet          be vewwy quiet (I'm hunting wabbits)
 567      -fFILE, --file=FILE  write output to FILE
 568      -mMODE, --mode=MODE  interaction mode: one of 'novice', 'intermediate'
 569                           [default], 'expert'
 570
 571      Dangerous Options:
 572      Caution: use of these options is at your own risk.  It is believed that
 573      some of them bite.
 574      -g                 Group option.
 575
 576.. _optparse-printing-version-string:
 577
 578Printing a version string
 579^^^^^^^^^^^^^^^^^^^^^^^^^
 580
 581Similar to the brief usage string, :mod:`optparse` can also print a version
 582string for your program.  You have to supply the string as the ``version``
 583argument to OptionParser::
 584
 585   parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
 586
 587``"%prog"`` is expanded just like it is in ``usage``.  Apart from that,
 588``version`` can contain anything you like.  When you supply it, :mod:`optparse`
 589automatically adds a ``"--version"`` option to your parser. If it encounters
 590this option on the command line, it expands your ``version`` string (by
 591replacing ``"%prog"``), prints it to stdout, and exits.
 592
 593For example, if your script is called ``/usr/bin/foo``::
 594
 595   $ /usr/bin/foo --version
 596   foo 1.0
 597
 598
 599.. _optparse-how-optparse-handles-errors:
 600
 601How :mod:`optparse` handles errors
 602^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 603
 604There are two broad classes of errors that :mod:`optparse` has to worry about:
 605programmer errors and user errors.  Programmer errors are usually erroneous
 606calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
 607option attributes, missing option attributes, etc.  These are dealt with in the
 608usual way: raise an exception (either :exc:`optparse.OptionError` or
 609:exc:`TypeError`) and let the program crash.
 610
 611Handling user errors is much more important, since they are guaranteed to happen
 612no matter how stable your code is.  :mod:`optparse` can automatically detect
 613some user errors, such as bad option arguments (passing ``"-n 4x"`` where
 614:option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
 615of the command line, where :option:`-n` takes an argument of any type).  Also,
 616you can call :func:`OptionParser.error` to signal an application-defined error
 617condition::
 618
 619   (options, args) = parser.parse_args()
 620   [...]
 621   if options.a and options.b:
 622       parser.error("options -a and -b are mutually exclusive")
 623
 624In either case, :mod:`optparse` handles the error the same way: it prints the
 625program's usage message and an error message to standard error and exits with
 626error status 2.
 627
 628Consider the first example above, where the user passes ``"4x"`` to an option
 629that takes an integer::
 630
 631   $ /usr/bin/foo -n 4x
 632   usage: foo [options]
 633
 634   foo: error: option -n: invalid integer value: '4x'
 635
 636Or, where the user fails to pass a value at all::
 637
 638   $ /usr/bin/foo -n
 639   usage: foo [options]
 640
 641   foo: error: -n option requires an argument
 642
 643:mod:`optparse`\ -generated error messages take care always to mention the
 644option involved in the error; be sure to do the same when calling
 645:func:`OptionParser.error` from your application code.
 646
 647If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
 648you'll need to subclass OptionParser and override its :meth:`exit` and/or
 649:meth:`error` methods.
 650
 651
 652.. _optparse-putting-it-all-together:
 653
 654Putting it all together
 655^^^^^^^^^^^^^^^^^^^^^^^
 656
 657Here's what :mod:`optparse`\ -based scripts usually look like::
 658
 659   from optparse import OptionParser
 660   [...]
 661   def main():
 662       usage = "usage: %prog [options] arg"
 663       parser = OptionParser(usage)
 664       parser.add_option("-f", "--file", dest="filename",
 665                         help="read data from FILENAME")
 666       parser.add_option("-v", "--verbose",
 667                         action="store_true", dest="verbose")
 668       parser.add_option("-q", "--quiet",
 669                         action="store_false", dest="verbose")
 670       [...]
 671       (options, args) = parser.parse_args()
 672       if len(args) != 1:
 673           parser.error("incorrect number of arguments")
 674       if options.verbose:
 675           print "reading %s..." % options.filename
 676       [...]
 677
 678   if __name__ == "__main__":
 679       main()
 680
 681
 682.. _optparse-reference-guide:
 683
 684Reference Guide
 685---------------
 686
 687
 688.. _optparse-creating-parser:
 689
 690Creating the parser
 691^^^^^^^^^^^^^^^^^^^
 692
 693The first step in using :mod:`optparse` is to create an OptionParser instance.
 694
 695.. class:: OptionParser(...)
 696
 697   The OptionParser constructor has no required arguments, but a number of
 698   optional keyword arguments.  You should always pass them as keyword
 699   arguments, i.e. do not rely on the order in which the arguments are declared.
 700
 701   ``usage`` (default: ``"%prog [options]"``)
 702      The usage summary to print when your program is run incorrectly or with a
 703      help option.  When :mod:`optparse` prints the usage string, it expands
 704      ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
 705      passed that keyword argument).  To suppress a usage message, pass the
 706      special value :data:`optparse.SUPPRESS_USAGE`.
 707
 708   ``option_list`` (default: ``[]``)
 709      A list of Option objects to populate the parser with.  The options in
 710      ``option_list`` are added after any options in ``standard_option_list`` (a
 711      class attribute that may be set by OptionParser subclasses), but before
 712      any version or help options. Deprecated; use :meth:`add_option` after
 713      creating the parser instead.
 714
 715   ``option_class`` (default: optparse.Option)
 716      Class to use when adding options to the parser in :meth:`add_option`.
 717
 718   ``version`` (default: ``None``)
 719      A version string to print when the user supplies a version option. If you
 720      supply a true value for ``version``, :mod:`optparse` automatically adds a
 721      version option with the single option string ``"--version"``.  The
 722      substring ``"%prog"`` is expanded the same as for ``usage``.
 723
 724   ``conflict_handler`` (default: ``"error"``)
 725      Specifies what to do when options with conflicting option strings are
 726      added to the parser; see section
 727      :ref:`optparse-conflicts-between-options`.
 728
 729   ``description`` (default: ``None``)
 730      A paragraph of text giving a brief overview of your program.
 731      :mod:`optparse` reformats this paragraph to fit the current terminal width
 732      and prints it when the user requests help (after ``usage``, but before the
 733      list of options).
 734
 735   ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
 736      An instance of optparse.HelpFormatter that will be used for printing help
 737      text.  :mod:`optparse` provides two concrete classes for this purpose:
 738      IndentedHelpFormatter and TitledHelpFormatter.
 739
 740   ``add_help_option`` (default: ``True``)
 741      If true, :mod:`optparse` will add a help option (with option strings ``"-h"``
 742      and ``"--help"``) to the parser.
 743
 744   ``prog``
 745      The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
 746      instead of ``os.path.basename(sys.argv[0])``.
 747
 748
 749
 750.. _optparse-populating-parser:
 751
 752Populating the parser
 753^^^^^^^^^^^^^^^^^^^^^
 754
 755There are several ways to populate the parser with options.  The preferred way
 756is by using :meth:`OptionParser.add_option`, as shown in section
 757:ref:`optparse-tutorial`.  :meth:`add_option` can be called in one of two ways:
 758
 759* pass it an Option instance (as returned by :func:`make_option`)
 760
 761* pass it any combination of positional and keyword arguments that are
 762  acceptable to :func:`make_option` (i.e., to the Option constructor), and it
 763  will create the Option instance for you
 764
 765The other alternative is to pass a list of pre-constructed Option instances to
 766the OptionParser constructor, as in::
 767
 768   option_list = [
 769       make_option("-f", "--filename",
 770                   action="store", type="string", dest="filename"),
 771       make_option("-q", "--quiet",
 772                   action="store_false", dest="verbose"),
 773       ]
 774   parser = OptionParser(option_list=option_list)
 775
 776(:func:`make_option` is a factory function for creating Option instances;
 777currently it is an alias for the Option constructor.  A future version of
 778:mod:`optparse` may split Option into several classes, and :func:`make_option`
 779will pick the right class to instantiate.  Do not instantiate Option directly.)
 780
 781
 782.. _optparse-defining-options:
 783
 784Defining options
 785^^^^^^^^^^^^^^^^
 786
 787Each Option instance represents a set of synonymous command-line option strings,
 788e.g. :option:`-f` and :option:`--file`.  You can specify any number of short or
 789long option strings, but you must specify at least one overall option string.
 790
 791The canonical way to create an :class:`Option` instance is with the
 792:meth:`add_option` method of :class:`OptionParser`.
 793
 794.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
 795
 796   To define an option with only a short option string::
 797
 798      parser.add_option("-f", attr=value, ...)
 799
 800   And to define an option with only a long option string::
 801
 802      parser.add_option("--foo", attr=value, ...)
 803
 804   The keyword arguments define attributes of the new Option object.  The most
 805   important option attribute is :attr:`~Option.action`, and it largely
 806   determines which other attributes are relevant or required.  If you pass
 807   irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
 808   raises an :exc:`OptionError` exception explaining your mistake.
 809
 810   An option's *action* determines what :mod:`optparse` does when it encounters
 811   this option on the command-line.  The standard option actions hard-coded into
 812   :mod:`optparse` are:
 813
 814   ``"store"``
 815      store this option's argument (default)
 816
 817   ``"store_const"``
 818      store a constant value
 819
 820   ``"store_true"``
 821      store a true value
 822
 823   ``"store_false"``
 824      store a false value
 825
 826   ``"append"``
 827      append this option's argument to a list
 828
 829   ``"append_const"``
 830      append a constant value to a list
 831
 832   ``"count"``
 833      increment a counter by one
 834
 835   ``"callback"``
 836      call a specified function
 837
 838   ``"help"``
 839      print a usage message including all options and the documentation for them
 840
 841   (If you don't supply an action, the default is ``"store"``.  For this action,
 842   you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
 843   attributes; see :ref:`optparse-standard-option-actions`.)
 844
 845As you can see, most actions involve storing or updating a value somewhere.
 846:mod:`optparse` always creates a special object for this, conventionally called
 847``options`` (it happens to be an instance of :class:`optparse.Values`).  Option
 848arguments (and various other values) are stored as attributes of this object,
 849according to the :attr:`~Option.dest` (destination) option attribute.
 850
 851For example, when you call ::
 852
 853   parser.parse_args()
 854
 855one of the first things :mod:`optparse` does is create the ``options`` object::
 856
 857   options = Values()
 858
 859If one of the options in this parser is defined with ::
 860
 861   parser.add_option("-f", "--file", action="store", type="string", dest="filename")
 862
 863and the command-line being parsed includes any of the following::
 864
 865   -ffoo
 866   -f foo
 867   --file=foo
 868   --file foo
 869
 870then :mod:`optparse`, on seeing this option, will do the equivalent of ::
 871
 872   options.filename = "foo"
 873
 874The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
 875as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
 876one that makes sense for *all* options.
 877
 878
 879.. _optparse-option-attributes:
 880
 881Option attributes
 882^^^^^^^^^^^^^^^^^
 883
 884The following option attributes may be passed as keyword arguments to
 885:meth:`OptionParser.add_option`.  If you pass an option attribute that is not
 886relevant to a particular option, or fail to pass a required option attribute,
 887:mod:`optparse` raises :exc:`OptionError`.
 888
 889.. attribute:: Option.action
 890
 891   (default: ``"store"``)
 892
 893   Determines :mod:`optparse`'s behaviour when this option is seen on the
 894   command line; the available options are documented :ref:`here
 895   <optparse-standard-option-actions>`.
 896
 897.. attribute:: Option.type
 898
 899   (default: ``"string"``)
 900
 901   The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
 902   the available option types are documented :ref:`here
 903   <optparse-standard-option-types>`.
 904
 905.. attribute:: Option.dest
 906
 907   (default: derived from option strings)
 908
 909   If the option's action implies writing or modifying a value somewhere, this
 910   tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
 911   attribute of the ``options`` object that :mod:`optparse` builds as it parses
 912   the command line.
 913
 914.. attribute:: Option.default
 915
 916   The value to use for this option's destination if the option is not seen on
 917   the command line.  See also :meth:`OptionParser.set_defaults`.
 918
 919.. attribute:: Option.nargs
 920
 921   (default: 1)
 922
 923   How many arguments of type :attr:`~Option.type` should be consumed when this
 924   option is seen.  If > 1, :mod:`optparse` will store a tuple of values to
 925   :attr:`~Option.dest`.
 926
 927.. attribute:: Option.const
 928
 929   For actions that store a constant value, the constant value to store.
 930
 931.. attribute:: Option.choices
 932
 933   For options of type ``"choice"``, the list of strings the user may choose
 934   from.
 935
 936.. attribute:: Option.callback
 937
 938   For options with action ``"callback"``, the callable to call when this option
 939   is seen.  See section :ref:`optparse-option-callbacks` for detail on the
 940   arguments passed to the callable.
 941
 942.. attribute:: Option.callback_args
 943               Option.callback_kwargs
 944
 945   Additional positional and keyword arguments to pass to ``callback`` after the
 946   four standard callback arguments.
 947
 948.. attribute:: Option.help
 949
 950   Help text to print for this option when listing all available options after
 951   the user supplies a :attr:`~Option.help` option (such as ``"--help"``).  If
 952   no help text is supplied, the option will be listed without help text.  To
 953   hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
 954
 955.. attribute:: Option.metavar
 956
 957   (default: derived from option strings)
 958
 959   Stand-in for the option argument(s) to use when printing help text.  See
 960   section :ref:`optparse-tutorial` for an example.
 961
 962
 963.. _optparse-standard-option-actions:
 964
 965Standard option actions
 966^^^^^^^^^^^^^^^^^^^^^^^
 967
 968The various option actions all have slightly different requirements and effects.
 969Most actions have several relevant option attributes which you may specify to
 970guide :mod:`optparse`'s behaviour; a few have required attributes, which you
 971must specify for any option using that action.
 972
 973* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
 974  :attr:`~Option.nargs`, :attr:`~Option.choices`]
 975
 976  The option must be followed by an argument, which is converted to a value
 977  according to :attr:`~Option.type` and stored in :attr:`~Option.dest`.  If
 978  :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
 979  command line; all will be converted according to :attr:`~Option.type` and
 980  stored to :attr:`~Option.dest` as a tuple.  See the
 981  :ref:`optparse-standard-option-types` section.
 982
 983  If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
 984  defaults to ``"choice"``.
 985
 986  If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
 987
 988  If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
 989  from the first long option string (e.g., ``"--foo-bar"`` implies
 990  ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
 991  destination from the first short option string (e.g., ``"-f"`` implies ``f``).
 992
 993  Example::
 994
 995     parser.add_option("-f")
 996     parser.add_option("-p", type="float", nargs=3, dest="point")
 997
 998  As it parses the command line ::
 999
1000     -f foo.txt -p 1 -3.5 4 -fbar.txt
1001
1002  :mod:`optparse` will set ::
1003
1004     options.f = "foo.txt"
1005     options.point = (1.0, -3.5, 4.0)
1006     options.f = "bar.txt"
1007
1008* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1009  :attr:`~Option.dest`]
1010
1011  The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
1012
1013  Example::
1014
1015     parser.add_option("-q", "--quiet",
1016                       action="store_const", const=0, dest="verbose")
1017     parser.add_option("-v", "--verbose",
1018                       action="store_const", const=1, dest="verbose")
1019     parser.add_option("--noisy",
1020                       action="store_const", const=2, dest="verbose")
1021
1022  If ``"--noisy"`` is seen, :mod:`optparse` will set  ::
1023
1024     options.verbose = 2
1025
1026* ``"store_true"`` [relevant: :attr:`~Option.dest`]
1027
1028  A special case of ``"store_const"`` that stores a true value to
1029  :attr:`~Option.dest`.
1030
1031* ``"store_false"`` [relevant: :attr:`~Option.dest`]
1032
1033  Like ``"store_true"``, but stores a false value.
1034
1035  Example::
1036
1037     parser.add_option("--clobber", action="store_true", dest="clobber")
1038     parser.add_option("--no-clobber", action="store_false", dest="clobber")
1039
1040* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1041  :attr:`~Option.nargs`, :attr:`~Option.choices`]
1042
1043  The option must be followed by an argument, which is appended to the list in
1044  :attr:`~Option.dest`.  If no default value for :attr:`~Option.dest` is
1045  supplied, an empty list is automatically created when :mod:`optparse` first
1046  encounters this option on the command-line.  If :attr:`~Option.nargs` > 1,
1047  multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1048  is appended to :attr:`~Option.dest`.
1049
1050  The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1051  for the ``"store"`` action.
1052
1053  Example::
1054
1055     parser.add_option("-t", "--tracks", action="append", type="int")
1056
1057  If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
1058  of::
1059
1060     options.tracks = []
1061     options.tracks.append(int("3"))
1062
1063  If, a little later on, ``"--tracks=4"`` is seen, it does::
1064
1065     options.tracks.append(int("4"))
1066
1067* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1068  :attr:`~Option.dest`]
1069
1070  Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1071  :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1072  ``None``, and an empty list is automatically created the first time the option
1073  is encountered.
1074
1075* ``"count"`` [relevant: :attr:`~Option.dest`]
1076
1077  Increment the integer stored at :attr:`~Option.dest`.  If no default value is
1078  supplied, :attr:`~Option.dest` is set to zero before being incremented the
1079  first time.
1080
1081  Example::
1082
1083     parser.add_option("-v", action="count", dest="verbosity")
1084
1085  The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
1086  equivalent of::
1087
1088     options.verbosity = 0
1089     options.verbosity += 1
1090
1091  Every subsequent occurrence of ``"-v"`` results in  ::
1092
1093     options.verbosity += 1
1094
1095* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1096  :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1097  :attr:`~Option.callback_kwargs`]
1098
1099  Call the function specified by :attr:`~Option.callback`, which is called as ::
1100
1101     func(option, opt_str, value, parser, *args, **kwargs)
1102
1103  See section :ref:`optparse-option-callbacks` for more detail.
1104
1105* ``"help"``
1106
1107  Prints a complete help message for all the options in the current option
1108  parser.  The help message is constructed from the ``usage`` string passed to
1109  OptionParser's constructor and the :attr:`~Option.help` string passed to every
1110  option.
1111
1112  If no :attr:`~Option.help` string is supplied for an option, it will still be
1113  listed in the help message.  To omit an option entirely, use the special value
1114  :data:`optparse.SUPPRESS_HELP`.
1115
1116  :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1117  OptionParsers, so you do not normally need to create one.
1118
1119  Example::
1120
1121     from optparse import OptionParser, SUPPRESS_HELP
1122
1123     # usually, a help option is added automatically, but that can
1124     # be suppressed using the add_help_option argument
1125     parser = OptionParser(add_help_option=False)
1126
1127     parser.add_option("-h", "--help", action="help")
1128     parser.add_option("-v", action="store_true", dest="verbose",
1129                       help="Be moderately verbose")
1130     parser.add_option("--file", dest="filename",
1131                       help="Input file to read data from")
1132     parser.add_option("--secret", help=SUPPRESS_HELP)
1133
1134  If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line,
1135  it will print something like the following help message to stdout (assuming
1136  ``sys.argv[0]`` is ``"foo.py"``)::
1137
1138     usage: foo.py [options]
1139
1140     options:
1141       -h, --help        Show this help message and exit
1142       -v                Be moderately verbose
1143       --file=FILENAME   Input file to read data from
1144
1145  After printing the help message, :mod:`optparse` terminates your process with
1146  ``sys.exit(0)``.
1147
1148* ``"version"``
1149
1150  Prints the version number supplied to the OptionParser to stdout and exits.
1151  The version number is actually formatted and printed by the
1152  ``print_version()`` method of OptionParser.  Generally only relevant if the
1153  ``version`` argument is supplied to the OptionParser constructor.  As with
1154  :attr:`~Option.help` options, you will rarely create ``version`` options,
1155  since :mod:`optparse` automatically adds them when needed.
1156
1157
1158.. _optparse-standard-option-types:
1159
1160Standard option types
1161^^^^^^^^^^^^^^^^^^^^^
1162
1163:mod:`optparse` has six built-in option types: ``"string"``, ``"int"``,
1164``"long"``, ``"choice"``, ``"float"`` and ``"complex"``.  If you need to add new
1165option types, see section :ref:`optparse-extending-optparse`.
1166
1167Arguments to string options are not checked or converted in any way: the text on
1168the command line is stored in the destination (or passed to the callback) as-is.
1169
1170Integer arguments (type ``"int"`` or ``"long"``) are parsed as follows:
1171
1172* if the number starts with ``0x``, it is parsed as a hexadecimal number
1173
1174* if the number starts with ``0``, it is parsed as an octal number
1175
1176* if the number starts with ``0b``, it is parsed as a binary number
1177
1178* otherwise, the number is parsed as a decimal number
1179
1180
1181The conversion is done by calling either :func:`int` or :func:`long` with the
1182appropriate base (2, 8, 10, or 16).  If this fails, so will :mod:`optparse`,
1183although with a more useful error message.
1184
1185``"float"`` and ``"complex"`` option arguments are converted directly with
1186:func:`float` and :func:`complex`, with similar error-handling.
1187
1188``"choice"`` options are a subtype of ``"string"`` options.  The
1189:attr:`~Option.choices`` option attribute (a sequence of strings) defines the
1190set of allowed option arguments.  :func:`optparse.check_choice` compares
1191user-supplied option arguments against this master list and raises
1192:exc:`OptionValueError` if an invalid string is given.
1193
1194
1195.. _optparse-parsing-arguments:
1196
1197Parsing arguments
1198^^^^^^^^^^^^^^^^^
1199
1200The whole point of creating and populating an OptionParser is to call its
1201:meth:`parse_args` method::
1202
1203   (options, args) = parser.parse_args(args=None, values=None)
1204
1205where the input parameters are
1206
1207``args``
1208   the list of arguments to process (default: ``sys.argv[1:]``)
1209
1210``values``
1211   object to store option arguments in (default: a new instance of
1212   :class:`optparse.Values`)
1213
1214and the return values are
1215
1216``options``
1217   the same object that was passed in as ``values``, or the optparse.Values
1218   instance created by :mod:`optparse`
1219
1220``args``
1221   the leftover positional arguments after all options have been processed
1222
1223The most common usage is to supply neither keyword argument.  If you supply
1224``values``, it will be modified with repeated :func:`setattr` calls (roughly one
1225for every option argument stored to an option destination) and returned by
1226:meth:`parse_args`.
1227
1228If :meth:`parse_args` encounters any errors in the argument list, it calls the
1229OptionParser's :meth:`error` method with an appropriate end-user error message.
1230This ultimately terminates your process with an exit status of 2 (the
1231traditional Unix exit status for command-line errors).
1232
1233
1234.. _optparse-querying-manipulating-option-parser:
1235
1236Querying and manipulating your option parser
1237^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1238
1239The default behavior of the option parser can be customized slightly, and you
1240can also poke around your option parser and see what's there.  OptionParser
1241provides several methods to help you out:
1242
1243.. method:: OptionParser.disable_interspersed_args()
1244
1245   Set parsing to stop on the first non-option.  For example, if ``"-a"`` and
1246   ``"-b"`` are both simple options that take no arguments, :mod:`optparse`
1247   normally accepts this syntax::
1248
1249      prog -a arg1 -b arg2
1250
1251   and treats it as equivalent to  ::
1252
1253      prog -a -b arg1 arg2
1254
1255   To disable this feature, call :meth:`disable_interspersed_args`.  This
1256   restores traditional Unix syntax, where option parsing stops with the first
1257   non-option argument.
1258
1259   Use this if you have a command processor which runs another command which has
1260   options of its own and you want to make sure these options don't get
1261   confused.  For example, each command might have a different set of options.
1262
1263.. method:: OptionParser.enable_interspersed_args()
1264
1265   Set parsing to not stop on the first non-option, allowing interspersing
1266   switches with command arguments.  This is the default behavior.
1267
1268.. method:: OptionParser.get_option(opt_str)
1269
1270   Returns the Option instance with the option string *opt_str*, or ``None`` if
1271   no options have that option string.
1272
1273.. method:: OptionParser.has_option(opt_str)
1274
1275   Return true if the OptionParser has an option with option string *opt_str*
1276   (e.g., ``"-q"`` or ``"--verbose"``).
1277
1278.. method:: OptionParser.remove_option(opt_str)
1279
1280   If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1281   option is removed.  If that option provided any other option strings, all of
1282   those option strings become invalid. If *opt_str* does not occur in any
1283   option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
1284
1285
1286.. _optparse-conflicts-between-options:
1287
1288Conflicts between options
1289^^^^^^^^^^^^^^^^^^^^^^^^^
1290
1291If you're not careful, it's easy to define options with conflicting option
1292strings::
1293
1294   parser.add_option("-n", "--dry-run", ...)
1295   [...]
1296   parser.add_option("-n", "--noisy", ...)
1297
1298(This is particularly true if you've defined your own OptionParser subclass with
1299some standard options.)
1300
1301Every time you add an option, :mod:`optparse` checks for conflicts with existing
1302options.  If it finds any, it invokes the current conflict-handling mechanism.
1303You can set the conflict-handling mechanism either in the constructor::
1304
1305   parser = OptionParser(..., conflict_handler=handler)
1306
1307or with a separate call::
1308
1309   parser.set_conflict_handler(handler)
1310
1311The available conflict handlers are:
1312
1313   ``"error"`` (default)
1314      assume option conflicts are a programming error and raise
1315      :exc:`OptionConflictError`
1316
1317   ``"resolve"``
1318      resolve option conflicts intelligently (see below)
1319
1320
1321As an example, let's define an :class:`OptionParser` that resolves conflicts
1322intelligently and add conflicting options to it::
1323
1324   parser = OptionParser(conflict_handler="resolve")
1325   parser.add_option("-n", "--dry-run", ..., help="do no harm")
1326   parser.add_option("-n", "--noisy", ..., help="be noisy")
1327
1328At this point, :mod:`optparse` detects that a previā€¦

Large files files are truncated, but you can click here to view the full file