rest25/library/optparse.rst => rest262/library/optparse.rst
n1-.. % THIS FILE IS AUTO-GENERATED!  DO NOT EDIT!
2-.. % (Your changes will be lost the next time it is generated.)
3- 
4- 
5:mod:`optparse` --- More powerful command line option parser
6============================================================
7
8.. module:: optparse
9   :synopsis: More convenient, flexible, and powerful command-line parsing library.
10.. moduleauthor:: Greg Ward <gward@python.net>
11
12
13.. versionadded:: 2.3
14
15.. sectionauthor:: Greg Ward <gward@python.net>
16
17
18``optparse`` is a more convenient, flexible, and powerful library for parsing
n19-command-line options than ``getopt``.  ``optparse`` uses a more declarative
n15+command-line options than the old :mod:`getopt` module.  ``optparse`` uses a more declarative
20style of command-line parsing: you create an instance of :class:`OptionParser`,
21populate it with options, and parse the command line. ``optparse`` allows users
22to specify options in the conventional GNU/POSIX syntax, and additionally
23generates usage and help messages for you.
n24- 
25-.. % An intro blurb used only when generating LaTeX docs for the Python
26-.. % manual (based on README.txt).
27
28Here's an example of using ``optparse`` in a simple script::
29
30   from optparse import OptionParser
31   [...]
32   parser = OptionParser()
33   parser.add_option("-f", "--file", dest="filename",
34                     help="write report to FILE", metavar="FILE")
69   options:
70     -h, --help            show this help message and exit
71     -f FILE, --file=FILE  write report to FILE
72     -q, --quiet           don't print status messages to stdout
73
74where the value of *yourscript* is determined at runtime (normally from
75``sys.argv[0]``).
76
n77-.. % $Id: intro.txt 413 2004-09-28 00:59:13Z greg $
78- 
79
80.. _optparse-background:
81
82Background
83----------
84
85:mod:`optparse` was explicitly designed to encourage the creation of programs
86with straightforward, conventional command-line interfaces.  To that end, it
100   (``sys.argv[0]`` is the name of the program being executed).  Unix shells also
101   use the term "word".
102
103   It is occasionally desirable to substitute an argument list other than
104   ``sys.argv[1:]``, so you should read "argument" as "an element of
105   ``sys.argv[1:]``, or of some other list provided as a substitute for
106   ``sys.argv[1:]``".
107
n108-option   
n99+option
109   an argument used to supply extra information to guide or customize the execution
110   of a program.  There are many different syntaxes for options; the traditional
111   Unix syntax is a hyphen ("-") followed by a single letter, e.g. ``"-x"`` or
112   ``"-F"``.  Also, traditional Unix syntax allows multiple options to be merged
113   into a single argument, e.g.  ``"-x -F"`` is equivalent to ``"-xF"``.  The GNU
114   project introduced ``"--"`` followed by a series of hyphen-separated words, e.g.
115   ``"--file"`` or ``"--dry-run"``.  These are the only two option syntaxes
116   provided by :mod:`optparse`.
117
118   Some other option syntaxes that the world has seen include:
119
n120-  a hyphen followed by a few letters, e.g. ``"-pf"`` (this is *not* the same
n111+   * a hyphen followed by a few letters, e.g. ``"-pf"`` (this is *not* the same
121     as multiple options merged into a single argument)
122
n123-  a hyphen followed by a whole word, e.g. ``"-file"`` (this is technically
n114+   * a hyphen followed by a whole word, e.g. ``"-file"`` (this is technically
124     equivalent to the previous syntax, but they aren't usually seen in the same
125     program)
126
n127-  a plus sign followed by a single letter, or a few letters, or a word, e.g.
n118+   * a plus sign followed by a single letter, or a few letters, or a word, e.g.
128     ``"+f"``, ``"+rgb"``
129
n130-  a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
n121+   * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
131     ``"/file"``
132
133   These option syntaxes are not supported by :mod:`optparse`, and they never will
134   be.  This is deliberate: the first three are non-standard on any environment,
135   and the last only makes sense if you're exclusively targeting VMS, MS-DOS,
136   and/or Windows.
137
138option argument
232required to supply---use sensible defaults whenever possible.  Of course, you
233also want to make your programs reasonably flexible.  That's what options are
234for.  Again, it doesn't matter if they are entries in a config file, widgets in
235the "Preferences" dialog of a GUI, or command-line options---the more options
236you implement, the more flexible your program is, and the more complicated its
237implementation becomes.  Too much flexibility has drawbacks as well, of course;
238too many options can overwhelm users and make your code much harder to maintain.
239
n240-.. % $Id: tao.txt 413 2004-09-28 00:59:13Z greg $
241- 
242
243.. _optparse-tutorial:
244
245Tutorial
246--------
247
248While :mod:`optparse` is quite flexible and powerful, it's also straightforward
249to use in most cases.  This section covers the code patterns that are common to
284
285   (options, args) = parser.parse_args()
286
287(If you like, you can pass a custom argument list to :meth:`parse_args`, but
288that's rarely necessary: by default it uses ``sys.argv[1:]``.)
289
290:meth:`parse_args` returns two values:
291
n292-*   ``options``, an object containing values for all of your options---e.g. if
n281+* ``options``, an object containing values for all of your options---e.g. if
293  ``"--file"`` takes a single string argument, then ``options.file`` will be the
294  filename supplied by the user, or ``None`` if the user did not supply that
295  option
296
n297-*   ``args``, the list of positional arguments leftover after parsing options
n286+* ``args``, the list of positional arguments leftover after parsing options
298
299This tutorial section only covers the four most important option attributes:
300:attr:`action`, :attr:`type`, :attr:`dest` (destination), and :attr:`help`. Of
301these, :attr:`action` is the most fundamental.
302
303
304.. _optparse-understanding-option-actions:
305
306Understanding option actions
307^^^^^^^^^^^^^^^^^^^^^^^^^^^^
308
309Actions tell :mod:`optparse` what to do when it encounters an option on the
310command line.  There is a fixed set of actions hard-coded into :mod:`optparse`;
311adding new actions is an advanced topic covered in section
n312-:ref:`optparse-extending-optparse`, Extending :mod:`optparse`. Most actions tell
n301+:ref:`optparse-extending-optparse`. Most actions tell
313:mod:`optparse` to store a value in some variable---for example, take a string
314from the command line and store it in an attribute of ``options``.
315
316If you don't specify an option action, :mod:`optparse` defaults to ``store``.
317
318
319.. _optparse-store-action:
320
364
365If you don't supply a destination, :mod:`optparse` figures out a sensible
366default from the option strings: if the first long option string is
367``"--foo-bar"``, then the default destination is ``foo_bar``.  If there are no
368long option strings, :mod:`optparse` looks at the first short option string: the
369default destination for ``"-f"`` is ``f``.
370
371:mod:`optparse` also includes built-in ``long`` and ``complex`` types.  Adding
n372-types is covered in section :ref:`optparse-extending-optparse`, Extending
n361+types is covered in section :ref:`optparse-extending-optparse`.
373-:mod:`optparse`.
374
375
376.. _optparse-handling-boolean-options:
377
378Handling boolean (flag) options
379^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
380
381Flag options---set a variable to true or false when a particular option is seen
410
411``count``
412   increment a counter by one
413
414``callback``
415   call a specified function
416
417These are covered in section :ref:`optparse-reference-guide`, Reference Guide
n418-and section :ref:`optparse-option-callbacks`, Option Callbacks.
n406+and section :ref:`optparse-option-callbacks`.
419
420
421.. _optparse-default-values:
422
423Default values
424^^^^^^^^^^^^^^
425
426All of the above examples involve setting some variable (the "destination") when
466.. _optparse-generating-help:
467
468Generating help
469^^^^^^^^^^^^^^^
470
471:mod:`optparse`'s ability to generate help and usage text automatically is
472useful for creating user-friendly command-line interfaces.  All you have to do
473is supply a :attr:`help` value for each option, and optionally a short usage
n474-message for your whole program.  Here's an OptionParser populated with user-
n462+message for your whole program.  Here's an OptionParser populated with
475-friendly (documented) options::
463+user-friendly (documented) options::
476
477   usage = "usage: %prog [options] arg1 arg2"
478   parser = OptionParser(usage=usage)
479   parser.add_option("-v", "--verbose",
480                     action="store_true", dest="verbose", default=True,
481                     help="make lots of noise [default]")
482   parser.add_option("-q", "--quiet",
n483-                     action="store_false", dest="verbose", 
n471+                     action="store_false", dest="verbose",
484                     help="be vewwy quiet (I'm hunting wabbits)")
485   parser.add_option("-f", "--filename",
486                     metavar="FILE", help="write output to FILE"),
487   parser.add_option("-m", "--mode",
488                     default="intermediate",
489                     help="interaction mode: novice, intermediate, "
490                          "or expert [default: %default]")
491
n492-If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the command-
n480+If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
493-line, or if you just call :meth:`parser.print_help`, it prints the following to
481+command-line, or if you just call :meth:`parser.print_help`, it prints the
494-standard output::
482+following to standard output::
495
496   usage: <yourscript> [options] arg1 arg2
497
498   options:
499     -h, --help            show this help message and exit
500     -v, --verbose         make lots of noise [default]
501     -q, --quiet           be vewwy quiet (I'm hunting wabbits)
502     -f FILE, --filename=FILE
505                           expert [default: intermediate]
506
507(If the help output is triggered by a help option, :mod:`optparse` exits after
508printing the help text.)
509
510There's a lot going on here to help :mod:`optparse` generate the best possible
511help message:
512
n513-*   the script defines its own usage message::
n501+* the script defines its own usage message::
514
515     usage = "usage: %prog [options] arg1 arg2"
516
517  :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
518  current program, i.e. ``os.path.basename(sys.argv[0])``.  The expanded string is
519  then printed before the detailed option help.
520
521  If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
n522-  default: "``usage: %prog [options]"``, which is fine if your script doesn't take
n510+  default: ``"usage: %prog [options]"``, which is fine if your script doesn't take
523  any positional arguments.
524
n525-*   every option defines a help string, and doesn't worry about line-
n513+* every option defines a help string, and doesn't worry about line-wrapping---
526-  wrapping---\ :mod:`optparse` takes care of wrapping lines and making the help
514+  :mod:`optparse` takes care of wrapping lines and making the help output look
527-  output look good.
515+  good.
528
n529-*   options that take a value indicate this fact in their automatically-
n517+* options that take a value indicate this fact in their automatically-generated
530-  generated help message, e.g. for the "mode" option::
518+  help message, e.g. for the "mode" option::
531
532     -m MODE, --mode=MODE
533
534  Here, "MODE" is called the meta-variable: it stands for the argument that the
535  user is expected to supply to :option:`-m`/:option:`--mode`.  By default,
536  :mod:`optparse` converts the destination variable name to uppercase and uses
537  that for the meta-variable.  Sometimes, that's not what you want---for example,
538  the :option:`--filename` option explicitly sets ``metavar="FILE"``, resulting in
541     -f FILE, --filename=FILE
542
543  This is important for more than just saving space, though: the manually written
544  help text uses the meta-variable "FILE" to clue the user in that there's a
545  connection between the semi-formal syntax "-f FILE" and the informal semantic
546  description "write output to FILE". This is a simple but effective way to make
547  your help text a lot clearer and more useful for end users.
548
n537+.. versionadded:: 2.4
549-*   options that have a default value can include ``%default`` in the help
538+   Options that have a default value can include ``%default`` in the help
550-  string---\ :mod:`optparse` will replace it with :func:`str` of the option's
539+   string---\ :mod:`optparse` will replace it with :func:`str` of the option's
551-  default value.  If an option has no default value (or the default value is
540+   default value.  If an option has no default value (or the default value is
552-  ``None``), ``%default`` expands to ``none``.
541+   ``None``), ``%default`` expands to ``none``.
553
n543+When dealing with many options, it is convenient to group these
544+options for better help output.  An :class:`OptionParser` can contain
545+several option groups, each of which can contain several options.
546+ 
547+Continuing with the parser defined above, adding an
548+:class:`OptionGroup` to a parser is easy::
549+ 
550+    group = OptionGroup(parser, "Dangerous Options",
551+                        "Caution: use these options at your own risk.  "
552+                        "It is believed that some of them bite.")
553+    group.add_option("-g", action="store_true", help="Group option.")
554+    parser.add_option_group(group)
555+ 
556+This would result in the following help output::
557+ 
558+    usage:  [options] arg1 arg2
559+ 
560+    options:
561+      -h, --help           show this help message and exit
562+      -v, --verbose        make lots of noise [default]
563+      -q, --quiet          be vewwy quiet (I'm hunting wabbits)
564+      -fFILE, --file=FILE  write output to FILE
565+      -mMODE, --mode=MODE  interaction mode: one of 'novice', 'intermediate'
566+                           [default], 'expert'
567+ 
568+      Dangerous Options:
569+      Caution: use of these options is at your own risk.  It is believed that
570+      some of them bite.
571+      -g                 Group option.
554
555.. _optparse-printing-version-string:
556
557Printing a version string
558^^^^^^^^^^^^^^^^^^^^^^^^^
559
560Similar to the brief usage string, :mod:`optparse` can also print a version
561string for your program.  You have to supply the string as the ``version``
579
580How :mod:`optparse` handles errors
581^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
582
583There are two broad classes of errors that :mod:`optparse` has to worry about:
584programmer errors and user errors.  Programmer errors are usually erroneous
585calls to ``parser.add_option()``, e.g. invalid option strings, unknown option
586attributes, missing option attributes, etc.  These are dealt with in the usual
n587-way: raise an exception (either ``optparse.OptionError`` or ``TypeError``) and
n605+way: raise an exception (either ``optparse.OptionError`` or :exc:`TypeError`) and
588let the program crash.
589
590Handling user errors is much more important, since they are guaranteed to happen
591no matter how stable your code is.  :mod:`optparse` can automatically detect
592some user errors, such as bad option arguments (passing ``"-n 4x"`` where
593:option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
594of the command line, where :option:`-n` takes an argument of any type).  Also,
595you can call ``parser.error()`` to signal an application-defined error
618   usage: foo [options]
619
620   foo: error: -n option requires an argument
621
622:mod:`optparse`\ -generated error messages take care always to mention the
623option involved in the error; be sure to do the same when calling
624``parser.error()`` from your application code.
625
n626-If :mod:`optparse`'s default error-handling behaviour does not suite your needs,
n644+If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
627-you'll need to subclass OptionParser and override ``exit()`` and/or
645+you'll need to subclass OptionParser and override its :meth:`exit` and/or
628-:meth:`error`.
646+:meth:`error` methods.
629
630
631.. _optparse-putting-it-all-together:
632
633Putting it all together
634^^^^^^^^^^^^^^^^^^^^^^^
635
636Here's what :mod:`optparse`\ -based scripts usually look like::
652           parser.error("incorrect number of arguments")
653       if options.verbose:
654           print "reading %s..." % options.filename
655       [...]
656
657   if __name__ == "__main__":
658       main()
659
n660-.. % $Id: tutorial.txt 515 2006-06-10 15:37:45Z gward $
661- 
662
663.. _optparse-reference-guide:
664
665Reference Guide
666---------------
667
668
669.. _optparse-creating-parser:
699   ``version`` (default: ``None``)
700      A version string to print when the user supplies a version option. If you supply
701      a true value for ``version``, :mod:`optparse` automatically adds a version
702      option with the single option string ``"--version"``.  The substring ``"%prog"``
703      is expanded the same as for ``usage``.
704
705   ``conflict_handler`` (default: ``"error"``)
706      Specifies what to do when options with conflicting option strings are added to
n707-      the parser; see section :ref:`optparse-conflicts-between-options`, Conflicts
n723+      the parser; see section :ref:`optparse-conflicts-between-options`.
708-      between options.
709
710   ``description`` (default: ``None``)
711      A paragraph of text giving a brief overview of your program.  :mod:`optparse`
712      reformats this paragraph to fit the current terminal width and prints it when
713      the user requests help (after ``usage``, but before the list of options).
714
715   ``formatter`` (default: a new IndentedHelpFormatter)
716      An instance of optparse.HelpFormatter that will be used for printing help text.
729
730.. _optparse-populating-parser:
731
732Populating the parser
733^^^^^^^^^^^^^^^^^^^^^
734
735There are several ways to populate the parser with options.  The preferred way
736is by using ``OptionParser.add_option()``, as shown in section
n737-:ref:`optparse-tutorial`, the tutorial.  :meth:`add_option` can be called in one
n752+:ref:`optparse-tutorial`.  :meth:`add_option` can be called in one of two ways:
738-of two ways:
739
n740-*   pass it an Option instance (as returned by :func:`make_option`)
n754+* pass it an Option instance (as returned by :func:`make_option`)
741
n742-*   pass it any combination of positional and keyword arguments that are
n756+* pass it any combination of positional and keyword arguments that are
743  acceptable to :func:`make_option` (i.e., to the Option constructor), and it will
744  create the Option instance for you
745
746The other alternative is to pass a list of pre-constructed Option instances to
747the OptionParser constructor, as in::
748
749   option_list = [
750       make_option("-f", "--filename",
780
781And to define an option with only a long option string::
782
783   parser.add_option("--foo", attr=value, ...)
784
785The keyword arguments define attributes of the new Option object.  The most
786important option attribute is :attr:`action`, and it largely determines which
787other attributes are relevant or required.  If you pass irrelevant option
n788-attributes, or fail to pass required ones, :mod:`optparse` raises an OptionError
n802+attributes, or fail to pass required ones, :mod:`optparse` raises an
789-exception explaining your mistake.
803+:exc:`OptionError` exception explaining your mistake.
790
n791-An options's *action* determines what :mod:`optparse` does when it encounters
n805+An option's *action* determines what :mod:`optparse` does when it encounters
792this option on the command-line.  The standard option actions hard-coded into
793:mod:`optparse` are:
794
795``store``
796   store this option's argument (default)
797
798``store_const``
799   store a constant value
861Standard option actions
862^^^^^^^^^^^^^^^^^^^^^^^
863
864The various option actions all have slightly different requirements and effects.
865Most actions have several relevant option attributes which you may specify to
866guide :mod:`optparse`'s behaviour; a few have required attributes, which you
867must specify for any option using that action.
868
n869-*   ``store`` [relevant: :attr:`type`, :attr:`dest`, ``nargs``, ``choices``]
n883+* ``store`` [relevant: :attr:`type`, :attr:`dest`, ``nargs``, ``choices``]
870
871  The option must be followed by an argument, which is converted to a value
872  according to :attr:`type` and stored in :attr:`dest`.  If ``nargs`` > 1,
873  multiple arguments will be consumed from the command line; all will be converted
874  according to :attr:`type` and stored to :attr:`dest` as a tuple.  See the
875  "Option types" section below.
876
877  If ``choices`` is supplied (a list or tuple of strings), the type defaults to
894     -f foo.txt -p 1 -3.5 4 -fbar.txt
895
896  :mod:`optparse` will set  ::
897
898     options.f = "foo.txt"
899     options.point = (1.0, -3.5, 4.0)
900     options.f = "bar.txt"
901
n902-*   ``store_const`` [required: ``const``; relevant: :attr:`dest`]
n916+* ``store_const`` [required: ``const``; relevant: :attr:`dest`]
903
904  The value ``const`` is stored in :attr:`dest`.
905
906  Example::
907
908     parser.add_option("-q", "--quiet",
909                       action="store_const", const=0, dest="verbose")
910     parser.add_option("-v", "--verbose",
911                       action="store_const", const=1, dest="verbose")
912     parser.add_option("--noisy",
913                       action="store_const", const=2, dest="verbose")
914
915  If ``"--noisy"`` is seen, :mod:`optparse` will set  ::
916
917     options.verbose = 2
918
n919-*   ``store_true`` [relevant: :attr:`dest`]
n933+* ``store_true`` [relevant: :attr:`dest`]
920
921  A special case of ``store_const`` that stores a true value to :attr:`dest`.
922
n923-*   ``store_false`` [relevant: :attr:`dest`]
n937+* ``store_false`` [relevant: :attr:`dest`]
924
925  Like ``store_true``, but stores a false value.
926
927  Example::
928
929     parser.add_option("--clobber", action="store_true", dest="clobber")
930     parser.add_option("--no-clobber", action="store_false", dest="clobber")
931
n932-*   ``append`` [relevant: :attr:`type`, :attr:`dest`, ``nargs``, ``choices``]
n946+* ``append`` [relevant: :attr:`type`, :attr:`dest`, ``nargs``, ``choices``]
933
934  The option must be followed by an argument, which is appended to the list in
935  :attr:`dest`.  If no default value for :attr:`dest` is supplied, an empty list
936  is automatically created when :mod:`optparse` first encounters this option on
937  the command-line.  If ``nargs`` > 1, multiple arguments are consumed, and a
938  tuple of length ``nargs`` is appended to :attr:`dest`.
939
940  The defaults for :attr:`type` and :attr:`dest` are the same as for the ``store``
949
950     options.tracks = []
951     options.tracks.append(int("3"))
952
953  If, a little later on, ``"--tracks=4"`` is seen, it does::
954
955     options.tracks.append(int("4"))
956
n957-*   ``append_const`` [required: ``const``; relevant: :attr:`dest`]
n971+* ``append_const`` [required: ``const``; relevant: :attr:`dest`]
958
959  Like ``store_const``, but the value ``const`` is appended to :attr:`dest`; as
n960-  with ``append``, :attr:`dest` defaults to ``None``, and an an empty list is
n974+  with ``append``, :attr:`dest` defaults to ``None``, and an empty list is
961  automatically created the first time the option is encountered.
962
n963-*   ``count`` [relevant: :attr:`dest`]
n977+* ``count`` [relevant: :attr:`dest`]
964
965  Increment the integer stored at :attr:`dest`.  If no default value is supplied,
966  :attr:`dest` is set to zero before being incremented the first time.
967
968  Example::
969
970     parser.add_option("-v", action="count", dest="verbosity")
971
974
975     options.verbosity = 0
976     options.verbosity += 1
977
978  Every subsequent occurrence of ``"-v"`` results in  ::
979
980     options.verbosity += 1
981
n982-*   ``callback`` [required: ``callback``; relevant: :attr:`type`, ``nargs``,
n996+* ``callback`` [required: ``callback``; relevant: :attr:`type`, ``nargs``,
983  ``callback_args``, ``callback_kwargs``]
984
985  Call the function specified by ``callback``, which is called as  ::
986
987     func(option, opt_str, value, parser, *args, **kwargs)
988
n989-  See section :ref:`optparse-option-callbacks`, Option Callbacks for more detail.
n1003+  See section :ref:`optparse-option-callbacks` for more detail.
990
n991-*   :attr:`help`
n1005+* :attr:`help`
992
993  Prints a complete help message for all the options in the current option parser.
994  The help message is constructed from the ``usage`` string passed to
995  OptionParser's constructor and the :attr:`help` string passed to every option.
996
997  If no :attr:`help` string is supplied for an option, it will still be listed in
998  the help message.  To omit an option entirely, use the special value
999  ``optparse.SUPPRESS_HELP``.
1022     options:
1023       -h, --help        Show this help message and exit
1024       -v                Be moderately verbose
1025       --file=FILENAME   Input file to read data from
1026
1027  After printing the help message, :mod:`optparse` terminates your process with
1028  ``sys.exit(0)``.
1029
n1030-*   ``version``
n1044+* ``version``
1031
1032  Prints the version number supplied to the OptionParser to stdout and exits.  The
1033  version number is actually formatted and printed by the ``print_version()``
1034  method of OptionParser.  Generally only relevant if the ``version`` argument is
1035  supplied to the OptionParser constructor.  As with :attr:`help` options, you
1036  will rarely create ``version`` options, since :mod:`optparse` automatically adds
1037  them when needed.
1038
1040.. _optparse-option-attributes:
1041
1042Option attributes
1043^^^^^^^^^^^^^^^^^
1044
1045The following option attributes may be passed as keyword arguments to
1046``parser.add_option()``.  If you pass an option attribute that is not relevant
1047to a particular option, or fail to pass a required option attribute,
n1048-:mod:`optparse` raises OptionError.
n1062+:mod:`optparse` raises :exc:`OptionError`.
1049
n1050-*   :attr:`action` (default: ``"store"``)
n1064+* :attr:`action` (default: ``"store"``)
1051
1052  Determines :mod:`optparse`'s behaviour when this option is seen on the command
1053  line; the available options are documented above.
1054
n1055-*   :attr:`type` (default: ``"string"``)
n1069+* :attr:`type` (default: ``"string"``)
1056
1057  The argument type expected by this option (e.g., ``"string"`` or ``"int"``); the
1058  available option types are documented below.
1059
n1060-*   :attr:`dest` (default: derived from option strings)
n1074+* :attr:`dest` (default: derived from option strings)
1061
1062  If the option's action implies writing or modifying a value somewhere, this
1063  tells :mod:`optparse` where to write it: :attr:`dest` names an attribute of the
1064  ``options`` object that :mod:`optparse` builds as it parses the command line.
1065
n1066-*   ``default`` (deprecated)
n1080+* ``default`` (deprecated)
1067
1068  The value to use for this option's destination if the option is not seen on the
1069  command line.  Deprecated; use ``parser.set_defaults()`` instead.
1070
n1071-*   ``nargs`` (default: 1)
n1085+* ``nargs`` (default: 1)
1072
1073  How many arguments of type :attr:`type` should be consumed when this option is
1074  seen.  If > 1, :mod:`optparse` will store a tuple of values to :attr:`dest`.
1075
n1076-*   ``const``
n1090+* ``const``
1077
1078  For actions that store a constant value, the constant value to store.
1079
n1080-*   ``choices``
n1094+* ``choices``
1081
1082  For options of type ``"choice"``, the list of strings the user may choose from.
1083
n1084-*   ``callback``
n1098+* ``callback``
1085
n1086-  For options with action ``"callback"``, the callable to call when this option is
n1100+  For options with action ``"callback"``, the callable to call when this option
1087-  seen.  See section :ref:`optparse-option-callbacks`, Option Callbacks for detail
1101+  is seen.  See section :ref:`optparse-option-callbacks` for detail on the
1088-  on the arguments passed to ``callable``.
1102+  arguments passed to ``callable``.
1089
n1090-*   ``callback_args``, ``callback_kwargs``
n1104+* ``callback_args``, ``callback_kwargs``
1091
1092  Additional positional and keyword arguments to pass to ``callback`` after the
1093  four standard callback arguments.
1094
n1095-*   :attr:`help`
n1109+* :attr:`help`
1096
1097  Help text to print for this option when listing all available options after the
1098  user supplies a :attr:`help` option (such as ``"--help"``). If no help text is
1099  supplied, the option will be listed without help text.  To hide this option, use
1100  the special value ``SUPPRESS_HELP``.
1101
n1102-*   ``metavar`` (default: derived from option strings)
n1116+* ``metavar`` (default: derived from option strings)
1103
1104  Stand-in for the option argument(s) to use when printing help text. See section
n1105-  :ref:`optparse-tutorial`, the tutorial for an example.
n1119+  :ref:`optparse-tutorial` for an example.
1106
1107
1108.. _optparse-standard-option-types:
1109
1110Standard option types
1111^^^^^^^^^^^^^^^^^^^^^
1112
1113:mod:`optparse` has six built-in option types: ``string``, ``int``, ``long``,
1114``choice``, ``float`` and ``complex``.  If you need to add new option types, see
n1115-section :ref:`optparse-extending-optparse`, Extending :mod:`optparse`.
n1129+section :ref:`optparse-extending-optparse`.
1116
1117Arguments to string options are not checked or converted in any way: the text on
1118the command line is stored in the destination (or passed to the callback) as-is.
1119
1120Integer arguments (type ``int`` or ``long``) are parsed as follows:
1121
n1122-*   if the number starts with ``0x``, it is parsed as a hexadecimal number
n1136+* if the number starts with ``0x``, it is parsed as a hexadecimal number
1123
n1124-*   if the number starts with ``0``, it is parsed as an octal number
n1138+* if the number starts with ``0``, it is parsed as an octal number
1125
n1126-*   if the number starts with ``0b``, is is parsed as a binary number
n1140+* if the number starts with ``0b``, it is parsed as a binary number
1127
n1128-*   otherwise, the number is parsed as a decimal number
n1142+* otherwise, the number is parsed as a decimal number
1129
1130
1131The conversion is done by calling either ``int()`` or ``long()`` with the
1132appropriate base (2, 8, 10, or 16).  If this fails, so will :mod:`optparse`,
1133although with a more useful error message.
1134
1135``float`` and ``complex`` option arguments are converted directly with
1136``float()`` and ``complex()``, with similar error-handling.
1137
1138``choice`` options are a subtype of ``string`` options.  The ``choices`` option
1139attribute (a sequence of strings) defines the set of allowed option arguments.
1140``optparse.check_choice()`` compares user-supplied option arguments against this
n1141-master list and raises OptionValueError if an invalid string is given.
n1155+master list and raises :exc:`OptionValueError` if an invalid string is given.
1142
1143
1144.. _optparse-parsing-arguments:
1145
1146Parsing arguments
1147^^^^^^^^^^^^^^^^^
1148
1149The whole point of creating and populating an OptionParser is to call its
1150:meth:`parse_args` method::
1151
n1152-   (options, args) = parser.parse_args(args=None, options=None)
n1166+   (options, args) = parser.parse_args(args=None, values=None)
1153
1154where the input parameters are
1155
1156``args``
1157   the list of arguments to process (default: ``sys.argv[1:]``)
1158
n1159-``options``
n1173+``values``
1160   object to store option arguments in (default: a new instance of optparse.Values)
1161
1162and the return values are
1163
1164``options``
1165   the same object that was passed in as ``options``, or the optparse.Values
1166   instance created by :mod:`optparse`
1167
1179traditional Unix exit status for command-line errors).
1180
1181
1182.. _optparse-querying-manipulating-option-parser:
1183
1184Querying and manipulating your option parser
1185^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1186
n1201+The default behavior of the option parser can be customized slightly,
1187-Sometimes, it's useful to poke around your option parser and see what's there.
1202+and you can also poke around your option parser and see what's there.
1188-OptionParser provides a couple of methods to help you out:
1203+OptionParser provides several methods to help you out:
1189
n1190-``has_option(opt_str)``
n1205+``disable_interspersed_args()``
1191-   Return true if the OptionParser has an option with  option string ``opt_str``
1206+  Set parsing to stop on the first non-option. Use this if you have a
1192-   (e.g., ``"-q"`` or ``"--verbose"``).
1207+  command processor which runs another command which has options of
1208+  its own and you want to make sure these options don't get
1209+  confused. For example, each command might have a different
1210+  set of options.
1211+ 
1212+``enable_interspersed_args()``
1213+  Set parsing to not stop on the first non-option, allowing
1214+  interspersing switches with command arguments.  For example,
1215+  ``"-s arg1 --long arg2"`` would return ``["arg1", "arg2"]``
1216+  as the command arguments and ``-s, --long`` as options.
1217+  This is the default behavior.
1193
1194``get_option(opt_str)``
1195   Returns the Option instance with the option string ``opt_str``, or ``None`` if
1196   no options have that option string.
1197
n1223+``has_option(opt_str)``
1224+   Return true if the OptionParser has an option with option string ``opt_str``
1225+   (e.g., ``"-q"`` or ``"--verbose"``).
1226+ 
1198``remove_option(opt_str)``
n1199-   If the OptionParser has an option corresponding to ``opt_str``, that option is
n1228+   If the :class:`OptionParser` has an option corresponding to ``opt_str``, that option is
1200   removed.  If that option provided any other option strings, all of those option
1201   strings become invalid. If ``opt_str`` does not occur in any option belonging to
n1202-   this OptionParser, raises ValueError.
n1231+   this :class:`OptionParser`, raises :exc:`ValueError`.
1203
1204
1205.. _optparse-conflicts-between-options:
1206
1207Conflicts between options
1208^^^^^^^^^^^^^^^^^^^^^^^^^
1209
1210If you're not careful, it's easy to define options with conflicting option
1225
1226or with a separate call::
1227
1228   parser.set_conflict_handler(handler)
1229
1230The available conflict handlers are:
1231
1232   ``error`` (default)
n1233-      assume option conflicts are a programming error and raise  OptionConflictError
n1262+      assume option conflicts are a programming error and raise :exc:`OptionConflictError`
1234
1235   ``resolve``
1236      resolve option conflicts intelligently (see below)
1237
1238
n1239-As an example, let's define an OptionParser that resolves conflicts
n1268+As an example, let's define an :class:`OptionParser` that resolves conflicts
1240intelligently and add conflicting options to it::
1241
1242   parser = OptionParser(conflict_handler="resolve")
1243   parser.add_option("-n", "--dry-run", ..., help="do no harm")
1244   parser.add_option("-n", "--noisy", ..., help="be noisy")
1245
1246At this point, :mod:`optparse` detects that a previously-added option is already
1247using the ``"-n"`` option string.  Since ``conflict_handler`` is ``"resolve"``,
1285
1286.. _optparse-other-methods:
1287
1288Other methods
1289^^^^^^^^^^^^^
1290
1291OptionParser supports several other public methods:
1292
n1293-*   ``set_usage(usage)``
n1322+* ``set_usage(usage)``
1294
1295  Set the usage string according to the rules described above for the ``usage``
1296  constructor keyword argument.  Passing ``None`` sets the default usage string;
1297  use ``SUPPRESS_USAGE`` to suppress a usage message.
1298
n1299-*   ``enable_interspersed_args()``, ``disable_interspersed_args()``
n1328+* ``enable_interspersed_args()``, ``disable_interspersed_args()``
1300
1301  Enable/disable positional arguments interspersed with options, similar to GNU
1302  getopt (enabled by default).  For example, if ``"-a"`` and ``"-b"`` are both
1303  simple options that take no arguments, :mod:`optparse` normally accepts this
1304  syntax::
1305
1306     prog -a arg1 -b arg2
1307
1308  and treats it as equivalent to  ::
1309
1310     prog -a -b arg1 arg2
1311
1312  To disable this feature, call ``disable_interspersed_args()``.  This restores
1313  traditional Unix syntax, where option parsing stops with the first non-option
1314  argument.
1315
n1316-*   ``set_defaults(dest=value, ...)``
n1345+* ``set_defaults(dest=value, ...)``
1317
1318  Set default values for several option destinations at once.  Using
1319  :meth:`set_defaults` is the preferred way to set default values for options,
1320  since multiple options can share the same destination.  For example, if several
1321  "mode" options all set the same destination, any one of them can set the
1322  default, and the last one wins::
1323
1324     parser.add_option("--advanced", action="store_const",
1331  To avoid this confusion, use :meth:`set_defaults`::
1332
1333     parser.set_defaults(mode="advanced")
1334     parser.add_option("--advanced", action="store_const",
1335                       dest="mode", const="advanced")
1336     parser.add_option("--novice", action="store_const",
1337                       dest="mode", const="novice")
1338
n1339-.. % $Id: reference.txt 519 2006-06-11 14:39:11Z gward $
1340- 
1341
1342.. _optparse-option-callbacks:
1343
1344Option Callbacks
1345----------------
1346
1347When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1348needs, you have two choices: extend :mod:`optparse` or define a callback option.
1349Extending :mod:`optparse` is more general, but overkill for a lot of simple
1350cases.  Quite often a simple callback is all you need.
1351
1352There are two steps to defining a callback option:
1353
n1354-*   define the option itself using the ``callback`` action
n1381+* define the option itself using the ``callback`` action
1355
n1356-*   write the callback; this is a function (or method) that takes at least four
n1383+* write the callback; this is a function (or method) that takes at least four
1357  arguments, as described below
1358
1359
1360.. _optparse-defining-callback-option:
1361
1362Defining a callback option
1363^^^^^^^^^^^^^^^^^^^^^^^^^^
1364
1463   is a dictionary of arbitrary keyword arguments supplied via ``callback_kwargs``.
1464
1465
1466.. _optparse-raising-errors-in-callback:
1467
1468Raising errors in a callback
1469^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1470
n1471-The callback function should raise OptionValueError if there are any problems
n1498+The callback function should raise :exc:`OptionValueError` if there are any problems
1472with the option or its argument(s).  :mod:`optparse` catches this and terminates
1473the program, printing the error message you supply to stderr.  Your message
1474should be clear, concise, accurate, and mention the option at fault.  Otherwise,
1475the user will have a hard time figuring out what he did wrong.
1476
1477
1478.. _optparse-callback-example-1:
1479
1480Callback example 1: trivial callback
1481^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1482
1483Here's an example of a callback option that takes no arguments, and simply
1484records that the option was seen::
1485
1486   def record_foo_seen(option, opt_str, value, parser):
n1487-       parser.saw_foo = True
n1514+       parser.values.saw_foo = True
1488
1489   parser.add_option("--foo", action="callback", callback=record_foo_seen)
1490
1491Of course, you could do that with the ``store_true`` action.
1492
1493
1494.. _optparse-callback-example-2:
1495
1581
1582Things get hairy when you want an option to take a variable number of arguments.
1583For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1584built-in capabilities for it.  And you have to deal with certain intricacies of
1585conventional Unix command-line parsing that :mod:`optparse` normally handles for
1586you.  In particular, callbacks should implement the conventional rules for bare
1587``"--"`` and ``"-"`` arguments:
1588
n1589-*   either ``"--"`` or ``"-"`` can be option arguments
n1616+* either ``"--"`` or ``"-"`` can be option arguments
1590
n1591-*   bare ``"--"`` (if not the argument to some option): halt command-line
n1618+* bare ``"--"`` (if not the argument to some option): halt command-line
1592  processing and discard the ``"--"``
1593
n1594-*   bare ``"-"`` (if not the argument to some option): halt command-line
n1621+* bare ``"-"`` (if not the argument to some option): halt command-line
1595  processing but keep the ``"-"`` (append it to ``parser.largs``)
1596
1597If you want an option that takes a variable number of arguments, there are
1598several subtle, tricky issues to worry about.  The exact implementation you
1599choose will be based on which trade-offs you're willing to make for your
1600application (which is why :mod:`optparse` doesn't support this sort of thing
1601directly).
1602
1603Nevertheless, here's a stab at a callback for an option with variable
1604arguments::
1605
n1606-   def vararg_callback(option, opt_str, value, parser):
n1633+    def vararg_callback(option, opt_str, value, parser):
1607-       assert value is None
1634+        assert value is None
1608-       done = 0
1609-       value = []
1635+        value = []
1636+ 
1637+        def floatable(str):
1638+            try:
1639+                float(str)
1640+                return True
1641+            except ValueError:
1642+                return False
1643+ 
1610-       rargs = parser.rargs
1644+        for arg in parser.rargs:
1611-       while rargs:
1645+            # stop on --foo like options
1612-           arg = rargs[0]
1613- 
1614-           # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1615-           # etc.  Note that this also stops on "-3" or "-3.0", so if
1616-           # your option takes numeric values, you will need to handle
1617-           # this.
1618-           if ((arg[:2] == "--" and len(arg) > 2) or
1646+            if arg[:2] == "--" and len(arg) > 2:
1619-               (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1620-               break
1647+                break
1621-           else:
1648+            # stop on -a, but not on -3 or -3.0
1649+            if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1650+                break
1622-               value.append(arg)
1651+            value.append(arg)
1623-               del rargs[0]
1624
n1653+        del parser.rargs[:len(value)]
1625        setattr(parser.values, option.dest, value)
1626
1627   [...]
n1628-   parser.add_option("-c", "--callback",
n1657+   parser.add_option("-c", "--callback", dest="vararg_attr",
1629-                     action="callback", callback=varargs)
1658+                     action="callback", callback=vararg_callback)
1630- 
1631-The main weakness with this particular implementation is that negative numbers
1632-in the arguments following ``"-c"`` will be interpreted as further options
1633-(probably causing an error), rather than as arguments to ``"-c"``.  Fixing this
1634-is left as an exercise for the reader.
1635- 
1636-.. % $Id: callbacks.txt 415 2004-09-30 02:26:17Z greg $
1637
1638
1639.. _optparse-extending-optparse:
1640
1641Extending :mod:`optparse`
1642-------------------------
1643
1644Since the two major controlling factors in how :mod:`optparse` interprets
1661:attr:`TYPE_CHECKER` is a dictionary mapping type names to type-checking
1662functions.  A type-checking function has the following signature::
1663
1664   def check_mytype(option, opt, value)
1665
1666where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1667(e.g., ``"-f"``), and ``value`` is the string from the command line that must be
1668checked and converted to your desired type.  ``check_mytype()`` should return an
n1669-object of the hypothetical type ``mytype``.  The value returned by a type-
n1691+object of the hypothetical type ``mytype``.  The value returned by a
1670-checking function will wind up in the OptionValues instance returned by
1692+type-checking function will wind up in the OptionValues instance returned by
1671:meth:`OptionParser.parse_args`, or be passed to a callback as the ``value``
1672parameter.
1673
n1674-Your type-checking function should raise OptionValueError if it encounters any
n1696+Your type-checking function should raise :exc:`OptionValueError` if it encounters any
1675-problems.  OptionValueError takes a single string argument, which is passed as-
1697+problems.  :exc:`OptionValueError` takes a single string argument, which is passed
1676-is to OptionParser's :meth:`error` method, which in turn prepends the program
1698+as-is to :class:`OptionParser`'s :meth:`error` method, which in turn prepends the program
1677name and the string ``"error:"`` and prints everything to stderr before
1678terminating the process.
1679
1680Here's a silly example that demonstrates adding a ``complex`` option type to
1681parse Python-style complex numbers on the command line.  (This is even sillier
1682than it used to be, because :mod:`optparse` 1.3 added built-in support for
1683complex numbers, but never mind.)
1684
1794               lvalue = value.split(",")
1795               values.ensure_value(dest, []).extend(lvalue)
1796           else:
1797               Option.take_action(
1798                   self, action, dest, opt, value, values, parser)
1799
1800Features of note:
1801
n1802-*   ``extend`` both expects a value on the command-line and stores that value
n1824+* ``extend`` both expects a value on the command-line and stores that value
1803  somewhere, so it goes in both :attr:`STORE_ACTIONS` and :attr:`TYPED_ACTIONS`
1804
n1805-*   to ensure that :mod:`optparse` assigns the default type of ``string`` to
n1827+* to ensure that :mod:`optparse` assigns the default type of ``string`` to
1806  ``extend`` actions, we put the ``extend`` action in ``ALWAYS_TYPED_ACTIONS`` as
1807  well
1808
n1809-*   :meth:`MyOption.take_action` implements just this one new action, and passes
n1831+* :meth:`MyOption.take_action` implements just this one new action, and passes
1810  control back to :meth:`Option.take_action` for the standard :mod:`optparse`
1811  actions
1812
n1813-*   ``values`` is an instance of the optparse_parser.Values class, which
n1835+* ``values`` is an instance of the optparse_parser.Values class, which
1814  provides the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1815  essentially :func:`getattr` with a safety valve; it is called as  ::
1816
1817     values.ensure_value(attr, value)
1818
1819  If the ``attr`` attribute of ``values`` doesn't exist or is None, then
1820  ensure_value() first sets it to ``value``, and then returns 'value. This is very
1821  handy for actions like ``extend``, ``append``, and ``count``, all of which
1822  accumulate data in a variable and expect that variable to be of a certain type
1823  (a list for the first two, an integer for the latter).  Using
1824  :meth:`ensure_value` means that scripts using your action don't have to worry
1825  about setting a default value for the option destinations in question; they can
1826  just leave the default as None and :meth:`ensure_value` will take care of
1827  getting it right when it's needed.
t1828- 
1829-.. % $Id: extending.txt 517 2006-06-10 16:18:11Z gward $
1830- 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op