Issue #7270: Add some dedicated unit tests for multi-thread synchronization
[python.git] / Doc / library / optparse.rst
blob5ac11c3c4e6b85bfd1007fc51306f73600ab14f3
1 :mod:`optparse` --- More powerful command line option parser
2 ============================================================
4 .. module:: optparse
5    :synopsis: More convenient, flexible, and powerful command-line parsing library.
6 .. moduleauthor:: Greg Ward <gward@python.net>
9 .. versionadded:: 2.3
11 .. sectionauthor:: Greg Ward <gward@python.net>
14 :mod:`optparse` is a more convenient, flexible, and powerful library for parsing
15 command-line options than the old :mod:`getopt` module.  :mod:`optparse` uses a
16 more declarative style of command-line parsing: you create an instance of
17 :class:`OptionParser`, populate it with options, and parse the command
18 line. :mod:`optparse` allows users to specify options in the conventional
19 GNU/POSIX syntax, and additionally generates usage and help messages for you.
21 Here's an example of using :mod:`optparse` in a simple script::
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")
32    (options, args) = parser.parse_args()
34 With these few lines of code, users of your script can now do the "usual thing"
35 on the command-line, for example::
37    <yourscript> --file=outfile -q
39 As it parses the command line, :mod:`optparse` sets attributes of the
40 ``options`` object returned by :meth:`parse_args` based on user-supplied
41 command-line values.  When :meth:`parse_args` returns from parsing this command
42 line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
43 ``False``.  :mod:`optparse` supports both long and short options, allows short
44 options to be merged together, and allows options to be associated with their
45 arguments in a variety of ways.  Thus, the following command lines are all
46 equivalent to the above example::
48    <yourscript> -f outfile --quiet
49    <yourscript> --quiet --file outfile
50    <yourscript> -q -foutfile
51    <yourscript> -qfoutfile
53 Additionally, users can run one of  ::
55    <yourscript> -h
56    <yourscript> --help
58 and :mod:`optparse` will print out a brief summary of your script's options::
60    usage: <yourscript> [options]
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
67 where the value of *yourscript* is determined at runtime (normally from
68 ``sys.argv[0]``).
71 .. _optparse-background:
73 Background
74 ----------
76 :mod:`optparse` was explicitly designed to encourage the creation of programs
77 with straightforward, conventional command-line interfaces.  To that end, it
78 supports only the most common command-line syntax and semantics conventionally
79 used under Unix.  If you are unfamiliar with these conventions, read this
80 section to acquaint yourself with them.
83 .. _optparse-terminology:
85 Terminology
86 ^^^^^^^^^^^
88 argument
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".
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:]``".
99 option
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`.
109    Some other option syntaxes that the world has seen include:
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)
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)
118    * a plus sign followed by a single letter, or a few letters, or a word, e.g.
119      ``"+f"``, ``"+rgb"``
121    * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
122      ``"/file"``
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.
129 option 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::
135       -f foo
136       --file foo
138    or included in the same argument::
140       -ffoo
141       --file=foo
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.
151 positional 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.
156 required 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`.
164 For example, consider this hypothetical command-line::
166    prog -v --report /tmp/report.txt foo bar
168 ``"-v"`` and ``"--report"`` are both options.  Assuming that :option:`--report`
169 takes one argument, ``"/tmp/report.txt"`` is an option argument.  ``"foo"`` and
170 ``"bar"`` are positional arguments.
173 .. _optparse-what-options-for:
175 What are options for?
176 ^^^^^^^^^^^^^^^^^^^^^
178 Options are used to provide extra information to tune or customize the execution
179 of a program.  In case it wasn't clear, options are usually *optional*.  A
180 program should be able to run just fine with no options whatsoever.  (Pick a
181 random program from the Unix or GNU toolsets.  Can it run without any options at
182 all and still make sense?  The main exceptions are ``find``, ``tar``, and
183 ``dd``\ ---all of which are mutant oddballs that have been rightly criticized
184 for their non-standard syntax and confusing interfaces.)
186 Lots of people want their programs to have "required options".  Think about it.
187 If it's required, then it's *not optional*!  If there is a piece of information
188 that your program absolutely requires in order to run successfully, that's what
189 positional arguments are for.
191 As an example of good command-line interface design, consider the humble ``cp``
192 utility, for copying files.  It doesn't make much sense to try to copy files
193 without supplying a destination and at least one source. Hence, ``cp`` fails if
194 you run it with no arguments.  However, it has a flexible, useful syntax that
195 does not require any options at all::
197    cp SOURCE DEST
198    cp SOURCE ... DEST-DIR
200 You can get pretty far with just that.  Most ``cp`` implementations provide a
201 bunch of options to tweak exactly how the files are copied: you can preserve
202 mode and modification time, avoid following symlinks, ask before clobbering
203 existing 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
205 directory.
208 .. _optparse-what-positional-arguments-for:
210 What are positional arguments for?
211 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
213 Positional arguments are for those pieces of information that your program
214 absolutely, positively requires to run.
216 A good user interface should have as few absolute requirements as possible.  If
217 your program requires 17 distinct pieces of information in order to run
218 successfully, it doesn't much matter *how* you get that information from the
219 user---most people will give up and walk away before they successfully run the
220 program.  This applies whether the user interface is a command-line, a
221 configuration file, or a GUI: if you make that many demands on your users, most
222 of them will simply give up.
224 In short, try to minimize the amount of information that users are absolutely
225 required to supply---use sensible defaults whenever possible.  Of course, you
226 also want to make your programs reasonably flexible.  That's what options are
227 for.  Again, it doesn't matter if they are entries in a config file, widgets in
228 the "Preferences" dialog of a GUI, or command-line options---the more options
229 you implement, the more flexible your program is, and the more complicated its
230 implementation becomes.  Too much flexibility has drawbacks as well, of course;
231 too many options can overwhelm users and make your code much harder to maintain.
234 .. _optparse-tutorial:
236 Tutorial
237 --------
239 While :mod:`optparse` is quite flexible and powerful, it's also straightforward
240 to use in most cases.  This section covers the code patterns that are common to
241 any :mod:`optparse`\ -based program.
243 First, you need to import the OptionParser class; then, early in the main
244 program, create an OptionParser instance::
246    from optparse import OptionParser
247    [...]
248    parser = OptionParser()
250 Then you can start defining options.  The basic syntax is::
252    parser.add_option(opt_str, ...,
253                      attr=value, ...)
255 Each option has one or more option strings, such as ``"-f"`` or ``"--file"``,
256 and several option attributes that tell :mod:`optparse` what to expect and what
257 to do when it encounters that option on the command line.
259 Typically, each option will have one short option string and one long option
260 string, e.g.::
262    parser.add_option("-f", "--file", ...)
264 You're free to define as many short option strings and as many long option
265 strings as you like (including zero), as long as there is at least one option
266 string overall.
268 The option strings passed to :meth:`add_option` are effectively labels for the
269 option defined by that call.  For brevity, we will frequently refer to
270 *encountering an option* on the command line; in reality, :mod:`optparse`
271 encounters *option strings* and looks up options from them.
273 Once all of your options are defined, instruct :mod:`optparse` to parse your
274 program's command line::
276    (options, args) = parser.parse_args()
278 (If you like, you can pass a custom argument list to :meth:`parse_args`, but
279 that's rarely necessary: by default it uses ``sys.argv[1:]``.)
281 :meth:`parse_args` returns two values:
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
288 * ``args``, the list of positional arguments leftover after parsing options
290 This 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
293 most fundamental.
296 .. _optparse-understanding-option-actions:
298 Understanding option actions
299 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
301 Actions tell :mod:`optparse` what to do when it encounters an option on the
302 command line.  There is a fixed set of actions hard-coded into :mod:`optparse`;
303 adding new actions is an advanced topic covered in section
304 :ref:`optparse-extending-optparse`.  Most actions tell :mod:`optparse` to store
305 a value in some variable---for example, take a string from the command line and
306 store it in an attribute of ``options``.
308 If you don't specify an option action, :mod:`optparse` defaults to ``store``.
311 .. _optparse-store-action:
313 The store action
314 ^^^^^^^^^^^^^^^^
316 The most common option action is ``store``, which tells :mod:`optparse` to take
317 the next argument (or the remainder of the current argument), ensure that it is
318 of the correct type, and store it to your chosen destination.
320 For example::
322    parser.add_option("-f", "--file",
323                      action="store", type="string", dest="filename")
325 Now let's make up a fake command line and ask :mod:`optparse` to parse it::
327    args = ["-f", "foo.txt"]
328    (options, args) = parser.parse_args(args)
330 When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
331 argument, ``"foo.txt"``, and stores it in ``options.filename``.  So, after this
332 call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
334 Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
335 Here's an option that expects an integer argument::
337    parser.add_option("-n", type="int", dest="num")
339 Note that this option has no long option string, which is perfectly acceptable.
340 Also, there's no explicit action, since the default is ``store``.
342 Let's parse another fake command-line.  This time, we'll jam the option argument
343 right up against the option: since ``"-n42"`` (one argument) is equivalent to
344 ``"-n 42"`` (two arguments), the code ::
346    (options, args) = parser.parse_args(["-n42"])
347    print options.num
349 will print ``"42"``.
351 If you don't specify a type, :mod:`optparse` assumes ``string``.  Combined with
352 the fact that the default action is ``store``, that means our first example can
353 be a lot shorter::
355    parser.add_option("-f", "--file", dest="filename")
357 If you don't supply a destination, :mod:`optparse` figures out a sensible
358 default 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
360 long option strings, :mod:`optparse` looks at the first short option string: the
361 default destination for ``"-f"`` is ``f``.
363 :mod:`optparse` also includes built-in ``long`` and ``complex`` types.  Adding
364 types is covered in section :ref:`optparse-extending-optparse`.
367 .. _optparse-handling-boolean-options:
369 Handling boolean (flag) options
370 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
372 Flag 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``
375 flag that is turned on with ``"-v"`` and off with ``"-q"``::
377    parser.add_option("-v", action="store_true", dest="verbose")
378    parser.add_option("-q", action="store_false", dest="verbose")
380 Here we have two different options with the same destination, which is perfectly
381 OK.  (It just means you have to be a bit careful when setting default values---
382 see below.)
384 When :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``.
389 .. _optparse-other-actions:
391 Other actions
392 ^^^^^^^^^^^^^
394 Some other actions supported by :mod:`optparse` are:
396 ``"store_const"``
397    store a constant value
399 ``"append"``
400    append this option's argument to a list
402 ``"count"``
403    increment a counter by one
405 ``"callback"``
406    call a specified function
408 These are covered in section :ref:`optparse-reference-guide`, Reference Guide
409 and section :ref:`optparse-option-callbacks`.
412 .. _optparse-default-values:
414 Default values
415 ^^^^^^^^^^^^^^
417 All of the above examples involve setting some variable (the "destination") when
418 certain command-line options are seen.  What happens if those options are never
419 seen?  Since we didn't supply any defaults, they are all set to ``None``.  This
420 is usually fine, but sometimes you want more control.  :mod:`optparse` lets you
421 supply a default value for each destination, which is assigned before the
422 command line is parsed.
424 First, 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::
427    parser.add_option("-v", action="store_true", dest="verbose", default=True)
428    parser.add_option("-q", action="store_false", dest="verbose")
430 Since default values apply to the *destination* rather than to any particular
431 option, and these two options happen to have the same destination, this is
432 exactly equivalent::
434    parser.add_option("-v", action="store_true", dest="verbose")
435    parser.add_option("-q", action="store_false", dest="verbose", default=True)
437 Consider this::
439    parser.add_option("-v", action="store_true", dest="verbose", default=False)
440    parser.add_option("-q", action="store_false", dest="verbose", default=True)
442 Again, the default value for ``verbose`` will be ``True``: the last default
443 value supplied for any particular destination is the one that counts.
445 A clearer way to specify default values is the :meth:`set_defaults` method of
446 OptionParser, which you can call at any time before calling :meth:`parse_args`::
448    parser.set_defaults(verbose=True)
449    parser.add_option(...)
450    (options, args) = parser.parse_args()
452 As before, the last value specified for a given option destination is the one
453 that counts.  For clarity, try to use one method or the other of setting default
454 values, not both.
457 .. _optparse-generating-help:
459 Generating help
460 ^^^^^^^^^^^^^^^
462 :mod:`optparse`'s ability to generate help and usage text automatically is
463 useful for creating user-friendly command-line interfaces.  All you have to do
464 is supply a :attr:`~Option.help` value for each option, and optionally a short
465 usage message for your whole program.  Here's an OptionParser populated with
466 user-friendly (documented) options::
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]")
483 If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
484 command-line, or if you just call :meth:`parser.print_help`, it prints the
485 following to standard output::
487    usage: <yourscript> [options] arg1 arg2
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]
498 (If the help output is triggered by a help option, :mod:`optparse` exits after
499 printing the help text.)
501 There's a lot going on here to help :mod:`optparse` generate the best possible
502 help message:
504 * the script defines its own usage message::
506      usage = "usage: %prog [options] arg1 arg2"
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.
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.
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.
520 * options that take a value indicate this fact in their automatically-generated
521   help message, e.g. for the "mode" option::
523      -m MODE, --mode=MODE
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::
532      -f FILE, --filename=FILE
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.
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``.
546 When dealing with many options, it is convenient to group these options for
547 better help output.  An :class:`OptionParser` can contain several option groups,
548 each of which can contain several options.
550 Continuing with the parser defined above, adding an :class:`OptionGroup` to a
551 parser is easy::
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)
559 This would result in the following help output::
561     usage:  [options] arg1 arg2
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'
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.
576 .. _optparse-printing-version-string:
578 Printing a version string
579 ^^^^^^^^^^^^^^^^^^^^^^^^^
581 Similar to the brief usage string, :mod:`optparse` can also print a version
582 string for your program.  You have to supply the string as the ``version``
583 argument to OptionParser::
585    parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
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`
589 automatically adds a ``"--version"`` option to your parser. If it encounters
590 this option on the command line, it expands your ``version`` string (by
591 replacing ``"%prog"``), prints it to stdout, and exits.
593 For example, if your script is called ``/usr/bin/foo``::
595    $ /usr/bin/foo --version
596    foo 1.0
599 .. _optparse-how-optparse-handles-errors:
601 How :mod:`optparse` handles errors
602 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
604 There are two broad classes of errors that :mod:`optparse` has to worry about:
605 programmer errors and user errors.  Programmer errors are usually erroneous
606 calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
607 option attributes, missing option attributes, etc.  These are dealt with in the
608 usual way: raise an exception (either :exc:`optparse.OptionError` or
609 :exc:`TypeError`) and let the program crash.
611 Handling user errors is much more important, since they are guaranteed to happen
612 no matter how stable your code is.  :mod:`optparse` can automatically detect
613 some user errors, such as bad option arguments (passing ``"-n 4x"`` where
614 :option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
615 of the command line, where :option:`-n` takes an argument of any type).  Also,
616 you can call :func:`OptionParser.error` to signal an application-defined error
617 condition::
619    (options, args) = parser.parse_args()
620    [...]
621    if options.a and options.b:
622        parser.error("options -a and -b are mutually exclusive")
624 In either case, :mod:`optparse` handles the error the same way: it prints the
625 program's usage message and an error message to standard error and exits with
626 error status 2.
628 Consider the first example above, where the user passes ``"4x"`` to an option
629 that takes an integer::
631    $ /usr/bin/foo -n 4x
632    usage: foo [options]
634    foo: error: option -n: invalid integer value: '4x'
636 Or, where the user fails to pass a value at all::
638    $ /usr/bin/foo -n
639    usage: foo [options]
641    foo: error: -n option requires an argument
643 :mod:`optparse`\ -generated error messages take care always to mention the
644 option involved in the error; be sure to do the same when calling
645 :func:`OptionParser.error` from your application code.
647 If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
648 you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
649 and/or :meth:`~OptionParser.error` methods.
652 .. _optparse-putting-it-all-together:
654 Putting it all together
655 ^^^^^^^^^^^^^^^^^^^^^^^
657 Here's what :mod:`optparse`\ -based scripts usually look like::
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        [...]
678    if __name__ == "__main__":
679        main()
682 .. _optparse-reference-guide:
684 Reference Guide
685 ---------------
688 .. _optparse-creating-parser:
690 Creating the parser
691 ^^^^^^^^^^^^^^^^^^^
693 The first step in using :mod:`optparse` is to create an OptionParser instance.
695 .. class:: OptionParser(...)
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.
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`.
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.
715    ``option_class`` (default: optparse.Option)
716       Class to use when adding options to the parser in :meth:`add_option`.
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``.
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`.
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).
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.
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.
744    ``prog``
745       The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
746       instead of ``os.path.basename(sys.argv[0])``.
750 .. _optparse-populating-parser:
752 Populating the parser
753 ^^^^^^^^^^^^^^^^^^^^^
755 There are several ways to populate the parser with options.  The preferred way
756 is 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:
759 * pass it an Option instance (as returned by :func:`make_option`)
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
765 The other alternative is to pass a list of pre-constructed Option instances to
766 the OptionParser constructor, as in::
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)
776 (:func:`make_option` is a factory function for creating Option instances;
777 currently 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`
779 will pick the right class to instantiate.  Do not instantiate Option directly.)
782 .. _optparse-defining-options:
784 Defining options
785 ^^^^^^^^^^^^^^^^
787 Each Option instance represents a set of synonymous command-line option strings,
788 e.g. :option:`-f` and :option:`--file`.  You can specify any number of short or
789 long option strings, but you must specify at least one overall option string.
791 The canonical way to create an :class:`Option` instance is with the
792 :meth:`add_option` method of :class:`OptionParser`.
794 .. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
796    To define an option with only a short option string::
798       parser.add_option("-f", attr=value, ...)
800    And to define an option with only a long option string::
802       parser.add_option("--foo", attr=value, ...)
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.
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:
814    ``"store"``
815       store this option's argument (default)
817    ``"store_const"``
818       store a constant value
820    ``"store_true"``
821       store a true value
823    ``"store_false"``
824       store a false value
826    ``"append"``
827       append this option's argument to a list
829    ``"append_const"``
830       append a constant value to a list
832    ``"count"``
833       increment a counter by one
835    ``"callback"``
836       call a specified function
838    ``"help"``
839       print a usage message including all options and the documentation for them
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`.)
845 As 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
848 arguments (and various other values) are stored as attributes of this object,
849 according to the :attr:`~Option.dest` (destination) option attribute.
851 For example, when you call ::
853    parser.parse_args()
855 one of the first things :mod:`optparse` does is create the ``options`` object::
857    options = Values()
859 If one of the options in this parser is defined with ::
861    parser.add_option("-f", "--file", action="store", type="string", dest="filename")
863 and the command-line being parsed includes any of the following::
865    -ffoo
866    -f foo
867    --file=foo
868    --file foo
870 then :mod:`optparse`, on seeing this option, will do the equivalent of ::
872    options.filename = "foo"
874 The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
875 as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
876 one that makes sense for *all* options.
879 .. _optparse-option-attributes:
881 Option attributes
882 ^^^^^^^^^^^^^^^^^
884 The following option attributes may be passed as keyword arguments to
885 :meth:`OptionParser.add_option`.  If you pass an option attribute that is not
886 relevant to a particular option, or fail to pass a required option attribute,
887 :mod:`optparse` raises :exc:`OptionError`.
889 .. attribute:: Option.action
891    (default: ``"store"``)
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>`.
897 .. attribute:: Option.type
899    (default: ``"string"``)
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>`.
905 .. attribute:: Option.dest
907    (default: derived from option strings)
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.
914 .. attribute:: Option.default
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`.
919 .. attribute:: Option.nargs
921    (default: 1)
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`.
927 .. attribute:: Option.const
929    For actions that store a constant value, the constant value to store.
931 .. attribute:: Option.choices
933    For options of type ``"choice"``, the list of strings the user may choose
934    from.
936 .. attribute:: Option.callback
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.
942 .. attribute:: Option.callback_args
943                Option.callback_kwargs
945    Additional positional and keyword arguments to pass to ``callback`` after the
946    four standard callback arguments.
948 .. attribute:: Option.help
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`.
955 .. attribute:: Option.metavar
957    (default: derived from option strings)
959    Stand-in for the option argument(s) to use when printing help text.  See
960    section :ref:`optparse-tutorial` for an example.
963 .. _optparse-standard-option-actions:
965 Standard option actions
966 ^^^^^^^^^^^^^^^^^^^^^^^
968 The various option actions all have slightly different requirements and effects.
969 Most actions have several relevant option attributes which you may specify to
970 guide :mod:`optparse`'s behaviour; a few have required attributes, which you
971 must specify for any option using that action.
973 * ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
974   :attr:`~Option.nargs`, :attr:`~Option.choices`]
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.
983   If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
984   defaults to ``"choice"``.
986   If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
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``).
993   Example::
995      parser.add_option("-f")
996      parser.add_option("-p", type="float", nargs=3, dest="point")
998   As it parses the command line ::
1000      -f foo.txt -p 1 -3.5 4 -fbar.txt
1002   :mod:`optparse` will set ::
1004      options.f = "foo.txt"
1005      options.point = (1.0, -3.5, 4.0)
1006      options.f = "bar.txt"
1008 * ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1009   :attr:`~Option.dest`]
1011   The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
1013   Example::
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")
1022   If ``"--noisy"`` is seen, :mod:`optparse` will set  ::
1024      options.verbose = 2
1026 * ``"store_true"`` [relevant: :attr:`~Option.dest`]
1028   A special case of ``"store_const"`` that stores a true value to
1029   :attr:`~Option.dest`.
1031 * ``"store_false"`` [relevant: :attr:`~Option.dest`]
1033   Like ``"store_true"``, but stores a false value.
1035   Example::
1037      parser.add_option("--clobber", action="store_true", dest="clobber")
1038      parser.add_option("--no-clobber", action="store_false", dest="clobber")
1040 * ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1041   :attr:`~Option.nargs`, :attr:`~Option.choices`]
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`.
1050   The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1051   for the ``"store"`` action.
1053   Example::
1055      parser.add_option("-t", "--tracks", action="append", type="int")
1057   If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
1058   of::
1060      options.tracks = []
1061      options.tracks.append(int("3"))
1063   If, a little later on, ``"--tracks=4"`` is seen, it does::
1065      options.tracks.append(int("4"))
1067 * ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1068   :attr:`~Option.dest`]
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.
1075 * ``"count"`` [relevant: :attr:`~Option.dest`]
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.
1081   Example::
1083      parser.add_option("-v", action="count", dest="verbosity")
1085   The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
1086   equivalent of::
1088      options.verbosity = 0
1089      options.verbosity += 1
1091   Every subsequent occurrence of ``"-v"`` results in  ::
1093      options.verbosity += 1
1095 * ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1096   :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1097   :attr:`~Option.callback_kwargs`]
1099   Call the function specified by :attr:`~Option.callback`, which is called as ::
1101      func(option, opt_str, value, parser, *args, **kwargs)
1103   See section :ref:`optparse-option-callbacks` for more detail.
1105 * ``"help"``
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.
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`.
1116   :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1117   OptionParsers, so you do not normally need to create one.
1119   Example::
1121      from optparse import OptionParser, SUPPRESS_HELP
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)
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)
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"``)::
1138      usage: foo.py [options]
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
1145   After printing the help message, :mod:`optparse` terminates your process with
1146   ``sys.exit(0)``.
1148 * ``"version"``
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.
1158 .. _optparse-standard-option-types:
1160 Standard option types
1161 ^^^^^^^^^^^^^^^^^^^^^
1163 :mod:`optparse` has six built-in option types: ``"string"``, ``"int"``,
1164 ``"long"``, ``"choice"``, ``"float"`` and ``"complex"``.  If you need to add new
1165 option types, see section :ref:`optparse-extending-optparse`.
1167 Arguments to string options are not checked or converted in any way: the text on
1168 the command line is stored in the destination (or passed to the callback) as-is.
1170 Integer arguments (type ``"int"`` or ``"long"``) are parsed as follows:
1172 * if the number starts with ``0x``, it is parsed as a hexadecimal number
1174 * if the number starts with ``0``, it is parsed as an octal number
1176 * if the number starts with ``0b``, it is parsed as a binary number
1178 * otherwise, the number is parsed as a decimal number
1181 The conversion is done by calling either :func:`int` or :func:`long` with the
1182 appropriate base (2, 8, 10, or 16).  If this fails, so will :mod:`optparse`,
1183 although with a more useful error message.
1185 ``"float"`` and ``"complex"`` option arguments are converted directly with
1186 :func:`float` and :func:`complex`, with similar error-handling.
1188 ``"choice"`` options are a subtype of ``"string"`` options.  The
1189 :attr:`~Option.choices`` option attribute (a sequence of strings) defines the
1190 set of allowed option arguments.  :func:`optparse.check_choice` compares
1191 user-supplied option arguments against this master list and raises
1192 :exc:`OptionValueError` if an invalid string is given.
1195 .. _optparse-parsing-arguments:
1197 Parsing arguments
1198 ^^^^^^^^^^^^^^^^^
1200 The whole point of creating and populating an OptionParser is to call its
1201 :meth:`parse_args` method::
1203    (options, args) = parser.parse_args(args=None, values=None)
1205 where the input parameters are
1207 ``args``
1208    the list of arguments to process (default: ``sys.argv[1:]``)
1210 ``values``
1211    object to store option arguments in (default: a new instance of
1212    :class:`optparse.Values`)
1214 and the return values are
1216 ``options``
1217    the same object that was passed in as ``values``, or the optparse.Values
1218    instance created by :mod:`optparse`
1220 ``args``
1221    the leftover positional arguments after all options have been processed
1223 The 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
1225 for every option argument stored to an option destination) and returned by
1226 :meth:`parse_args`.
1228 If :meth:`parse_args` encounters any errors in the argument list, it calls the
1229 OptionParser's :meth:`error` method with an appropriate end-user error message.
1230 This ultimately terminates your process with an exit status of 2 (the
1231 traditional Unix exit status for command-line errors).
1234 .. _optparse-querying-manipulating-option-parser:
1236 Querying and manipulating your option parser
1237 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1239 The default behavior of the option parser can be customized slightly, and you
1240 can also poke around your option parser and see what's there.  OptionParser
1241 provides several methods to help you out:
1243 .. method:: OptionParser.disable_interspersed_args()
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::
1249       prog -a arg1 -b arg2
1251    and treats it as equivalent to  ::
1253       prog -a -b arg1 arg2
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.
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.
1263 .. method:: OptionParser.enable_interspersed_args()
1265    Set parsing to not stop on the first non-option, allowing interspersing
1266    switches with command arguments.  This is the default behavior.
1268 .. method:: OptionParser.get_option(opt_str)
1270    Returns the Option instance with the option string *opt_str*, or ``None`` if
1271    no options have that option string.
1273 .. method:: OptionParser.has_option(opt_str)
1275    Return true if the OptionParser has an option with option string *opt_str*
1276    (e.g., ``"-q"`` or ``"--verbose"``).
1278 .. method:: OptionParser.remove_option(opt_str)
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`.
1286 .. _optparse-conflicts-between-options:
1288 Conflicts between options
1289 ^^^^^^^^^^^^^^^^^^^^^^^^^
1291 If you're not careful, it's easy to define options with conflicting option
1292 strings::
1294    parser.add_option("-n", "--dry-run", ...)
1295    [...]
1296    parser.add_option("-n", "--noisy", ...)
1298 (This is particularly true if you've defined your own OptionParser subclass with
1299 some standard options.)
1301 Every time you add an option, :mod:`optparse` checks for conflicts with existing
1302 options.  If it finds any, it invokes the current conflict-handling mechanism.
1303 You can set the conflict-handling mechanism either in the constructor::
1305    parser = OptionParser(..., conflict_handler=handler)
1307 or with a separate call::
1309    parser.set_conflict_handler(handler)
1311 The available conflict handlers are:
1313    ``"error"`` (default)
1314       assume option conflicts are a programming error and raise
1315       :exc:`OptionConflictError`
1317    ``"resolve"``
1318       resolve option conflicts intelligently (see below)
1321 As an example, let's define an :class:`OptionParser` that resolves conflicts
1322 intelligently and add conflicting options to it::
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")
1328 At this point, :mod:`optparse` detects that a previously-added option is already
1329 using the ``"-n"`` option string.  Since ``conflict_handler`` is ``"resolve"``,
1330 it resolves the situation by removing ``"-n"`` from the earlier option's list of
1331 option strings.  Now ``"--dry-run"`` is the only way for the user to activate
1332 that option.  If the user asks for help, the help message will reflect that::
1334    options:
1335      --dry-run     do no harm
1336      [...]
1337      -n, --noisy   be noisy
1339 It's possible to whittle away the option strings for a previously-added option
1340 until there are none left, and the user has no way of invoking that option from
1341 the command-line.  In that case, :mod:`optparse` removes that option completely,
1342 so it doesn't show up in help text or anywhere else. Carrying on with our
1343 existing OptionParser::
1345    parser.add_option("--dry-run", ..., help="new dry-run option")
1347 At this point, the original :option:`-n/--dry-run` option is no longer
1348 accessible, so :mod:`optparse` removes it, leaving this help text::
1350    options:
1351      [...]
1352      -n, --noisy   be noisy
1353      --dry-run     new dry-run option
1356 .. _optparse-cleanup:
1358 Cleanup
1359 ^^^^^^^
1361 OptionParser instances have several cyclic references.  This should not be a
1362 problem for Python's garbage collector, but you may wish to break the cyclic
1363 references explicitly by calling :meth:`~OptionParser.destroy` on your
1364 OptionParser once you are done with it.  This is particularly useful in
1365 long-running applications where large object graphs are reachable from your
1366 OptionParser.
1369 .. _optparse-other-methods:
1371 Other methods
1372 ^^^^^^^^^^^^^
1374 OptionParser supports several other public methods:
1376 .. method:: OptionParser.set_usage(usage)
1378    Set the usage string according to the rules described above for the ``usage``
1379    constructor keyword argument.  Passing ``None`` sets the default usage
1380    string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
1382 .. method:: OptionParser.set_defaults(dest=value, ...)
1384    Set default values for several option destinations at once.  Using
1385    :meth:`set_defaults` is the preferred way to set default values for options,
1386    since multiple options can share the same destination.  For example, if
1387    several "mode" options all set the same destination, any one of them can set
1388    the default, and the last one wins::
1390       parser.add_option("--advanced", action="store_const",
1391                         dest="mode", const="advanced",
1392                         default="novice")    # overridden below
1393       parser.add_option("--novice", action="store_const",
1394                         dest="mode", const="novice",
1395                         default="advanced")  # overrides above setting
1397    To avoid this confusion, use :meth:`set_defaults`::
1399       parser.set_defaults(mode="advanced")
1400       parser.add_option("--advanced", action="store_const",
1401                         dest="mode", const="advanced")
1402       parser.add_option("--novice", action="store_const",
1403                         dest="mode", const="novice")
1406 .. _optparse-option-callbacks:
1408 Option Callbacks
1409 ----------------
1411 When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1412 needs, you have two choices: extend :mod:`optparse` or define a callback option.
1413 Extending :mod:`optparse` is more general, but overkill for a lot of simple
1414 cases.  Quite often a simple callback is all you need.
1416 There are two steps to defining a callback option:
1418 * define the option itself using the ``"callback"`` action
1420 * write the callback; this is a function (or method) that takes at least four
1421   arguments, as described below
1424 .. _optparse-defining-callback-option:
1426 Defining a callback option
1427 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1429 As always, the easiest way to define a callback option is by using the
1430 :meth:`OptionParser.add_option` method.  Apart from :attr:`~Option.action`, the
1431 only option attribute you must specify is ``callback``, the function to call::
1433    parser.add_option("-c", action="callback", callback=my_callback)
1435 ``callback`` is a function (or other callable object), so you must have already
1436 defined ``my_callback()`` when you create this callback option. In this simple
1437 case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,
1438 which usually means that the option takes no arguments---the mere presence of
1439 :option:`-c` on the command-line is all it needs to know.  In some
1440 circumstances, though, you might want your callback to consume an arbitrary
1441 number of command-line arguments.  This is where writing callbacks gets tricky;
1442 it's covered later in this section.
1444 :mod:`optparse` always passes four particular arguments to your callback, and it
1445 will only pass additional arguments if you specify them via
1446 :attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`.  Thus, the
1447 minimal callback function signature is::
1449    def my_callback(option, opt, value, parser):
1451 The four arguments to a callback are described below.
1453 There are several other option attributes that you can supply when you define a
1454 callback option:
1456 :attr:`~Option.type`
1457    has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1458    instructs :mod:`optparse` to consume one argument and convert it to
1459    :attr:`~Option.type`.  Rather than storing the converted value(s) anywhere,
1460    though, :mod:`optparse` passes it to your callback function.
1462 :attr:`~Option.nargs`
1463    also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
1464    consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1465    :attr:`~Option.type`.  It then passes a tuple of converted values to your
1466    callback.
1468 :attr:`~Option.callback_args`
1469    a tuple of extra positional arguments to pass to the callback
1471 :attr:`~Option.callback_kwargs`
1472    a dictionary of extra keyword arguments to pass to the callback
1475 .. _optparse-how-callbacks-called:
1477 How callbacks are called
1478 ^^^^^^^^^^^^^^^^^^^^^^^^
1480 All callbacks are called as follows::
1482    func(option, opt_str, value, parser, *args, **kwargs)
1484 where
1486 ``option``
1487    is the Option instance that's calling the callback
1489 ``opt_str``
1490    is the option string seen on the command-line that's triggering the callback.
1491    (If an abbreviated long option was used, ``opt_str`` will be the full,
1492    canonical option string---e.g. if the user puts ``"--foo"`` on the
1493    command-line as an abbreviation for ``"--foobar"``, then ``opt_str`` will be
1494    ``"--foobar"``.)
1496 ``value``
1497    is the argument to this option seen on the command-line.  :mod:`optparse` will
1498    only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1499    the type implied by the option's type.  If :attr:`~Option.type` for this option is
1500    ``None`` (no argument expected), then ``value`` will be ``None``.  If :attr:`~Option.nargs`
1501    > 1, ``value`` will be a tuple of values of the appropriate type.
1503 ``parser``
1504    is the OptionParser instance driving the whole thing, mainly useful because
1505    you can access some other interesting data through its instance attributes:
1507    ``parser.largs``
1508       the current list of leftover arguments, ie. arguments that have been
1509       consumed but are neither options nor option arguments. Feel free to modify
1510       ``parser.largs``, e.g. by adding more arguments to it.  (This list will
1511       become ``args``, the second return value of :meth:`parse_args`.)
1513    ``parser.rargs``
1514       the current list of remaining arguments, ie. with ``opt_str`` and
1515       ``value`` (if applicable) removed, and only the arguments following them
1516       still there.  Feel free to modify ``parser.rargs``, e.g. by consuming more
1517       arguments.
1519    ``parser.values``
1520       the object where option values are by default stored (an instance of
1521       optparse.OptionValues).  This lets callbacks use the same mechanism as the
1522       rest of :mod:`optparse` for storing option values; you don't need to mess
1523       around with globals or closures.  You can also access or modify the
1524       value(s) of any options already encountered on the command-line.
1526 ``args``
1527    is a tuple of arbitrary positional arguments supplied via the
1528    :attr:`~Option.callback_args` option attribute.
1530 ``kwargs``
1531    is a dictionary of arbitrary keyword arguments supplied via
1532    :attr:`~Option.callback_kwargs`.
1535 .. _optparse-raising-errors-in-callback:
1537 Raising errors in a callback
1538 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1540 The callback function should raise :exc:`OptionValueError` if there are any
1541 problems with the option or its argument(s).  :mod:`optparse` catches this and
1542 terminates the program, printing the error message you supply to stderr.  Your
1543 message should be clear, concise, accurate, and mention the option at fault.
1544 Otherwise, the user will have a hard time figuring out what he did wrong.
1547 .. _optparse-callback-example-1:
1549 Callback example 1: trivial callback
1550 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1552 Here's an example of a callback option that takes no arguments, and simply
1553 records that the option was seen::
1555    def record_foo_seen(option, opt_str, value, parser):
1556        parser.values.saw_foo = True
1558    parser.add_option("--foo", action="callback", callback=record_foo_seen)
1560 Of course, you could do that with the ``"store_true"`` action.
1563 .. _optparse-callback-example-2:
1565 Callback example 2: check option order
1566 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1568 Here's a slightly more interesting example: record the fact that ``"-a"`` is
1569 seen, but blow up if it comes after ``"-b"`` in the command-line.  ::
1571    def check_order(option, opt_str, value, parser):
1572        if parser.values.b:
1573            raise OptionValueError("can't use -a after -b")
1574        parser.values.a = 1
1575    [...]
1576    parser.add_option("-a", action="callback", callback=check_order)
1577    parser.add_option("-b", action="store_true", dest="b")
1580 .. _optparse-callback-example-3:
1582 Callback example 3: check option order (generalized)
1583 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1585 If you want to re-use this callback for several similar options (set a flag, but
1586 blow up if ``"-b"`` has already been seen), it needs a bit of work: the error
1587 message and the flag that it sets must be generalized.  ::
1589    def check_order(option, opt_str, value, parser):
1590        if parser.values.b:
1591            raise OptionValueError("can't use %s after -b" % opt_str)
1592        setattr(parser.values, option.dest, 1)
1593    [...]
1594    parser.add_option("-a", action="callback", callback=check_order, dest='a')
1595    parser.add_option("-b", action="store_true", dest="b")
1596    parser.add_option("-c", action="callback", callback=check_order, dest='c')
1599 .. _optparse-callback-example-4:
1601 Callback example 4: check arbitrary condition
1602 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1604 Of course, you could put any condition in there---you're not limited to checking
1605 the values of already-defined options.  For example, if you have options that
1606 should not be called when the moon is full, all you have to do is this::
1608    def check_moon(option, opt_str, value, parser):
1609        if is_moon_full():
1610            raise OptionValueError("%s option invalid when moon is full"
1611                                   % opt_str)
1612        setattr(parser.values, option.dest, 1)
1613    [...]
1614    parser.add_option("--foo",
1615                      action="callback", callback=check_moon, dest="foo")
1617 (The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1620 .. _optparse-callback-example-5:
1622 Callback example 5: fixed arguments
1623 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1625 Things get slightly more interesting when you define callback options that take
1626 a fixed number of arguments.  Specifying that a callback option takes arguments
1627 is similar to defining a ``"store"`` or ``"append"`` option: if you define
1628 :attr:`~Option.type`, then the option takes one argument that must be
1629 convertible to that type; if you further define :attr:`~Option.nargs`, then the
1630 option takes :attr:`~Option.nargs` arguments.
1632 Here's an example that just emulates the standard ``"store"`` action::
1634    def store_value(option, opt_str, value, parser):
1635        setattr(parser.values, option.dest, value)
1636    [...]
1637    parser.add_option("--foo",
1638                      action="callback", callback=store_value,
1639                      type="int", nargs=3, dest="foo")
1641 Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1642 them to integers for you; all you have to do is store them.  (Or whatever;
1643 obviously you don't need a callback for this example.)
1646 .. _optparse-callback-example-6:
1648 Callback example 6: variable arguments
1649 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1651 Things get hairy when you want an option to take a variable number of arguments.
1652 For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1653 built-in capabilities for it.  And you have to deal with certain intricacies of
1654 conventional Unix command-line parsing that :mod:`optparse` normally handles for
1655 you.  In particular, callbacks should implement the conventional rules for bare
1656 ``"--"`` and ``"-"`` arguments:
1658 * either ``"--"`` or ``"-"`` can be option arguments
1660 * bare ``"--"`` (if not the argument to some option): halt command-line
1661   processing and discard the ``"--"``
1663 * bare ``"-"`` (if not the argument to some option): halt command-line
1664   processing but keep the ``"-"`` (append it to ``parser.largs``)
1666 If you want an option that takes a variable number of arguments, there are
1667 several subtle, tricky issues to worry about.  The exact implementation you
1668 choose will be based on which trade-offs you're willing to make for your
1669 application (which is why :mod:`optparse` doesn't support this sort of thing
1670 directly).
1672 Nevertheless, here's a stab at a callback for an option with variable
1673 arguments::
1675     def vararg_callback(option, opt_str, value, parser):
1676         assert value is None
1677         value = []
1679         def floatable(str):
1680             try:
1681                 float(str)
1682                 return True
1683             except ValueError:
1684                 return False
1686         for arg in parser.rargs:
1687             # stop on --foo like options
1688             if arg[:2] == "--" and len(arg) > 2:
1689                 break
1690             # stop on -a, but not on -3 or -3.0
1691             if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1692                 break
1693             value.append(arg)
1695         del parser.rargs[:len(value)]
1696         setattr(parser.values, option.dest, value)
1698    [...]
1699    parser.add_option("-c", "--callback", dest="vararg_attr",
1700                      action="callback", callback=vararg_callback)
1703 .. _optparse-extending-optparse:
1705 Extending :mod:`optparse`
1706 -------------------------
1708 Since the two major controlling factors in how :mod:`optparse` interprets
1709 command-line options are the action and type of each option, the most likely
1710 direction of extension is to add new actions and new types.
1713 .. _optparse-adding-new-types:
1715 Adding new types
1716 ^^^^^^^^^^^^^^^^
1718 To add new types, you need to define your own subclass of :mod:`optparse`'s
1719 :class:`Option` class.  This class has a couple of attributes that define
1720 :mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
1722 .. attribute:: Option.TYPES
1724    A tuple of type names; in your subclass, simply define a new tuple
1725    :attr:`TYPES` that builds on the standard one.
1727 .. attribute:: Option.TYPE_CHECKER
1729    A dictionary mapping type names to type-checking functions.  A type-checking
1730    function has the following signature::
1732       def check_mytype(option, opt, value)
1734    where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1735    (e.g., ``"-f"``), and ``value`` is the string from the command line that must
1736    be checked and converted to your desired type.  ``check_mytype()`` should
1737    return an object of the hypothetical type ``mytype``.  The value returned by
1738    a type-checking function will wind up in the OptionValues instance returned
1739    by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1740    ``value`` parameter.
1742    Your type-checking function should raise :exc:`OptionValueError` if it
1743    encounters any problems.  :exc:`OptionValueError` takes a single string
1744    argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1745    method, which in turn prepends the program name and the string ``"error:"``
1746    and prints everything to stderr before terminating the process.
1748 Here's a silly example that demonstrates adding a ``"complex"`` option type to
1749 parse Python-style complex numbers on the command line.  (This is even sillier
1750 than it used to be, because :mod:`optparse` 1.3 added built-in support for
1751 complex numbers, but never mind.)
1753 First, the necessary imports::
1755    from copy import copy
1756    from optparse import Option, OptionValueError
1758 You need to define your type-checker first, since it's referred to later (in the
1759 :attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
1761    def check_complex(option, opt, value):
1762        try:
1763            return complex(value)
1764        except ValueError:
1765            raise OptionValueError(
1766                "option %s: invalid complex value: %r" % (opt, value))
1768 Finally, the Option subclass::
1770    class MyOption (Option):
1771        TYPES = Option.TYPES + ("complex",)
1772        TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1773        TYPE_CHECKER["complex"] = check_complex
1775 (If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
1776 up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1777 Option class.  This being Python, nothing stops you from doing that except good
1778 manners and common sense.)
1780 That's it!  Now you can write a script that uses the new option type just like
1781 any other :mod:`optparse`\ -based script, except you have to instruct your
1782 OptionParser to use MyOption instead of Option::
1784    parser = OptionParser(option_class=MyOption)
1785    parser.add_option("-c", type="complex")
1787 Alternately, you can build your own option list and pass it to OptionParser; if
1788 you don't use :meth:`add_option` in the above way, you don't need to tell
1789 OptionParser which option class to use::
1791    option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1792    parser = OptionParser(option_list=option_list)
1795 .. _optparse-adding-new-actions:
1797 Adding new actions
1798 ^^^^^^^^^^^^^^^^^^
1800 Adding new actions is a bit trickier, because you have to understand that
1801 :mod:`optparse` has a couple of classifications for actions:
1803 "store" actions
1804    actions that result in :mod:`optparse` storing a value to an attribute of the
1805    current OptionValues instance; these options require a :attr:`~Option.dest`
1806    attribute to be supplied to the Option constructor.
1808 "typed" actions
1809    actions that take a value from the command line and expect it to be of a
1810    certain type; or rather, a string that can be converted to a certain type.
1811    These options require a :attr:`~Option.type` attribute to the Option
1812    constructor.
1814 These are overlapping sets: some default "store" actions are ``"store"``,
1815 ``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1816 actions are ``"store"``, ``"append"``, and ``"callback"``.
1818 When you add an action, you need to categorize it by listing it in at least one
1819 of the following class attributes of Option (all are lists of strings):
1821 .. attribute:: Option.ACTIONS
1823    All actions must be listed in ACTIONS.
1825 .. attribute:: Option.STORE_ACTIONS
1827    "store" actions are additionally listed here.
1829 .. attribute:: Option.TYPED_ACTIONS
1831    "typed" actions are additionally listed here.
1833 .. attribute:: Option.ALWAYS_TYPED_ACTIONS
1835    Actions that always take a type (i.e. whose options always take a value) are
1836    additionally listed here.  The only effect of this is that :mod:`optparse`
1837    assigns the default type, ``"string"``, to options with no explicit type
1838    whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
1840 In order to actually implement your new action, you must override Option's
1841 :meth:`take_action` method and add a case that recognizes your action.
1843 For example, let's add an ``"extend"`` action.  This is similar to the standard
1844 ``"append"`` action, but instead of taking a single value from the command-line
1845 and appending it to an existing list, ``"extend"`` will take multiple values in
1846 a single comma-delimited string, and extend an existing list with them.  That
1847 is, if ``"--names"`` is an ``"extend"`` option of type ``"string"``, the command
1848 line ::
1850    --names=foo,bar --names blah --names ding,dong
1852 would result in a list  ::
1854    ["foo", "bar", "blah", "ding", "dong"]
1856 Again we define a subclass of Option::
1858    class MyOption (Option):
1860        ACTIONS = Option.ACTIONS + ("extend",)
1861        STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1862        TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1863        ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1865        def take_action(self, action, dest, opt, value, values, parser):
1866            if action == "extend":
1867                lvalue = value.split(",")
1868                values.ensure_value(dest, []).extend(lvalue)
1869            else:
1870                Option.take_action(
1871                    self, action, dest, opt, value, values, parser)
1873 Features of note:
1875 * ``"extend"`` both expects a value on the command-line and stores that value
1876   somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1877   :attr:`~Option.TYPED_ACTIONS`.
1879 * to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1880   ``"extend"`` actions, we put the ``"extend"`` action in
1881   :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
1883 * :meth:`MyOption.take_action` implements just this one new action, and passes
1884   control back to :meth:`Option.take_action` for the standard :mod:`optparse`
1885   actions.
1887 * ``values`` is an instance of the optparse_parser.Values class, which provides
1888   the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1889   essentially :func:`getattr` with a safety valve; it is called as ::
1891      values.ensure_value(attr, value)
1893   If the ``attr`` attribute of ``values`` doesn't exist or is None, then
1894   ensure_value() first sets it to ``value``, and then returns 'value. This is
1895   very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
1896   of which accumulate data in a variable and expect that variable to be of a
1897   certain type (a list for the first two, an integer for the latter).  Using
1898   :meth:`ensure_value` means that scripts using your action don't have to worry
1899   about setting a default value for the option destinations in question; they
1900   can just leave the default as None and :meth:`ensure_value` will take care of
1901   getting it right when it's needed.