1:mod:`optparse` --- Parser for command line options
2===================================================
3
4.. module:: optparse
5   :synopsis: Command-line option parsing library.
6   :deprecated:
7
8.. moduleauthor:: Greg Ward <[email protected]>
9.. sectionauthor:: Greg Ward <[email protected]>
10
11**Source code:** :source:`Lib/optparse.py`
12
13.. deprecated:: 3.2
14   The :mod:`optparse` module is deprecated and will not be developed further;
15   development will continue with the :mod:`argparse` module.
16
17--------------
18
19:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
20command-line options than the old :mod:`getopt` module.  :mod:`optparse` uses a
21more declarative style of command-line parsing: you create an instance of
22:class:`OptionParser`, populate it with options, and parse the command
23line. :mod:`optparse` allows users to specify options in the conventional
24GNU/POSIX syntax, and additionally generates usage and help messages for you.
25
26Here's an example of using :mod:`optparse` in a simple script::
27
28   from optparse import OptionParser
29   ...
30   parser = OptionParser()
31   parser.add_option("-f", "--file", dest="filename",
32                     help="write report to FILE", metavar="FILE")
33   parser.add_option("-q", "--quiet",
34                     action="store_false", dest="verbose", default=True,
35                     help="don't print status messages to stdout")
36
37   (options, args) = parser.parse_args()
38
39With these few lines of code, users of your script can now do the "usual thing"
40on the command-line, for example::
41
42   <yourscript> --file=outfile -q
43
44As it parses the command line, :mod:`optparse` sets attributes of the
45``options`` object returned by :meth:`parse_args` based on user-supplied
46command-line values.  When :meth:`parse_args` returns from parsing this command
47line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
48``False``.  :mod:`optparse` supports both long and short options, allows short
49options to be merged together, and allows options to be associated with their
50arguments in a variety of ways.  Thus, the following command lines are all
51equivalent to the above example::
52
53   <yourscript> -f outfile --quiet
54   <yourscript> --quiet --file outfile
55   <yourscript> -q -foutfile
56   <yourscript> -qfoutfile
57
58Additionally, users can run one of the following ::
59
60   <yourscript> -h
61   <yourscript> --help
62
63and :mod:`optparse` will print out a brief summary of your script's options:
64
65.. code-block:: text
66
67   Usage: <yourscript> [options]
68
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
77
78.. _optparse-background:
79
80Background
81----------
82
83:mod:`optparse` was explicitly designed to encourage the creation of programs
84with straightforward, conventional command-line interfaces.  To that end, it
85supports only the most common command-line syntax and semantics conventionally
86used under Unix.  If you are unfamiliar with these conventions, read this
87section to acquaint yourself with them.
88
89
90.. _optparse-terminology:
91
92Terminology
93^^^^^^^^^^^
94
95argument
96   a string entered on the command-line, and passed by the shell to ``execl()``
97   or ``execv()``.  In Python, arguments are elements of ``sys.argv[1:]``
98   (``sys.argv[0]`` is the name of the program being executed).  Unix shells
99   also use the term "word".
100
101   It is occasionally desirable to substitute an argument list other than
102   ``sys.argv[1:]``, so you should read "argument" as "an element of
103   ``sys.argv[1:]``, or of some other list provided as a substitute for
104   ``sys.argv[1:]``".
105
106option
107   an argument used to supply extra information to guide or customize the
108   execution of a program.  There are many different syntaxes for options; the
109   traditional Unix syntax is a hyphen ("-") followed by a single letter,
110   e.g. ``-x`` or ``-F``.  Also, traditional Unix syntax allows multiple
111   options to be merged into a single argument, e.g. ``-x -F`` is equivalent
112   to ``-xF``.  The GNU project introduced ``--`` followed by a series of
113   hyphen-separated words, e.g. ``--file`` or ``--dry-run``.  These are the
114   only two option syntaxes provided by :mod:`optparse`.
115
116   Some other option syntaxes that the world has seen include:
117
118   * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
119     as multiple options merged into a single argument)
120
121   * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
122     equivalent to the previous syntax, but they aren't usually seen in the same
123     program)
124
125   * a plus sign followed by a single letter, or a few letters, or a word, e.g.
126     ``+f``, ``+rgb``
127
128   * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``,
129     ``/file``
130
131   These option syntaxes are not supported by :mod:`optparse`, and they never
132   will be.  This is deliberate: the first three are non-standard on any
133   environment, and the last only makes sense if you're exclusively targeting
134   Windows or certain legacy platforms (e.g. VMS, MS-DOS).
135
136option argument
137   an argument that follows an option, is closely associated with that option,
138   and is consumed from the argument list when that option is. With
139   :mod:`optparse`, option arguments may either be in a separate argument from
140   their option:
141
142   .. code-block:: text
143
144      -f foo
145      --file foo
146
147   or included in the same argument:
148
149   .. code-block:: text
150
151      -ffoo
152      --file=foo
153
154   Typically, a given option either takes an argument or it doesn't. Lots of
155   people want an "optional option arguments" feature, meaning that some options
156   will take an argument if they see it, and won't if they don't.  This is
157   somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
158   an optional argument and ``-b`` is another option entirely, how do we
159   interpret ``-ab``?  Because of this ambiguity, :mod:`optparse` does not
160   support this feature.
161
162positional argument
163   something leftover in the argument list after options have been parsed, i.e.
164   after options and their arguments have been parsed and removed from the
165   argument list.
166
167required option
168   an option that must be supplied on the command-line; note that the phrase
169   "required option" is self-contradictory in English.  :mod:`optparse` doesn't
170   prevent you from implementing required options, but doesn't give you much
171   help at it either.
172
173For example, consider this hypothetical command-line::
174
175   prog -v --report report.txt foo bar
176
177``-v`` and ``--report`` are both options.  Assuming that ``--report``
178takes one argument, ``report.txt`` is an option argument.  ``foo`` and
179``bar`` are positional arguments.
180
181
182.. _optparse-what-options-for:
183
184What are options for?
185^^^^^^^^^^^^^^^^^^^^^
186
187Options are used to provide extra information to tune or customize the execution
188of a program.  In case it wasn't clear, options are usually *optional*.  A
189program should be able to run just fine with no options whatsoever.  (Pick a
190random program from the Unix or GNU toolsets.  Can it run without any options at
191all and still make sense?  The main exceptions are ``find``, ``tar``, and
192``dd``\ ---all of which are mutant oddballs that have been rightly criticized
193for their non-standard syntax and confusing interfaces.)
194
195Lots of people want their programs to have "required options".  Think about it.
196If it's required, then it's *not optional*!  If there is a piece of information
197that your program absolutely requires in order to run successfully, that's what
198positional arguments are for.
199
200As an example of good command-line interface design, consider the humble ``cp``
201utility, for copying files.  It doesn't make much sense to try to copy files
202without supplying a destination and at least one source. Hence, ``cp`` fails if
203you run it with no arguments.  However, it has a flexible, useful syntax that
204does not require any options at all::
205
206   cp SOURCE DEST
207   cp SOURCE ... DEST-DIR
208
209You can get pretty far with just that.  Most ``cp`` implementations provide a
210bunch of options to tweak exactly how the files are copied: you can preserve
211mode and modification time, avoid following symlinks, ask before clobbering
212existing files, etc.  But none of this distracts from the core mission of
213``cp``, which is to copy either one file to another, or several files to another
214directory.
215
216
217.. _optparse-what-positional-arguments-for:
218
219What are positional arguments for?
220^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
221
222Positional arguments are for those pieces of information that your program
223absolutely, positively requires to run.
224
225A good user interface should have as few absolute requirements as possible.  If
226your program requires 17 distinct pieces of information in order to run
227successfully, it doesn't much matter *how* you get that information from the
228user---most people will give up and walk away before they successfully run the
229program.  This applies whether the user interface is a command-line, a
230configuration file, or a GUI: if you make that many demands on your users, most
231of them will simply give up.
232
233In short, try to minimize the amount of information that users are absolutely
234required to supply---use sensible defaults whenever possible.  Of course, you
235also want to make your programs reasonably flexible.  That's what options are
236for.  Again, it doesn't matter if they are entries in a config file, widgets in
237the "Preferences" dialog of a GUI, or command-line options---the more options
238you implement, the more flexible your program is, and the more complicated its
239implementation becomes.  Too much flexibility has drawbacks as well, of course;
240too many options can overwhelm users and make your code much harder to maintain.
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
250any :mod:`optparse`\ -based program.
251
252First, you need to import the OptionParser class; then, early in the main
253program, create an OptionParser instance::
254
255   from optparse import OptionParser
256   ...
257   parser = OptionParser()
258
259Then you can start defining options.  The basic syntax is::
260
261   parser.add_option(opt_str, ...,
262                     attr=value, ...)
263
264Each option has one or more option strings, such as ``-f`` or ``--file``,
265and several option attributes that tell :mod:`optparse` what to expect and what
266to do when it encounters that option on the command line.
267
268Typically, each option will have one short option string and one long option
269string, e.g.::
270
271   parser.add_option("-f", "--file", ...)
272
273You're free to define as many short option strings and as many long option
274strings as you like (including zero), as long as there is at least one option
275string overall.
276
277The option strings passed to :meth:`OptionParser.add_option` are effectively
278labels for the
279option defined by that call.  For brevity, we will frequently refer to
280*encountering an option* on the command line; in reality, :mod:`optparse`
281encounters *option strings* and looks up options from them.
282
283Once all of your options are defined, instruct :mod:`optparse` to parse your
284program's command line::
285
286   (options, args) = parser.parse_args()
287
288(If you like, you can pass a custom argument list to :meth:`parse_args`, but
289that's rarely necessary: by default it uses ``sys.argv[1:]``.)
290
291:meth:`parse_args` returns two values:
292
293* ``options``, an object containing values for all of your options---e.g. if
294  ``--file`` takes a single string argument, then ``options.file`` will be the
295  filename supplied by the user, or ``None`` if the user did not supply that
296  option
297
298* ``args``, the list of positional arguments leftover after parsing options
299
300This tutorial section only covers the four most important option attributes:
301:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
302(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
303most fundamental.
304
305
306.. _optparse-understanding-option-actions:
307
308Understanding option actions
309^^^^^^^^^^^^^^^^^^^^^^^^^^^^
310
311Actions tell :mod:`optparse` what to do when it encounters an option on the
312command line.  There is a fixed set of actions hard-coded into :mod:`optparse`;
313adding new actions is an advanced topic covered in section
314:ref:`optparse-extending-optparse`.  Most actions tell :mod:`optparse` to store
315a value in some variable---for example, take a string from the command line and
316store it in an attribute of ``options``.
317
318If you don't specify an option action, :mod:`optparse` defaults to ``store``.
319
320
321.. _optparse-store-action:
322
323The store action
324^^^^^^^^^^^^^^^^
325
326The most common option action is ``store``, which tells :mod:`optparse` to take
327the next argument (or the remainder of the current argument), ensure that it is
328of the correct type, and store it to your chosen destination.
329
330For example::
331
332   parser.add_option("-f", "--file",
333                     action="store", type="string", dest="filename")
334
335Now let's make up a fake command line and ask :mod:`optparse` to parse it::
336
337   args = ["-f", "foo.txt"]
338   (options, args) = parser.parse_args(args)
339
340When :mod:`optparse` sees the option string ``-f``, it consumes the next
341argument, ``foo.txt``, and stores it in ``options.filename``.  So, after this
342call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
343
344Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
345Here's an option that expects an integer argument::
346
347   parser.add_option("-n", type="int", dest="num")
348
349Note that this option has no long option string, which is perfectly acceptable.
350Also, there's no explicit action, since the default is ``store``.
351
352Let's parse another fake command-line.  This time, we'll jam the option argument
353right up against the option: since ``-n42`` (one argument) is equivalent to
354``-n 42`` (two arguments), the code ::
355
356   (options, args) = parser.parse_args(["-n42"])
357   print(options.num)
358
359will print ``42``.
360
361If you don't specify a type, :mod:`optparse` assumes ``string``.  Combined with
362the fact that the default action is ``store``, that means our first example can
363be a lot shorter::
364
365   parser.add_option("-f", "--file", dest="filename")
366
367If you don't supply a destination, :mod:`optparse` figures out a sensible
368default from the option strings: if the first long option string is
369``--foo-bar``, then the default destination is ``foo_bar``.  If there are no
370long option strings, :mod:`optparse` looks at the first short option string: the
371default destination for ``-f`` is ``f``.
372
373:mod:`optparse` also includes the built-in ``complex`` type.  Adding
374types is covered in section :ref:`optparse-extending-optparse`.
375
376
377.. _optparse-handling-boolean-options:
378
379Handling boolean (flag) options
380^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
381
382Flag options---set a variable to true or false when a particular option is
383seen---are quite common.  :mod:`optparse` supports them with two separate actions,
384``store_true`` and ``store_false``.  For example, you might have a ``verbose``
385flag that is turned on with ``-v`` and off with ``-q``::
386
387   parser.add_option("-v", action="store_true", dest="verbose")
388   parser.add_option("-q", action="store_false", dest="verbose")
389
390Here we have two different options with the same destination, which is perfectly
391OK.  (It just means you have to be a bit careful when setting default
392values---see below.)
393
394When :mod:`optparse` encounters ``-v`` on the command line, it sets
395``options.verbose`` to ``True``; when it encounters ``-q``,
396``options.verbose`` is set to ``False``.
397
398
399.. _optparse-other-actions:
400
401Other actions
402^^^^^^^^^^^^^
403
404Some other actions supported by :mod:`optparse` are:
405
406``"store_const"``
407   store a constant value, pre-set via :attr:`Option.const`
408
409``"append"``
410   append this option's argument to a list
411
412``"count"``
413   increment a counter by one
414
415``"callback"``
416   call a specified function
417
418These are covered in section :ref:`optparse-reference-guide`,
419and section :ref:`optparse-option-callbacks`.
420
421
422.. _optparse-default-values:
423
424Default values
425^^^^^^^^^^^^^^
426
427All of the above examples involve setting some variable (the "destination") when
428certain command-line options are seen.  What happens if those options are never
429seen?  Since we didn't supply any defaults, they are all set to ``None``.  This
430is usually fine, but sometimes you want more control.  :mod:`optparse` lets you
431supply a default value for each destination, which is assigned before the
432command line is parsed.
433
434First, consider the verbose/quiet example.  If we want :mod:`optparse` to set
435``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
436
437   parser.add_option("-v", action="store_true", dest="verbose", default=True)
438   parser.add_option("-q", action="store_false", dest="verbose")
439
440Since default values apply to the *destination* rather than to any particular
441option, and these two options happen to have the same destination, this is
442exactly equivalent::
443
444   parser.add_option("-v", action="store_true", dest="verbose")
445   parser.add_option("-q", action="store_false", dest="verbose", default=True)
446
447Consider this::
448
449   parser.add_option("-v", action="store_true", dest="verbose", default=False)
450   parser.add_option("-q", action="store_false", dest="verbose", default=True)
451
452Again, the default value for ``verbose`` will be ``True``: the last default
453value supplied for any particular destination is the one that counts.
454
455A clearer way to specify default values is the :meth:`set_defaults` method of
456OptionParser, which you can call at any time before calling :meth:`parse_args`::
457
458   parser.set_defaults(verbose=True)
459   parser.add_option(...)
460   (options, args) = parser.parse_args()
461
462As before, the last value specified for a given option destination is the one
463that counts.  For clarity, try to use one method or the other of setting default
464values, not both.
465
466
467.. _optparse-generating-help:
468
469Generating help
470^^^^^^^^^^^^^^^
471
472:mod:`optparse`'s ability to generate help and usage text automatically is
473useful for creating user-friendly command-line interfaces.  All you have to do
474is supply a :attr:`~Option.help` value for each option, and optionally a short
475usage message for your whole program.  Here's an OptionParser populated with
476user-friendly (documented) options::
477
478   usage = "usage: %prog [options] arg1 arg2"
479   parser = OptionParser(usage=usage)
480   parser.add_option("-v", "--verbose",
481                     action="store_true", dest="verbose", default=True,
482                     help="make lots of noise [default]")
483   parser.add_option("-q", "--quiet",
484                     action="store_false", dest="verbose",
485                     help="be vewwy quiet (I'm hunting wabbits)")
486   parser.add_option("-f", "--filename",
487                     metavar="FILE", help="write output to FILE")
488   parser.add_option("-m", "--mode",
489                     default="intermediate",
490                     help="interaction mode: novice, intermediate, "
491                          "or expert [default: %default]")
492
493If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
494command-line, or if you just call :meth:`parser.print_help`, it prints the
495following to standard output:
496
497.. code-block:: text
498
499   Usage: <yourscript> [options] arg1 arg2
500
501   Options:
502     -h, --help            show this help message and exit
503     -v, --verbose         make lots of noise [default]
504     -q, --quiet           be vewwy quiet (I'm hunting wabbits)
505     -f FILE, --filename=FILE
506                           write output to FILE
507     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
508                           expert [default: intermediate]
509
510(If the help output is triggered by a help option, :mod:`optparse` exits after
511printing the help text.)
512
513There's a lot going on here to help :mod:`optparse` generate the best possible
514help message:
515
516* the script defines its own usage message::
517
518     usage = "usage: %prog [options] arg1 arg2"
519
520  :mod:`optparse` expands ``%prog`` in the usage string to the name of the
521  current program, i.e. ``os.path.basename(sys.argv[0])``.  The expanded string
522  is then printed before the detailed option help.
523
524  If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
525  default: ``"Usage: %prog [options]"``, which is fine if your script doesn't
526  take any positional arguments.
527
528* every option defines a help string, and doesn't worry about
529  line-wrapping---\ :mod:`optparse` takes care of wrapping lines and making
530  the help output look good.
531
532* options that take a value indicate this fact in their automatically generated
533  help message, e.g. for the "mode" option::
534
535     -m MODE, --mode=MODE
536
537  Here, "MODE" is called the meta-variable: it stands for the argument that the
538  user is expected to supply to ``-m``/``--mode``.  By default,
539  :mod:`optparse` converts the destination variable name to uppercase and uses
540  that for the meta-variable.  Sometimes, that's not what you want---for
541  example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
542  resulting in this automatically generated option description::
543
544     -f FILE, --filename=FILE
545
546  This is important for more than just saving space, though: the manually
547  written help text uses the meta-variable ``FILE`` to clue the user in that
548  there's a connection between the semi-formal syntax ``-f FILE`` and the informal
549  semantic description "write output to FILE". This is a simple but effective
550  way to make your help text a lot clearer and more useful for end users.
551
552* options that have a default value can include ``%default`` in the help
553  string---\ :mod:`optparse` will replace it with :func:`str` of the option's
554  default value.  If an option has no default value (or the default value is
555  ``None``), ``%default`` expands to ``none``.
556
557Grouping Options
558++++++++++++++++
559
560When dealing with many options, it is convenient to group these options for
561better help output.  An :class:`OptionParser` can contain several option groups,
562each of which can contain several options.
563
564An option group is obtained using the class :class:`OptionGroup`:
565
566.. class:: OptionGroup(parser, title, description=None)
567
568   where
569
570   * parser is the :class:`OptionParser` instance the group will be inserted in
571     to
572   * title is the group title
573   * description, optional, is a long description of the group
574
575:class:`OptionGroup` inherits from :class:`OptionContainer` (like
576:class:`OptionParser`) and so the :meth:`add_option` method can be used to add
577an option to the group.
578
579Once all the options are declared, using the :class:`OptionParser` method
580:meth:`add_option_group` the group is added to the previously defined parser.
581
582Continuing with the parser defined in the previous section, adding an
583:class:`OptionGroup` to a parser is easy::
584
585    group = OptionGroup(parser, "Dangerous Options",
586                        "Caution: use these options at your own risk.  "
587                        "It is believed that some of them bite.")
588    group.add_option("-g", action="store_true", help="Group option.")
589    parser.add_option_group(group)
590
591This would result in the following help output:
592
593.. code-block:: text
594
595   Usage: <yourscript> [options] arg1 arg2
596
597   Options:
598     -h, --help            show this help message and exit
599     -v, --verbose         make lots of noise [default]
600     -q, --quiet           be vewwy quiet (I'm hunting wabbits)
601     -f FILE, --filename=FILE
602                           write output to FILE
603     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
604                           expert [default: intermediate]
605
606     Dangerous Options:
607       Caution: use these options at your own risk.  It is believed that some
608       of them bite.
609
610       -g                  Group option.
611
612A bit more complete example might involve using more than one group: still
613extending the previous example::
614
615    group = OptionGroup(parser, "Dangerous Options",
616                        "Caution: use these options at your own risk.  "
617                        "It is believed that some of them bite.")
618    group.add_option("-g", action="store_true", help="Group option.")
619    parser.add_option_group(group)
620
621    group = OptionGroup(parser, "Debug Options")
622    group.add_option("-d", "--debug", action="store_true",
623                     help="Print debug information")
624    group.add_option("-s", "--sql", action="store_true",
625                     help="Print all SQL statements executed")
626    group.add_option("-e", action="store_true", help="Print every action done")
627    parser.add_option_group(group)
628
629that results in the following output:
630
631.. code-block:: text
632
633   Usage: <yourscript> [options] arg1 arg2
634
635   Options:
636     -h, --help            show this help message and exit
637     -v, --verbose         make lots of noise [default]
638     -q, --quiet           be vewwy quiet (I'm hunting wabbits)
639     -f FILE, --filename=FILE
640                           write output to FILE
641     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
642                           [default: intermediate]
643
644     Dangerous Options:
645       Caution: use these options at your own risk.  It is believed that some
646       of them bite.
647
648       -g                  Group option.
649
650     Debug Options:
651       -d, --debug         Print debug information
652       -s, --sql           Print all SQL statements executed
653       -e                  Print every action done
654
655Another interesting method, in particular when working programmatically with
656option groups is:
657
658.. method:: OptionParser.get_option_group(opt_str)
659
660   Return the :class:`OptionGroup` to which the short or long option
661   string *opt_str* (e.g. ``'-o'`` or ``'--option'``) belongs. If
662   there's no such :class:`OptionGroup`, return ``None``.
663
664.. _optparse-printing-version-string:
665
666Printing a version string
667^^^^^^^^^^^^^^^^^^^^^^^^^
668
669Similar to the brief usage string, :mod:`optparse` can also print a version
670string for your program.  You have to supply the string as the ``version``
671argument to OptionParser::
672
673   parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
674
675``%prog`` is expanded just like it is in ``usage``.  Apart from that,
676``version`` can contain anything you like.  When you supply it, :mod:`optparse`
677automatically adds a ``--version`` option to your parser. If it encounters
678this option on the command line, it expands your ``version`` string (by
679replacing ``%prog``), prints it to stdout, and exits.
680
681For example, if your script is called ``/usr/bin/foo``:
682
683.. code-block:: shell-session
684
685   $ /usr/bin/foo --version
686   foo 1.0
687
688The following two methods can be used to print and get the ``version`` string:
689
690.. method:: OptionParser.print_version(file=None)
691
692   Print the version message for the current program (``self.version``) to
693   *file* (default stdout).  As with :meth:`print_usage`, any occurrence
694   of ``%prog`` in ``self.version`` is replaced with the name of the current
695   program.  Does nothing if ``self.version`` is empty or undefined.
696
697.. method:: OptionParser.get_version()
698
699   Same as :meth:`print_version` but returns the version string instead of
700   printing it.
701
702
703.. _optparse-how-optparse-handles-errors:
704
705How :mod:`optparse` handles errors
706^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
707
708There are two broad classes of errors that :mod:`optparse` has to worry about:
709programmer errors and user errors.  Programmer errors are usually erroneous
710calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
711option attributes, missing option attributes, etc.  These are dealt with in the
712usual way: raise an exception (either :exc:`optparse.OptionError` or
713:exc:`TypeError`) and let the program crash.
714
715Handling user errors is much more important, since they are guaranteed to happen
716no matter how stable your code is.  :mod:`optparse` can automatically detect
717some user errors, such as bad option arguments (passing ``-n 4x`` where
718``-n`` takes an integer argument), missing arguments (``-n`` at the end
719of the command line, where ``-n`` takes an argument of any type).  Also,
720you can call :func:`OptionParser.error` to signal an application-defined error
721condition::
722
723   (options, args) = parser.parse_args()
724   ...
725   if options.a and options.b:
726       parser.error("options -a and -b are mutually exclusive")
727
728In either case, :mod:`optparse` handles the error the same way: it prints the
729program's usage message and an error message to standard error and exits with
730error status 2.
731
732Consider the first example above, where the user passes ``4x`` to an option
733that takes an integer:
734
735.. code-block:: shell-session
736
737   $ /usr/bin/foo -n 4x
738   Usage: foo [options]
739
740   foo: error: option -n: invalid integer value: '4x'
741
742Or, where the user fails to pass a value at all:
743
744.. code-block:: shell-session
745
746   $ /usr/bin/foo -n
747   Usage: foo [options]
748
749   foo: error: -n option requires an argument
750
751:mod:`optparse`\ -generated error messages take care always to mention the
752option involved in the error; be sure to do the same when calling
753:func:`OptionParser.error` from your application code.
754
755If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
756you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
757and/or :meth:`~OptionParser.error` methods.
758
759
760.. _optparse-putting-it-all-together:
761
762Putting it all together
763^^^^^^^^^^^^^^^^^^^^^^^
764
765Here's what :mod:`optparse`\ -based scripts usually look like::
766
767   from optparse import OptionParser
768   ...
769   def main():
770       usage = "usage: %prog [options] arg"
771       parser = OptionParser(usage)
772       parser.add_option("-f", "--file", dest="filename",
773                         help="read data from FILENAME")
774       parser.add_option("-v", "--verbose",
775                         action="store_true", dest="verbose")
776       parser.add_option("-q", "--quiet",
777                         action="store_false", dest="verbose")
778       ...
779       (options, args) = parser.parse_args()
780       if len(args) != 1:
781           parser.error("incorrect number of arguments")
782       if options.verbose:
783           print("reading %s..." % options.filename)
784       ...
785
786   if __name__ == "__main__":
787       main()
788
789
790.. _optparse-reference-guide:
791
792Reference Guide
793---------------
794
795
796.. _optparse-creating-parser:
797
798Creating the parser
799^^^^^^^^^^^^^^^^^^^
800
801The first step in using :mod:`optparse` is to create an OptionParser instance.
802
803.. class:: OptionParser(...)
804
805   The OptionParser constructor has no required arguments, but a number of
806   optional keyword arguments.  You should always pass them as keyword
807   arguments, i.e. do not rely on the order in which the arguments are declared.
808
809   ``usage`` (default: ``"%prog [options]"``)
810      The usage summary to print when your program is run incorrectly or with a
811      help option.  When :mod:`optparse` prints the usage string, it expands
812      ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
813      passed that keyword argument).  To suppress a usage message, pass the
814      special value :data:`optparse.SUPPRESS_USAGE`.
815
816   ``option_list`` (default: ``[]``)
817      A list of Option objects to populate the parser with.  The options in
818      ``option_list`` are added after any options in ``standard_option_list`` (a
819      class attribute that may be set by OptionParser subclasses), but before
820      any version or help options. Deprecated; use :meth:`add_option` after
821      creating the parser instead.
822
823   ``option_class`` (default: optparse.Option)
824      Class to use when adding options to the parser in :meth:`add_option`.
825
826   ``version`` (default: ``None``)
827      A version string to print when the user supplies a version option. If you
828      supply a true value for ``version``, :mod:`optparse` automatically adds a
829      version option with the single option string ``--version``.  The
830      substring ``%prog`` is expanded the same as for ``usage``.
831
832   ``conflict_handler`` (default: ``"error"``)
833      Specifies what to do when options with conflicting option strings are
834      added to the parser; see section
835      :ref:`optparse-conflicts-between-options`.
836
837   ``description`` (default: ``None``)
838      A paragraph of text giving a brief overview of your program.
839      :mod:`optparse` reformats this paragraph to fit the current terminal width
840      and prints it when the user requests help (after ``usage``, but before the
841      list of options).
842
843   ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
844      An instance of optparse.HelpFormatter that will be used for printing help
845      text.  :mod:`optparse` provides two concrete classes for this purpose:
846      IndentedHelpFormatter and TitledHelpFormatter.
847
848   ``add_help_option`` (default: ``True``)
849      If true, :mod:`optparse` will add a help option (with option strings ``-h``
850      and ``--help``) to the parser.
851
852   ``prog``
853      The string to use when expanding ``%prog`` in ``usage`` and ``version``
854      instead of ``os.path.basename(sys.argv[0])``.
855
856   ``epilog`` (default: ``None``)
857      A paragraph of help text to print after the option help.
858
859.. _optparse-populating-parser:
860
861Populating the parser
862^^^^^^^^^^^^^^^^^^^^^
863
864There are several ways to populate the parser with options.  The preferred way
865is by using :meth:`OptionParser.add_option`, as shown in section
866:ref:`optparse-tutorial`.  :meth:`add_option` can be called in one of two ways:
867
868* pass it an Option instance (as returned by :func:`make_option`)
869
870* pass it any combination of positional and keyword arguments that are
871  acceptable to :func:`make_option` (i.e., to the Option constructor), and it
872  will create the Option instance for you
873
874The other alternative is to pass a list of pre-constructed Option instances to
875the OptionParser constructor, as in::
876
877   option_list = [
878       make_option("-f", "--filename",
879                   action="store", type="string", dest="filename"),
880       make_option("-q", "--quiet",
881                   action="store_false", dest="verbose"),
882       ]
883   parser = OptionParser(option_list=option_list)
884
885(:func:`make_option` is a factory function for creating Option instances;
886currently it is an alias for the Option constructor.  A future version of
887:mod:`optparse` may split Option into several classes, and :func:`make_option`
888will pick the right class to instantiate.  Do not instantiate Option directly.)
889
890
891.. _optparse-defining-options:
892
893Defining options
894^^^^^^^^^^^^^^^^
895
896Each Option instance represents a set of synonymous command-line option strings,
897e.g. ``-f`` and ``--file``.  You can specify any number of short or
898long option strings, but you must specify at least one overall option string.
899
900The canonical way to create an :class:`Option` instance is with the
901:meth:`add_option` method of :class:`OptionParser`.
902
903.. method:: OptionParser.add_option(option)
904            OptionParser.add_option(*opt_str, attr=value, ...)
905
906   To define an option with only a short option string::
907
908      parser.add_option("-f", attr=value, ...)
909
910   And to define an option with only a long option string::
911
912      parser.add_option("--foo", attr=value, ...)
913
914   The keyword arguments define attributes of the new Option object.  The most
915   important option attribute is :attr:`~Option.action`, and it largely
916   determines which other attributes are relevant or required.  If you pass
917   irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
918   raises an :exc:`OptionError` exception explaining your mistake.
919
920   An option's *action* determines what :mod:`optparse` does when it encounters
921   this option on the command-line.  The standard option actions hard-coded into
922   :mod:`optparse` are:
923
924   ``"store"``
925      store this option's argument (default)
926
927   ``"store_const"``
928      store a constant value, pre-set via :attr:`Option.const`
929
930   ``"store_true"``
931      store ``True``
932
933   ``"store_false"``
934      store ``False``
935
936   ``"append"``
937      append this option's argument to a list
938
939   ``"append_const"``
940      append a constant value to a list, pre-set via :attr:`Option.const`
941
942   ``"count"``
943      increment a counter by one
944
945   ``"callback"``
946      call a specified function
947
948   ``"help"``
949      print a usage message including all options and the documentation for them
950
951   (If you don't supply an action, the default is ``"store"``.  For this action,
952   you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
953   attributes; see :ref:`optparse-standard-option-actions`.)
954
955As you can see, most actions involve storing or updating a value somewhere.
956:mod:`optparse` always creates a special object for this, conventionally called
957``options``, which is an instance of :class:`optparse.Values`.
958
959.. class:: Values
960
961   An object holding parsed argument names and values as attributes.
962   Normally created by calling when calling :meth:`OptionParser.parse_args`,
963   and can be overridden by a custom subclass passed to the *values* argument of
964   :meth:`OptionParser.parse_args` (as described in :ref:`optparse-parsing-arguments`).
965
966Option
967arguments (and various other values) are stored as attributes of this object,
968according to the :attr:`~Option.dest` (destination) option attribute.
969
970For example, when you call ::
971
972   parser.parse_args()
973
974one of the first things :mod:`optparse` does is create the ``options`` object::
975
976   options = Values()
977
978If one of the options in this parser is defined with ::
979
980   parser.add_option("-f", "--file", action="store", type="string", dest="filename")
981
982and the command-line being parsed includes any of the following::
983
984   -ffoo
985   -f foo
986   --file=foo
987   --file foo
988
989then :mod:`optparse`, on seeing this option, will do the equivalent of ::
990
991   options.filename = "foo"
992
993The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
994as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
995one that makes sense for *all* options.
996
997
998.. _optparse-option-attributes:
999
1000Option attributes
1001^^^^^^^^^^^^^^^^^
1002
1003.. class:: Option
1004
1005   A single command line argument,
1006   with various attributes passed by keyword to the constructor.
1007   Normally created with :meth:`OptionParser.add_option` rather than directly,
1008   and can be overridden by a custom class via the *option_class* argument
1009   to :class:`OptionParser`.
1010
1011The following option attributes may be passed as keyword arguments to
1012:meth:`OptionParser.add_option`.  If you pass an option attribute that is not
1013relevant to a particular option, or fail to pass a required option attribute,
1014:mod:`optparse` raises :exc:`OptionError`.
1015
1016.. attribute:: Option.action
1017
1018   (default: ``"store"``)
1019
1020   Determines :mod:`optparse`'s behaviour when this option is seen on the
1021   command line; the available options are documented :ref:`here
1022   <optparse-standard-option-actions>`.
1023
1024.. attribute:: Option.type
1025
1026   (default: ``"string"``)
1027
1028   The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
1029   the available option types are documented :ref:`here
1030   <optparse-standard-option-types>`.
1031
1032.. attribute:: Option.dest
1033
1034   (default: derived from option strings)
1035
1036   If the option's action implies writing or modifying a value somewhere, this
1037   tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
1038   attribute of the ``options`` object that :mod:`optparse` builds as it parses
1039   the command line.
1040
1041.. attribute:: Option.default
1042
1043   The value to use for this option's destination if the option is not seen on
1044   the command line.  See also :meth:`OptionParser.set_defaults`.
1045
1046.. attribute:: Option.nargs
1047
1048   (default: 1)
1049
1050   How many arguments of type :attr:`~Option.type` should be consumed when this
1051   option is seen.  If > 1, :mod:`optparse` will store a tuple of values to
1052   :attr:`~Option.dest`.
1053
1054.. attribute:: Option.const
1055
1056   For actions that store a constant value, the constant value to store.
1057
1058.. attribute:: Option.choices
1059
1060   For options of type ``"choice"``, the list of strings the user may choose
1061   from.
1062
1063.. attribute:: Option.callback
1064
1065   For options with action ``"callback"``, the callable to call when this option
1066   is seen.  See section :ref:`optparse-option-callbacks` for detail on the
1067   arguments passed to the callable.
1068
1069.. attribute:: Option.callback_args
1070               Option.callback_kwargs
1071
1072   Additional positional and keyword arguments to pass to ``callback`` after the
1073   four standard callback arguments.
1074
1075.. attribute:: Option.help
1076
1077   Help text to print for this option when listing all available options after
1078   the user supplies a :attr:`~Option.help` option (such as ``--help``).  If
1079   no help text is supplied, the option will be listed without help text.  To
1080   hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
1081
1082.. attribute:: Option.metavar
1083
1084   (default: derived from option strings)
1085
1086   Stand-in for the option argument(s) to use when printing help text.  See
1087   section :ref:`optparse-tutorial` for an example.
1088
1089
1090.. _optparse-standard-option-actions:
1091
1092Standard option actions
1093^^^^^^^^^^^^^^^^^^^^^^^
1094
1095The various option actions all have slightly different requirements and effects.
1096Most actions have several relevant option attributes which you may specify to
1097guide :mod:`optparse`'s behaviour; a few have required attributes, which you
1098must specify for any option using that action.
1099
1100* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1101  :attr:`~Option.nargs`, :attr:`~Option.choices`]
1102
1103  The option must be followed by an argument, which is converted to a value
1104  according to :attr:`~Option.type` and stored in :attr:`~Option.dest`.  If
1105  :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1106  command line; all will be converted according to :attr:`~Option.type` and
1107  stored to :attr:`~Option.dest` as a tuple.  See the
1108  :ref:`optparse-standard-option-types` section.
1109
1110  If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1111  defaults to ``"choice"``.
1112
1113  If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
1114
1115  If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
1116  from the first long option string (e.g., ``--foo-bar`` implies
1117  ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
1118  destination from the first short option string (e.g., ``-f`` implies ``f``).
1119
1120  Example::
1121
1122     parser.add_option("-f")
1123     parser.add_option("-p", type="float", nargs=3, dest="point")
1124
1125  As it parses the command line ::
1126
1127     -f foo.txt -p 1 -3.5 4 -fbar.txt
1128
1129  :mod:`optparse` will set ::
1130
1131     options.f = "foo.txt"
1132     options.point = (1.0, -3.5, 4.0)
1133     options.f = "bar.txt"
1134
1135* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1136  :attr:`~Option.dest`]
1137
1138  The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
1139
1140  Example::
1141
1142     parser.add_option("-q", "--quiet",
1143                       action="store_const", const=0, dest="verbose")
1144     parser.add_option("-v", "--verbose",
1145                       action="store_const", const=1, dest="verbose")
1146     parser.add_option("--noisy",
1147                       action="store_const", const=2, dest="verbose")
1148
1149  If ``--noisy`` is seen, :mod:`optparse` will set  ::
1150
1151     options.verbose = 2
1152
1153* ``"store_true"`` [relevant: :attr:`~Option.dest`]
1154
1155  A special case of ``"store_const"`` that stores ``True`` to
1156  :attr:`~Option.dest`.
1157
1158* ``"store_false"`` [relevant: :attr:`~Option.dest`]
1159
1160  Like ``"store_true"``, but stores ``False``.
1161
1162  Example::
1163
1164     parser.add_option("--clobber", action="store_true", dest="clobber")
1165     parser.add_option("--no-clobber", action="store_false", dest="clobber")
1166
1167* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1168  :attr:`~Option.nargs`, :attr:`~Option.choices`]
1169
1170  The option must be followed by an argument, which is appended to the list in
1171  :attr:`~Option.dest`.  If no default value for :attr:`~Option.dest` is
1172  supplied, an empty list is automatically created when :mod:`optparse` first
1173  encounters this option on the command-line.  If :attr:`~Option.nargs` > 1,
1174  multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1175  is appended to :attr:`~Option.dest`.
1176
1177  The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1178  for the ``"store"`` action.
1179
1180  Example::
1181
1182     parser.add_option("-t", "--tracks", action="append", type="int")
1183
1184  If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
1185  of::
1186
1187     options.tracks = []
1188     options.tracks.append(int("3"))
1189
1190  If, a little later on, ``--tracks=4`` is seen, it does::
1191
1192     options.tracks.append(int("4"))
1193
1194  The ``append`` action calls the ``append`` method on the current value of the
1195  option.  This means that any default value specified must have an ``append``
1196  method.  It also means that if the default value is non-empty, the default
1197  elements will be present in the parsed value for the option, with any values
1198  from the command line appended after those default values::
1199
1200     >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
1201     >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
1202     >>> opts.files
1203     ['~/.mypkg/defaults', 'overrides.mypkg']
1204
1205* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1206  :attr:`~Option.dest`]
1207
1208  Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1209  :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1210  ``None``, and an empty list is automatically created the first time the option
1211  is encountered.
1212
1213* ``"count"`` [relevant: :attr:`~Option.dest`]
1214
1215  Increment the integer stored at :attr:`~Option.dest`.  If no default value is
1216  supplied, :attr:`~Option.dest` is set to zero before being incremented the
1217  first time.
1218
1219  Example::
1220
1221     parser.add_option("-v", action="count", dest="verbosity")
1222
1223  The first time ``-v`` is seen on the command line, :mod:`optparse` does the
1224  equivalent of::
1225
1226     options.verbosity = 0
1227     options.verbosity += 1
1228
1229  Every subsequent occurrence of ``-v`` results in  ::
1230
1231     options.verbosity += 1
1232
1233* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1234  :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1235  :attr:`~Option.callback_kwargs`]
1236
1237  Call the function specified by :attr:`~Option.callback`, which is called as ::
1238
1239     func(option, opt_str, value, parser, *args, **kwargs)
1240
1241  See section :ref:`optparse-option-callbacks` for more detail.
1242
1243* ``"help"``
1244
1245  Prints a complete help message for all the options in the current option
1246  parser.  The help message is constructed from the ``usage`` string passed to
1247  OptionParser's constructor and the :attr:`~Option.help` string passed to every
1248  option.
1249
1250  If no :attr:`~Option.help` string is supplied for an option, it will still be
1251  listed in the help message.  To omit an option entirely, use the special value
1252  :data:`optparse.SUPPRESS_HELP`.
1253
1254  :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1255  OptionParsers, so you do not normally need to create one.
1256
1257  Example::
1258
1259     from optparse import OptionParser, SUPPRESS_HELP
1260
1261     # usually, a help option is added automatically, but that can
1262     # be suppressed using the add_help_option argument
1263     parser = OptionParser(add_help_option=False)
1264
1265     parser.add_option("-h", "--help", action="help")
1266     parser.add_option("-v", action="store_true", dest="verbose",
1267                       help="Be moderately verbose")
1268     parser.add_option("--file", dest="filename",
1269                       help="Input file to read data from")
1270     parser.add_option("--secret", help=SUPPRESS_HELP)
1271
1272  If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
1273  it will print something like the following help message to stdout (assuming
1274  ``sys.argv[0]`` is ``"foo.py"``):
1275
1276  .. code-block:: text
1277
1278     Usage: foo.py [options]
1279
1280     Options:
1281       -h, --help        Show this help message and exit
1282       -v                Be moderately verbose
1283       --file=FILENAME   Input file to read data from
1284
1285  After printing the help message, :mod:`optparse` terminates your process with
1286  ``sys.exit(0)``.
1287
1288* ``"version"``
1289
1290  Prints the version number supplied to the OptionParser to stdout and exits.
1291  The version number is actually formatted and printed by the
1292  ``print_version()`` method of OptionParser.  Generally only relevant if the
1293  ``version`` argument is supplied to the OptionParser constructor.  As with
1294  :attr:`~Option.help` options, you will rarely create ``version`` options,
1295  since :mod:`optparse` automatically adds them when needed.
1296
1297
1298.. _optparse-standard-option-types:
1299
1300Standard option types
1301^^^^^^^^^^^^^^^^^^^^^
1302
1303:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1304``"choice"``, ``"float"`` and ``"complex"``.  If you need to add new
1305option types, see section :ref:`optparse-extending-optparse`.
1306
1307Arguments to string options are not checked or converted in any way: the text on
1308the command line is stored in the destination (or passed to the callback) as-is.
1309
1310Integer arguments (type ``"int"``) are parsed as follows:
1311
1312* if the number starts with ``0x``, it is parsed as a hexadecimal number
1313
1314* if the number starts with ``0``, it is parsed as an octal number
1315
1316* if the number starts with ``0b``, it is parsed as a binary number
1317
1318* otherwise, the number is parsed as a decimal number
1319
1320
1321The conversion is done by calling :func:`int` with the appropriate base (2, 8,
132210, or 16).  If this fails, so will :mod:`optparse`, although with a more useful
1323error message.
1324
1325``"float"`` and ``"complex"`` option arguments are converted directly with
1326:func:`float` and :func:`complex`, with similar error-handling.
1327
1328``"choice"`` options are a subtype of ``"string"`` options.  The
1329:attr:`~Option.choices` option attribute (a sequence of strings) defines the
1330set of allowed option arguments.  :func:`optparse.check_choice` compares
1331user-supplied option arguments against this master list and raises
1332:exc:`OptionValueError` if an invalid string is given.
1333
1334
1335.. _optparse-parsing-arguments:
1336
1337Parsing arguments
1338^^^^^^^^^^^^^^^^^
1339
1340The whole point of creating and populating an OptionParser is to call its
1341:meth:`parse_args` method::
1342
1343   (options, args) = parser.parse_args(args=None, values=None)
1344
1345where the input parameters are
1346
1347``args``
1348   the list of arguments to process (default: ``sys.argv[1:]``)
1349
1350``values``
1351   an :class:`optparse.Values` object to store option arguments in (default: a
1352   new instance of :class:`Values`) -- if you give an existing object, the
1353   option defaults will not be initialized on it
1354
1355and the return values are
1356
1357``options``
1358   the same object that was passed in as ``values``, or the optparse.Values
1359   instance created by :mod:`optparse`
1360
1361``args``
1362   the leftover positional arguments after all options have been processed
1363
1364The most common usage is to supply neither keyword argument.  If you supply
1365``values``, it will be modified with repeated :func:`setattr` calls (roughly one
1366for every option argument stored to an option destination) and returned by
1367:meth:`parse_args`.
1368
1369If :meth:`parse_args` encounters any errors in the argument list, it calls the
1370OptionParser's :meth:`error` method with an appropriate end-user error message.
1371This ultimately terminates your process with an exit status of 2 (the
1372traditional Unix exit status for command-line errors).
1373
1374
1375.. _optparse-querying-manipulating-option-parser:
1376
1377Querying and manipulating your option parser
1378^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1379
1380The default behavior of the option parser can be customized slightly, and you
1381can also poke around your option parser and see what's there.  OptionParser
1382provides several methods to help you out:
1383
1384.. method:: OptionParser.disable_interspersed_args()
1385
1386   Set parsing to stop on the first non-option.  For example, if ``-a`` and
1387   ``-b`` are both simple options that take no arguments, :mod:`optparse`
1388   normally accepts this syntax::
1389
1390      prog -a arg1 -b arg2
1391
1392   and treats it as equivalent to  ::
1393
1394      prog -a -b arg1 arg2
1395
1396   To disable this feature, call :meth:`disable_interspersed_args`.  This
1397   restores traditional Unix syntax, where option parsing stops with the first
1398   non-option argument.
1399
1400   Use this if you have a command processor which runs another command which has
1401   options of its own and you want to make sure these options don't get
1402   confused.  For example, each command might have a different set of options.
1403
1404.. method:: OptionParser.enable_interspersed_args()
1405
1406   Set parsing to not stop on the first non-option, allowing interspersing
1407   switches with command arguments.  This is the default behavior.
1408
1409.. method:: OptionParser.get_option(opt_str)
1410
1411   Returns the Option instance with the option string *opt_str*, or ``None`` if
1412   no options have that option string.
1413
1414.. method:: OptionParser.has_option(opt_str)
1415
1416   Return ``True`` if the OptionParser has an option with option string *opt_str*
1417   (e.g., ``-q`` or ``--verbose``).
1418
1419.. method:: OptionParser.remove_option(opt_str)
1420
1421   If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1422   option is removed.  If that option provided any other option strings, all of
1423   those option strings become invalid. If *opt_str* does not occur in any
1424   option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
1425
1426
1427.. _optparse-conflicts-between-options:
1428
1429Conflicts between options
1430^^^^^^^^^^^^^^^^^^^^^^^^^
1431
1432If you're not careful, it's easy to define options with conflicting option
1433strings::
1434
1435   parser.add_option("-n", "--dry-run", ...)
1436   ...
1437   parser.add_option("-n", "--noisy", ...)
1438
1439(This is particularly true if you've defined your own OptionParser subclass with
1440some standard options.)
1441
1442Every time you add an option, :mod:`optparse` checks for conflicts with existing
1443options.  If it finds any, it invokes the current conflict-handling mechanism.
1444You can set the conflict-handling mechanism either in the constructor::
1445
1446   parser = OptionParser(..., conflict_handler=handler)
1447
1448or with a separate call::
1449
1450   parser.set_conflict_handler(handler)
1451
1452The available conflict handlers are:
1453
1454   ``"error"`` (default)
1455      assume option conflicts are a programming error and raise
1456      :exc:`OptionConflictError`
1457
1458   ``"resolve"``
1459      resolve option conflicts intelligently (see below)
1460
1461
1462As an example, let's define an :class:`OptionParser` that resolves conflicts
1463intelligently and add conflicting options to it::
1464
1465   parser = OptionParser(conflict_handler="resolve")
1466   parser.add_option("-n", "--dry-run", ..., help="do no harm")
1467   parser.add_option("-n", "--noisy", ..., help="be noisy")
1468
1469At this point, :mod:`optparse` detects that a previously added option is already
1470using the ``-n`` option string.  Since ``conflict_handler`` is ``"resolve"``,
1471it resolves the situation by removing ``-n`` from the earlier option's list of
1472option strings.  Now ``--dry-run`` is the only way for the user to activate
1473that option.  If the user asks for help, the help message will reflect that::
1474
1475   Options:
1476     --dry-run     do no harm
1477     ...
1478     -n, --noisy   be noisy
1479
1480It's possible to whittle away the option strings for a previously added option
1481until there are none left, and the user has no way of invoking that option from
1482the command-line.  In that case, :mod:`optparse` removes that option completely,
1483so it doesn't show up in help text or anywhere else. Carrying on with our
1484existing OptionParser::
1485
1486   parser.add_option("--dry-run", ..., help="new dry-run option")
1487
1488At this point, the original ``-n``/``--dry-run`` option is no longer
1489accessible, so :mod:`optparse` removes it, leaving this help text::
1490
1491   Options:
1492     ...
1493     -n, --noisy   be noisy
1494     --dry-run     new dry-run option
1495
1496
1497.. _optparse-cleanup:
1498
1499Cleanup
1500^^^^^^^
1501
1502OptionParser instances have several cyclic references.  This should not be a
1503problem for Python's garbage collector, but you may wish to break the cyclic
1504references explicitly by calling :meth:`~OptionParser.destroy` on your
1505OptionParser once you are done with it.  This is particularly useful in
1506long-running applications where large object graphs are reachable from your
1507OptionParser.
1508
1509
1510.. _optparse-other-methods:
1511
1512Other methods
1513^^^^^^^^^^^^^
1514
1515OptionParser supports several other public methods:
1516
1517.. method:: OptionParser.set_usage(usage)
1518
1519   Set the usage string according to the rules described above for the ``usage``
1520   constructor keyword argument.  Passing ``None`` sets the default usage
1521   string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
1522
1523.. method:: OptionParser.print_usage(file=None)
1524
1525   Print the usage message for the current program (``self.usage``) to *file*
1526   (default stdout).  Any occurrence of the string ``%prog`` in ``self.usage``
1527   is replaced with the name of the current program.  Does nothing if
1528   ``self.usage`` is empty or not defined.
1529
1530.. method:: OptionParser.get_usage()
1531
1532   Same as :meth:`print_usage` but returns the usage string instead of
1533   printing it.
1534
1535.. method:: OptionParser.set_defaults(dest=value, ...)
1536
1537   Set default values for several option destinations at once.  Using
1538   :meth:`set_defaults` is the preferred way to set default values for options,
1539   since multiple options can share the same destination.  For example, if
1540   several "mode" options all set the same destination, any one of them can set
1541   the default, and the last one wins::
1542
1543      parser.add_option("--advanced", action="store_const",
1544                        dest="mode", const="advanced",
1545                        default="novice")    # overridden below
1546      parser.add_option("--novice", action="store_const",
1547                        dest="mode", const="novice",
1548                        default="advanced")  # overrides above setting
1549
1550   To avoid this confusion, use :meth:`set_defaults`::
1551
1552      parser.set_defaults(mode="advanced")
1553      parser.add_option("--advanced", action="store_const",
1554                        dest="mode", const="advanced")
1555      parser.add_option("--novice", action="store_const",
1556                        dest="mode", const="novice")
1557
1558
1559.. _optparse-option-callbacks:
1560
1561Option Callbacks
1562----------------
1563
1564When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1565needs, you have two choices: extend :mod:`optparse` or define a callback option.
1566Extending :mod:`optparse` is more general, but overkill for a lot of simple
1567cases.  Quite often a simple callback is all you need.
1568
1569There are two steps to defining a callback option:
1570
1571* define the option itself using the ``"callback"`` action
1572
1573* write the callback; this is a function (or method) that takes at least four
1574  arguments, as described below
1575
1576
1577.. _optparse-defining-callback-option:
1578
1579Defining a callback option
1580^^^^^^^^^^^^^^^^^^^^^^^^^^
1581
1582As always, the easiest way to define a callback option is by using the
1583:meth:`OptionParser.add_option` method.  Apart from :attr:`~Option.action`, the
1584only option attribute you must specify is ``callback``, the function to call::
1585
1586   parser.add_option("-c", action="callback", callback=my_callback)
1587
1588``callback`` is a function (or other callable object), so you must have already
1589defined ``my_callback()`` when you create this callback option. In this simple
1590case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
1591which usually means that the option takes no arguments---the mere presence of
1592``-c`` on the command-line is all it needs to know.  In some
1593circumstances, though, you might want your callback to consume an arbitrary
1594number of command-line arguments.  This is where writing callbacks gets tricky;
1595it's covered later in this section.
1596
1597:mod:`optparse` always passes four particular arguments to your callback, and it
1598will only pass additional arguments if you specify them via
1599:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`.  Thus, the
1600minimal callback function signature is::
1601
1602   def my_callback(option, opt, value, parser):
1603
1604The four arguments to a callback are described below.
1605
1606There are several other option attributes that you can supply when you define a
1607callback option:
1608
1609:attr:`~Option.type`
1610   has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1611   instructs :mod:`optparse` to consume one argument and convert it to
1612   :attr:`~Option.type`.  Rather than storing the converted value(s) anywhere,
1613   though, :mod:`optparse` passes it to your callback function.
1614
1615:attr:`~Option.nargs`
1616   also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
1617   consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1618   :attr:`~Option.type`.  It then passes a tuple of converted values to your
1619   callback.
1620
1621:attr:`~Option.callback_args`
1622   a tuple of extra positional arguments to pass to the callback
1623
1624:attr:`~Option.callback_kwargs`
1625   a dictionary of extra keyword arguments to pass to the callback
1626
1627
1628.. _optparse-how-callbacks-called:
1629
1630How callbacks are called
1631^^^^^^^^^^^^^^^^^^^^^^^^
1632
1633All callbacks are called as follows::
1634
1635   func(option, opt_str, value, parser, *args, **kwargs)
1636
1637where
1638
1639``option``
1640   is the Option instance that's calling the callback
1641
1642``opt_str``
1643   is the option string seen on the command-line that's triggering the callback.
1644   (If an abbreviated long option was used, ``opt_str`` will be the full,
1645   canonical option string---e.g. if the user puts ``--foo`` on the
1646   command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
1647   ``"--foobar"``.)
1648
1649``value``
1650   is the argument to this option seen on the command-line.  :mod:`optparse` will
1651   only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1652   the type implied by the option's type.  If :attr:`~Option.type` for this option is
1653   ``None`` (no argument expected), then ``value`` will be ``None``.  If :attr:`~Option.nargs`
1654   > 1, ``value`` will be a tuple of values of the appropriate type.
1655
1656``parser``
1657   is the OptionParser instance driving the whole thing, mainly useful because
1658   you can access some other interesting data through its instance attributes:
1659
1660   ``parser.largs``
1661      the current list of leftover arguments, ie. arguments that have been
1662      consumed but are neither options nor option arguments. Feel free to modify
1663      ``parser.largs``, e.g. by adding more arguments to it.  (This list will
1664      become ``args``, the second return value of :meth:`parse_args`.)
1665
1666   ``parser.rargs``
1667      the current list of remaining arguments, ie. with ``opt_str`` and
1668      ``value`` (if applicable) removed, and only the arguments following them
1669      still there.  Feel free to modify ``parser.rargs``, e.g. by consuming more
1670      arguments.
1671
1672   ``parser.values``
1673      the object where option values are by default stored (an instance of
1674      optparse.OptionValues).  This lets callbacks use the same mechanism as the
1675      rest of :mod:`optparse` for storing option values; you don't need to mess
1676      around with globals or closures.  You can also access or modify the
1677      value(s) of any options already encountered on the command-line.
1678
1679``args``
1680   is a tuple of arbitrary positional arguments supplied via the
1681   :attr:`~Option.callback_args` option attribute.
1682
1683``kwargs``
1684   is a dictionary of arbitrary keyword arguments supplied via
1685   :attr:`~Option.callback_kwargs`.
1686
1687
1688.. _optparse-raising-errors-in-callback:
1689
1690Raising errors in a callback
1691^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1692
1693The callback function should raise :exc:`OptionValueError` if there are any
1694problems with the option or its argument(s).  :mod:`optparse` catches this and
1695terminates the program, printing the error message you supply to stderr.  Your
1696message should be clear, concise, accurate, and mention the option at fault.
1697Otherwise, the user will have a hard time figuring out what they did wrong.
1698
1699
1700.. _optparse-callback-example-1:
1701
1702Callback example 1: trivial callback
1703^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1704
1705Here's an example of a callback option that takes no arguments, and simply
1706records that the option was seen::
1707
1708   def record_foo_seen(option, opt_str, value, parser):
1709       parser.values.saw_foo = True
1710
1711   parser.add_option("--foo", action="callback", callback=record_foo_seen)
1712
1713Of course, you could do that with the ``"store_true"`` action.
1714
1715
1716.. _optparse-callback-example-2:
1717
1718Callback example 2: check option order
1719^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1720
1721Here's a slightly more interesting example: record the fact that ``-a`` is
1722seen, but blow up if it comes after ``-b`` in the command-line.  ::
1723
1724   def check_order(option, opt_str, value, parser):
1725       if parser.values.b:
1726           raise OptionValueError("can't use -a after -b")
1727       parser.values.a = 1
1728   ...
1729   parser.add_option("-a", action="callback", callback=check_order)
1730   parser.add_option("-b", action="store_true", dest="b")
1731
1732
1733.. _optparse-callback-example-3:
1734
1735Callback example 3: check option order (generalized)
1736^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1737
1738If you want to re-use this callback for several similar options (set a flag, but
1739blow up if ``-b`` has already been seen), it needs a bit of work: the error
1740message and the flag that it sets must be generalized.  ::
1741
1742   def check_order(option, opt_str, value, parser):
1743       if parser.values.b:
1744           raise OptionValueError("can't use %s after -b" % opt_str)
1745       setattr(parser.values, option.dest, 1)
1746   ...
1747   parser.add_option("-a", action="callback", callback=check_order, dest='a')
1748   parser.add_option("-b", action="store_true", dest="b")
1749   parser.add_option("-c", action="callback", callback=check_order, dest='c')
1750
1751
1752.. _optparse-callback-example-4:
1753
1754Callback example 4: check arbitrary condition
1755^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1756
1757Of course, you could put any condition in there---you're not limited to checking
1758the values of already-defined options.  For example, if you have options that
1759should not be called when the moon is full, all you have to do is this::
1760
1761   def check_moon(option, opt_str, value, parser):
1762       if is_moon_full():
1763           raise OptionValueError("%s option invalid when moon is full"
1764                                  % opt_str)
1765       setattr(parser.values, option.dest, 1)
1766   ...
1767   parser.add_option("--foo",
1768                     action="callback", callback=check_moon, dest="foo")
1769
1770(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1771
1772
1773.. _optparse-callback-example-5:
1774
1775Callback example 5: fixed arguments
1776^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1777
1778Things get slightly more interesting when you define callback options that take
1779a fixed number of arguments.  Specifying that a callback option takes arguments
1780is similar to defining a ``"store"`` or ``"append"`` option: if you define
1781:attr:`~Option.type`, then the option takes one argument that must be
1782convertible to that type; if you further define :attr:`~Option.nargs`, then the
1783option takes :attr:`~Option.nargs` arguments.
1784
1785Here's an example that just emulates the standard ``"store"`` action::
1786
1787   def store_value(option, opt_str, value, parser):
1788       setattr(parser.values, option.dest, value)
1789   ...
1790   parser.add_option("--foo",
1791                     action="callback", callback=store_value,
1792                     type="int", nargs=3, dest="foo")
1793
1794Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1795them to integers for you; all you have to do is store them.  (Or whatever;
1796obviously you don't need a callback for this example.)
1797
1798
1799.. _optparse-callback-example-6:
1800
1801Callback example 6: variable arguments
1802^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1803
1804Things get hairy when you want an option to take a variable number of arguments.
1805For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1806built-in capabilities for it.  And you have to deal with certain intricacies of
1807conventional Unix command-line parsing that :mod:`optparse` normally handles for
1808you.  In particular, callbacks should implement the conventional rules for bare
1809``--`` and ``-`` arguments:
1810
1811* either ``--`` or ``-`` can be option arguments
1812
1813* bare ``--`` (if not the argument to some option): halt command-line
1814  processing and discard the ``--``
1815
1816* bare ``-`` (if not the argument to some option): halt command-line
1817  processing but keep the ``-`` (append it to ``parser.largs``)
1818
1819If you want an option that takes a variable number of arguments, there are
1820several subtle, tricky issues to worry about.  The exact implementation you
1821choose will be based on which trade-offs you're willing to make for your
1822application (which is why :mod:`optparse` doesn't support this sort of thing
1823directly).
1824
1825Nevertheless, here's a stab at a callback for an option with variable
1826arguments::
1827
1828    def vararg_callback(option, opt_str, value, parser):
1829        assert value is None
1830        value = []
1831
1832        def floatable(str):
1833            try:
1834                float(str)
1835                return True
1836            except ValueError:
1837                return False
1838
1839        for arg in parser.rargs:
1840            # stop on --foo like options
1841            if arg[:2] == "--" and len(arg) > 2:
1842                break
1843            # stop on -a, but not on -3 or -3.0
1844            if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1845                break
1846            value.append(arg)
1847
1848        del parser.rargs[:len(value)]
1849        setattr(parser.values, option.dest, value)
1850
1851    ...
1852    parser.add_option("-c", "--callback", dest="vararg_attr",
1853                      action="callback", callback=vararg_callback)
1854
1855
1856.. _optparse-extending-optparse:
1857
1858Extending :mod:`optparse`
1859-------------------------
1860
1861Since the two major controlling factors in how :mod:`optparse` interprets
1862command-line options are the action and type of each option, the most likely
1863direction of extension is to add new actions and new types.
1864
1865
1866.. _optparse-adding-new-types:
1867
1868Adding new types
1869^^^^^^^^^^^^^^^^
1870
1871To add new types, you need to define your own subclass of :mod:`optparse`'s
1872:class:`Option` class.  This class has a couple of attributes that define
1873:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
1874
1875.. attribute:: Option.TYPES
1876
1877   A tuple of type names; in your subclass, simply define a new tuple
1878   :attr:`TYPES` that builds on the standard one.
1879
1880.. attribute:: Option.TYPE_CHECKER
1881
1882   A dictionary mapping type names to type-checking functions.  A type-checking
1883   function has the following signature::
1884
1885      def check_mytype(option, opt, value)
1886
1887   where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1888   (e.g., ``-f``), and ``value`` is the string from the command line that must
1889   be checked and converted to your desired type.  ``check_mytype()`` should
1890   return an object of the hypothetical type ``mytype``.  The value returned by
1891   a type-checking function will wind up in the OptionValues instance returned
1892   by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1893   ``value`` parameter.
1894
1895   Your type-checking function should raise :exc:`OptionValueError` if it
1896   encounters any problems.  :exc:`OptionValueError` takes a single string
1897   argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1898   method, which in turn prepends the program name and the string ``"error:"``
1899   and prints everything to stderr before terminating the process.
1900
1901Here's a silly example that demonstrates adding a ``"complex"`` option type to
1902parse Python-style complex numbers on the command line.  (This is even sillier
1903than it used to be, because :mod:`optparse` 1.3 added built-in support for
1904complex numbers, but never mind.)
1905
1906First, the necessary imports::
1907
1908   from copy import copy
1909   from optparse import Option, OptionValueError
1910
1911You need to define your type-checker first, since it's referred to later (in the
1912:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
1913
1914   def check_complex(option, opt, value):
1915       try:
1916           return complex(value)
1917       except ValueError:
1918           raise OptionValueError(
1919               "option %s: invalid complex value: %r" % (opt, value))
1920
1921Finally, the Option subclass::
1922
1923   class MyOption (Option):
1924       TYPES = Option.TYPES + ("complex",)
1925       TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1926       TYPE_CHECKER["complex"] = check_complex
1927
1928(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
1929up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1930Option class.  This being Python, nothing stops you from doing that except good
1931manners and common sense.)
1932
1933That's it!  Now you can write a script that uses the new option type just like
1934any other :mod:`optparse`\ -based script, except you have to instruct your
1935OptionParser to use MyOption instead of Option::
1936
1937   parser = OptionParser(option_class=MyOption)
1938   parser.add_option("-c", type="complex")
1939
1940Alternately, you can build your own option list and pass it to OptionParser; if
1941you don't use :meth:`add_option` in the above way, you don't need to tell
1942OptionParser which option class to use::
1943
1944   option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1945   parser = OptionParser(option_list=option_list)
1946
1947
1948.. _optparse-adding-new-actions:
1949
1950Adding new actions
1951^^^^^^^^^^^^^^^^^^
1952
1953Adding new actions is a bit trickier, because you have to understand that
1954:mod:`optparse` has a couple of classifications for actions:
1955
1956"store" actions
1957   actions that result in :mod:`optparse` storing a value to an attribute of the
1958   current OptionValues instance; these options require a :attr:`~Option.dest`
1959   attribute to be supplied to the Option constructor.
1960
1961"typed" actions
1962   actions that take a value from the command line and expect it to be of a
1963   certain type; or rather, a string that can be converted to a certain type.
1964   These options require a :attr:`~Option.type` attribute to the Option
1965   constructor.
1966
1967These are overlapping sets: some default "store" actions are ``"store"``,
1968``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1969actions are ``"store"``, ``"append"``, and ``"callback"``.
1970
1971When you add an action, you need to categorize it by listing it in at least one
1972of the following class attributes of Option (all are lists of strings):
1973
1974.. attribute:: Option.ACTIONS
1975
1976   All actions must be listed in ACTIONS.
1977
1978.. attribute:: Option.STORE_ACTIONS
1979
1980   "store" actions are additionally listed here.
1981
1982.. attribute:: Option.TYPED_ACTIONS
1983
1984   "typed" actions are additionally listed here.
1985
1986.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1987
1988   Actions that always take a type (i.e. whose options always take a value) are
1989   additionally listed here.  The only effect of this is that :mod:`optparse`
1990   assigns the default type, ``"string"``, to options with no explicit type
1991   whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
1992
1993In order to actually implement your new action, you must override Option's
1994:meth:`take_action` method and add a case that recognizes your action.
1995
1996For example, let's add an ``"extend"`` action.  This is similar to the standard
1997``"append"`` action, but instead of taking a single value from the command-line
1998and appending it to an existing list, ``"extend"`` will take multiple values in
1999a single comma-delimited string, and extend an existing list with them.  That
2000is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
2001line ::
2002
2003   --names=foo,bar --names blah --names ding,dong
2004
2005would result in a list  ::
2006
2007   ["foo", "bar", "blah", "ding", "dong"]
2008
2009Again we define a subclass of Option::
2010
2011   class MyOption(Option):
2012
2013       ACTIONS = Option.ACTIONS + ("extend",)
2014       STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
2015       TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
2016       ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
2017
2018       def take_action(self, action, dest, opt, value, values, parser):
2019           if action == "extend":
2020               lvalue = value.split(",")
2021               values.ensure_value(dest, []).extend(lvalue)
2022           else:
2023               Option.take_action(
2024                   self, action, dest, opt, value, values, parser)
2025
2026Features of note:
2027
2028* ``"extend"`` both expects a value on the command-line and stores that value
2029  somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
2030  :attr:`~Option.TYPED_ACTIONS`.
2031
2032* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
2033  ``"extend"`` actions, we put the ``"extend"`` action in
2034  :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
2035
2036* :meth:`MyOption.take_action` implements just this one new action, and passes
2037  control back to :meth:`Option.take_action` for the standard :mod:`optparse`
2038  actions.
2039
2040* ``values`` is an instance of the optparse_parser.Values class, which provides
2041  the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
2042  essentially :func:`getattr` with a safety valve; it is called as ::
2043
2044     values.ensure_value(attr, value)
2045
2046  If the ``attr`` attribute of ``values`` doesn't exist or is ``None``, then
2047  ensure_value() first sets it to ``value``, and then returns 'value. This is
2048  very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
2049  of which accumulate data in a variable and expect that variable to be of a
2050  certain type (a list for the first two, an integer for the latter).  Using
2051  :meth:`ensure_value` means that scripts using your action don't have to worry
2052  about setting a default value for the option destinations in question; they
2053  can just leave the default as ``None`` and :meth:`ensure_value` will take care of
2054  getting it right when it's needed.
2055
2056Exceptions
2057----------
2058
2059.. exception:: OptionError
2060
2061   Raised if an :class:`Option` instance is created with invalid or
2062   inconsistent arguments.
2063
2064.. exception:: OptionConflictError
2065
2066   Raised if conflicting options are added to an :class:`OptionParser`.
2067
2068.. exception:: OptionValueError
2069
2070   Raised if an invalid option value is encountered on the command line.
2071
2072.. exception:: BadOptionError
2073
2074   Raised if an invalid option is passed on the command line.
2075
2076.. exception:: AmbiguousOptionError
2077
2078   Raised if an ambiguous option is passed on the command line.
2079