blob: 6dc57bb3a64e2da9669b78b2eede4bd6b810b1ad [file] [log] [blame]
Steven Bethard6d265692010-03-02 09:22:57 +00001:mod:`optparse` --- Parser for command line options
2===================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: optparse
Steven Bethard6d265692010-03-02 09:22:57 +00005 :synopsis: Command-line option parsing library.
Steven Bethard59710962010-05-24 03:21:08 +00006 :deprecated:
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Greg Ward <gward@python.net>
Georg Brandl116aa622007-08-15 14:28:22 +00008.. sectionauthor:: Greg Ward <gward@python.net>
9
Éric Araujo19f9b712011-08-19 00:49:18 +020010.. deprecated:: 3.2
11 The :mod:`optparse` module is deprecated and will not be developed further;
12 development will continue with the :mod:`argparse` module.
13
Raymond Hettinger469271d2011-01-27 20:38:46 +000014**Source code:** :source:`Lib/optparse.py`
15
16--------------
17
Georg Brandl15a515f2009-09-17 22:11:49 +000018:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
19command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
20more declarative style of command-line parsing: you create an instance of
21:class:`OptionParser`, populate it with options, and parse the command
22line. :mod:`optparse` allows users to specify options in the conventional
23GNU/POSIX syntax, and additionally generates usage and help messages for you.
Georg Brandl116aa622007-08-15 14:28:22 +000024
Georg Brandl15a515f2009-09-17 22:11:49 +000025Here's an example of using :mod:`optparse` in a simple script::
Georg Brandl116aa622007-08-15 14:28:22 +000026
27 from optparse import OptionParser
28 [...]
29 parser = OptionParser()
30 parser.add_option("-f", "--file", dest="filename",
31 help="write report to FILE", metavar="FILE")
32 parser.add_option("-q", "--quiet",
33 action="store_false", dest="verbose", default=True,
34 help="don't print status messages to stdout")
35
36 (options, args) = parser.parse_args()
37
38With these few lines of code, users of your script can now do the "usual thing"
39on the command-line, for example::
40
41 <yourscript> --file=outfile -q
42
Georg Brandl15a515f2009-09-17 22:11:49 +000043As it parses the command line, :mod:`optparse` sets attributes of the
44``options`` object returned by :meth:`parse_args` based on user-supplied
45command-line values. When :meth:`parse_args` returns from parsing this command
46line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
47``False``. :mod:`optparse` supports both long and short options, allows short
Georg Brandl116aa622007-08-15 14:28:22 +000048options to be merged together, and allows options to be associated with their
49arguments in a variety of ways. Thus, the following command lines are all
50equivalent to the above example::
51
52 <yourscript> -f outfile --quiet
53 <yourscript> --quiet --file outfile
54 <yourscript> -q -foutfile
55 <yourscript> -qfoutfile
56
57Additionally, users can run one of ::
58
59 <yourscript> -h
60 <yourscript> --help
61
Ezio Melotti383ae952010-01-03 09:06:02 +000062and :mod:`optparse` will print out a brief summary of your script's options:
63
64.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +000065
Georg Brandl121ff822011-01-02 14:23:43 +000066 Usage: <yourscript> [options]
Georg Brandl116aa622007-08-15 14:28:22 +000067
Georg Brandl121ff822011-01-02 14:23:43 +000068 Options:
Georg Brandl116aa622007-08-15 14:28:22 +000069 -h, --help show this help message and exit
70 -f FILE, --file=FILE write report to FILE
71 -q, --quiet don't print status messages to stdout
72
73where the value of *yourscript* is determined at runtime (normally from
74``sys.argv[0]``).
75
Georg Brandl116aa622007-08-15 14:28:22 +000076
77.. _optparse-background:
78
79Background
80----------
81
82:mod:`optparse` was explicitly designed to encourage the creation of programs
83with straightforward, conventional command-line interfaces. To that end, it
84supports only the most common command-line syntax and semantics conventionally
85used under Unix. If you are unfamiliar with these conventions, read this
86section to acquaint yourself with them.
87
88
89.. _optparse-terminology:
90
91Terminology
92^^^^^^^^^^^
93
94argument
Georg Brandl15a515f2009-09-17 22:11:49 +000095 a string entered on the command-line, and passed by the shell to ``execl()``
96 or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
97 (``sys.argv[0]`` is the name of the program being executed). Unix shells
98 also use the term "word".
Georg Brandl116aa622007-08-15 14:28:22 +000099
100 It is occasionally desirable to substitute an argument list other than
101 ``sys.argv[1:]``, so you should read "argument" as "an element of
102 ``sys.argv[1:]``, or of some other list provided as a substitute for
103 ``sys.argv[1:]``".
104
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000105option
Georg Brandl15a515f2009-09-17 22:11:49 +0000106 an argument used to supply extra information to guide or customize the
107 execution of a program. There are many different syntaxes for options; the
108 traditional Unix syntax is a hyphen ("-") followed by a single letter,
Éric Araujo713d3032010-11-18 16:38:46 +0000109 e.g. ``-x`` or ``-F``. Also, traditional Unix syntax allows multiple
110 options to be merged into a single argument, e.g. ``-x -F`` is equivalent
111 to ``-xF``. The GNU project introduced ``--`` followed by a series of
112 hyphen-separated words, e.g. ``--file`` or ``--dry-run``. These are the
Georg Brandl15a515f2009-09-17 22:11:49 +0000113 only two option syntaxes provided by :mod:`optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +0000114
115 Some other option syntaxes that the world has seen include:
116
Éric Araujo713d3032010-11-18 16:38:46 +0000117 * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
Georg Brandl116aa622007-08-15 14:28:22 +0000118 as multiple options merged into a single argument)
119
Éric Araujo713d3032010-11-18 16:38:46 +0000120 * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
Georg Brandl116aa622007-08-15 14:28:22 +0000121 equivalent to the previous syntax, but they aren't usually seen in the same
122 program)
123
124 * a plus sign followed by a single letter, or a few letters, or a word, e.g.
Éric Araujo713d3032010-11-18 16:38:46 +0000125 ``+f``, ``+rgb``
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Éric Araujo713d3032010-11-18 16:38:46 +0000127 * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``,
128 ``/file``
Georg Brandl116aa622007-08-15 14:28:22 +0000129
Georg Brandl15a515f2009-09-17 22:11:49 +0000130 These option syntaxes are not supported by :mod:`optparse`, and they never
131 will be. This is deliberate: the first three are non-standard on any
132 environment, and the last only makes sense if you're exclusively targeting
133 VMS, MS-DOS, and/or Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135option argument
Georg Brandl15a515f2009-09-17 22:11:49 +0000136 an argument that follows an option, is closely associated with that option,
137 and is consumed from the argument list when that option is. With
138 :mod:`optparse`, option arguments may either be in a separate argument from
Ezio Melotti383ae952010-01-03 09:06:02 +0000139 their option:
140
141 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000142
143 -f foo
144 --file foo
145
Ezio Melotti383ae952010-01-03 09:06:02 +0000146 or included in the same argument:
147
148 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150 -ffoo
151 --file=foo
152
Georg Brandl15a515f2009-09-17 22:11:49 +0000153 Typically, a given option either takes an argument or it doesn't. Lots of
154 people want an "optional option arguments" feature, meaning that some options
155 will take an argument if they see it, and won't if they don't. This is
Éric Araujo713d3032010-11-18 16:38:46 +0000156 somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
157 an optional argument and ``-b`` is another option entirely, how do we
158 interpret ``-ab``? Because of this ambiguity, :mod:`optparse` does not
Georg Brandl15a515f2009-09-17 22:11:49 +0000159 support this feature.
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161positional argument
162 something leftover in the argument list after options have been parsed, i.e.
Georg Brandl15a515f2009-09-17 22:11:49 +0000163 after options and their arguments have been parsed and removed from the
164 argument list.
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166required option
167 an option that must be supplied on the command-line; note that the phrase
168 "required option" is self-contradictory in English. :mod:`optparse` doesn't
Georg Brandl15a515f2009-09-17 22:11:49 +0000169 prevent you from implementing required options, but doesn't give you much
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000170 help at it either.
Georg Brandl116aa622007-08-15 14:28:22 +0000171
172For example, consider this hypothetical command-line::
173
174 prog -v --report /tmp/report.txt foo bar
175
Éric Araujo713d3032010-11-18 16:38:46 +0000176``-v`` and ``--report`` are both options. Assuming that ``--report``
177takes one argument, ``/tmp/report.txt`` is an option argument. ``foo`` and
178``bar`` are positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180
181.. _optparse-what-options-for:
182
183What are options for?
184^^^^^^^^^^^^^^^^^^^^^
185
186Options are used to provide extra information to tune or customize the execution
187of a program. In case it wasn't clear, options are usually *optional*. A
188program should be able to run just fine with no options whatsoever. (Pick a
189random program from the Unix or GNU toolsets. Can it run without any options at
190all and still make sense? The main exceptions are ``find``, ``tar``, and
191``dd``\ ---all of which are mutant oddballs that have been rightly criticized
192for their non-standard syntax and confusing interfaces.)
193
194Lots of people want their programs to have "required options". Think about it.
195If it's required, then it's *not optional*! If there is a piece of information
196that your program absolutely requires in order to run successfully, that's what
197positional arguments are for.
198
199As an example of good command-line interface design, consider the humble ``cp``
200utility, for copying files. It doesn't make much sense to try to copy files
201without supplying a destination and at least one source. Hence, ``cp`` fails if
202you run it with no arguments. However, it has a flexible, useful syntax that
203does not require any options at all::
204
205 cp SOURCE DEST
206 cp SOURCE ... DEST-DIR
207
208You can get pretty far with just that. Most ``cp`` implementations provide a
209bunch of options to tweak exactly how the files are copied: you can preserve
210mode and modification time, avoid following symlinks, ask before clobbering
211existing files, etc. But none of this distracts from the core mission of
212``cp``, which is to copy either one file to another, or several files to another
213directory.
214
215
216.. _optparse-what-positional-arguments-for:
217
218What are positional arguments for?
219^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
220
221Positional arguments are for those pieces of information that your program
222absolutely, positively requires to run.
223
224A good user interface should have as few absolute requirements as possible. If
225your program requires 17 distinct pieces of information in order to run
226successfully, it doesn't much matter *how* you get that information from the
227user---most people will give up and walk away before they successfully run the
228program. This applies whether the user interface is a command-line, a
229configuration file, or a GUI: if you make that many demands on your users, most
230of them will simply give up.
231
232In short, try to minimize the amount of information that users are absolutely
233required to supply---use sensible defaults whenever possible. Of course, you
234also want to make your programs reasonably flexible. That's what options are
235for. Again, it doesn't matter if they are entries in a config file, widgets in
236the "Preferences" dialog of a GUI, or command-line options---the more options
237you implement, the more flexible your program is, and the more complicated its
238implementation becomes. Too much flexibility has drawbacks as well, of course;
239too many options can overwhelm users and make your code much harder to maintain.
240
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242.. _optparse-tutorial:
243
244Tutorial
245--------
246
247While :mod:`optparse` is quite flexible and powerful, it's also straightforward
248to use in most cases. This section covers the code patterns that are common to
249any :mod:`optparse`\ -based program.
250
251First, you need to import the OptionParser class; then, early in the main
252program, create an OptionParser instance::
253
254 from optparse import OptionParser
255 [...]
256 parser = OptionParser()
257
258Then you can start defining options. The basic syntax is::
259
260 parser.add_option(opt_str, ...,
261 attr=value, ...)
262
Éric Araujo713d3032010-11-18 16:38:46 +0000263Each option has one or more option strings, such as ``-f`` or ``--file``,
Georg Brandl116aa622007-08-15 14:28:22 +0000264and several option attributes that tell :mod:`optparse` what to expect and what
265to do when it encounters that option on the command line.
266
267Typically, each option will have one short option string and one long option
268string, e.g.::
269
270 parser.add_option("-f", "--file", ...)
271
272You're free to define as many short option strings and as many long option
273strings as you like (including zero), as long as there is at least one option
274string overall.
275
276The option strings passed to :meth:`add_option` are effectively labels for the
277option defined by that call. For brevity, we will frequently refer to
278*encountering an option* on the command line; in reality, :mod:`optparse`
279encounters *option strings* and looks up options from them.
280
281Once all of your options are defined, instruct :mod:`optparse` to parse your
282program's command line::
283
284 (options, args) = parser.parse_args()
285
286(If you like, you can pass a custom argument list to :meth:`parse_args`, but
287that's rarely necessary: by default it uses ``sys.argv[1:]``.)
288
289:meth:`parse_args` returns two values:
290
291* ``options``, an object containing values for all of your options---e.g. if
Éric Araujo713d3032010-11-18 16:38:46 +0000292 ``--file`` takes a single string argument, then ``options.file`` will be the
Georg Brandl116aa622007-08-15 14:28:22 +0000293 filename supplied by the user, or ``None`` if the user did not supply that
294 option
295
296* ``args``, the list of positional arguments leftover after parsing options
297
298This tutorial section only covers the four most important option attributes:
Georg Brandl15a515f2009-09-17 22:11:49 +0000299:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
300(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
301most fundamental.
Georg Brandl116aa622007-08-15 14:28:22 +0000302
303
304.. _optparse-understanding-option-actions:
305
306Understanding option actions
307^^^^^^^^^^^^^^^^^^^^^^^^^^^^
308
309Actions tell :mod:`optparse` what to do when it encounters an option on the
310command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
311adding new actions is an advanced topic covered in section
Georg Brandl15a515f2009-09-17 22:11:49 +0000312:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
313a value in some variable---for example, take a string from the command line and
314store it in an attribute of ``options``.
Georg Brandl116aa622007-08-15 14:28:22 +0000315
316If you don't specify an option action, :mod:`optparse` defaults to ``store``.
317
318
319.. _optparse-store-action:
320
321The store action
322^^^^^^^^^^^^^^^^
323
324The most common option action is ``store``, which tells :mod:`optparse` to take
325the next argument (or the remainder of the current argument), ensure that it is
326of the correct type, and store it to your chosen destination.
327
328For example::
329
330 parser.add_option("-f", "--file",
331 action="store", type="string", dest="filename")
332
333Now let's make up a fake command line and ask :mod:`optparse` to parse it::
334
335 args = ["-f", "foo.txt"]
336 (options, args) = parser.parse_args(args)
337
Éric Araujo713d3032010-11-18 16:38:46 +0000338When :mod:`optparse` sees the option string ``-f``, it consumes the next
339argument, ``foo.txt``, and stores it in ``options.filename``. So, after this
Georg Brandl116aa622007-08-15 14:28:22 +0000340call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
341
342Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
343Here's an option that expects an integer argument::
344
345 parser.add_option("-n", type="int", dest="num")
346
347Note that this option has no long option string, which is perfectly acceptable.
348Also, there's no explicit action, since the default is ``store``.
349
350Let's parse another fake command-line. This time, we'll jam the option argument
Éric Araujo713d3032010-11-18 16:38:46 +0000351right up against the option: since ``-n42`` (one argument) is equivalent to
352``-n 42`` (two arguments), the code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354 (options, args) = parser.parse_args(["-n42"])
Georg Brandl6911e3c2007-09-04 07:15:32 +0000355 print(options.num)
Georg Brandl116aa622007-08-15 14:28:22 +0000356
Éric Araujo713d3032010-11-18 16:38:46 +0000357will print ``42``.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
360the fact that the default action is ``store``, that means our first example can
361be a lot shorter::
362
363 parser.add_option("-f", "--file", dest="filename")
364
365If you don't supply a destination, :mod:`optparse` figures out a sensible
366default from the option strings: if the first long option string is
Éric Araujo713d3032010-11-18 16:38:46 +0000367``--foo-bar``, then the default destination is ``foo_bar``. If there are no
Georg Brandl116aa622007-08-15 14:28:22 +0000368long option strings, :mod:`optparse` looks at the first short option string: the
Éric Araujo713d3032010-11-18 16:38:46 +0000369default destination for ``-f`` is ``f``.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
Georg Brandl5c106642007-11-29 17:41:05 +0000371:mod:`optparse` also includes the built-in ``complex`` type. Adding
Georg Brandl116aa622007-08-15 14:28:22 +0000372types is covered in section :ref:`optparse-extending-optparse`.
373
374
375.. _optparse-handling-boolean-options:
376
377Handling boolean (flag) options
378^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
379
380Flag options---set a variable to true or false when a particular option is seen
381---are quite common. :mod:`optparse` supports them with two separate actions,
382``store_true`` and ``store_false``. For example, you might have a ``verbose``
Éric Araujo713d3032010-11-18 16:38:46 +0000383flag that is turned on with ``-v`` and off with ``-q``::
Georg Brandl116aa622007-08-15 14:28:22 +0000384
385 parser.add_option("-v", action="store_true", dest="verbose")
386 parser.add_option("-q", action="store_false", dest="verbose")
387
388Here we have two different options with the same destination, which is perfectly
389OK. (It just means you have to be a bit careful when setting default values---
390see below.)
391
Éric Araujo713d3032010-11-18 16:38:46 +0000392When :mod:`optparse` encounters ``-v`` on the command line, it sets
393``options.verbose`` to ``True``; when it encounters ``-q``,
Georg Brandl116aa622007-08-15 14:28:22 +0000394``options.verbose`` is set to ``False``.
395
396
397.. _optparse-other-actions:
398
399Other actions
400^^^^^^^^^^^^^
401
402Some other actions supported by :mod:`optparse` are:
403
Georg Brandl15a515f2009-09-17 22:11:49 +0000404``"store_const"``
Georg Brandl116aa622007-08-15 14:28:22 +0000405 store a constant value
406
Georg Brandl15a515f2009-09-17 22:11:49 +0000407``"append"``
Georg Brandl116aa622007-08-15 14:28:22 +0000408 append this option's argument to a list
409
Georg Brandl15a515f2009-09-17 22:11:49 +0000410``"count"``
Georg Brandl116aa622007-08-15 14:28:22 +0000411 increment a counter by one
412
Georg Brandl15a515f2009-09-17 22:11:49 +0000413``"callback"``
Georg Brandl116aa622007-08-15 14:28:22 +0000414 call a specified function
415
416These are covered in section :ref:`optparse-reference-guide`, Reference Guide
417and section :ref:`optparse-option-callbacks`.
418
419
420.. _optparse-default-values:
421
422Default values
423^^^^^^^^^^^^^^
424
425All of the above examples involve setting some variable (the "destination") when
426certain command-line options are seen. What happens if those options are never
427seen? Since we didn't supply any defaults, they are all set to ``None``. This
428is usually fine, but sometimes you want more control. :mod:`optparse` lets you
429supply a default value for each destination, which is assigned before the
430command line is parsed.
431
432First, consider the verbose/quiet example. If we want :mod:`optparse` to set
Éric Araujo713d3032010-11-18 16:38:46 +0000433``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
Georg Brandl116aa622007-08-15 14:28:22 +0000434
435 parser.add_option("-v", action="store_true", dest="verbose", default=True)
436 parser.add_option("-q", action="store_false", dest="verbose")
437
438Since default values apply to the *destination* rather than to any particular
439option, and these two options happen to have the same destination, this is
440exactly equivalent::
441
442 parser.add_option("-v", action="store_true", dest="verbose")
443 parser.add_option("-q", action="store_false", dest="verbose", default=True)
444
445Consider this::
446
447 parser.add_option("-v", action="store_true", dest="verbose", default=False)
448 parser.add_option("-q", action="store_false", dest="verbose", default=True)
449
450Again, the default value for ``verbose`` will be ``True``: the last default
451value supplied for any particular destination is the one that counts.
452
453A clearer way to specify default values is the :meth:`set_defaults` method of
454OptionParser, which you can call at any time before calling :meth:`parse_args`::
455
456 parser.set_defaults(verbose=True)
457 parser.add_option(...)
458 (options, args) = parser.parse_args()
459
460As before, the last value specified for a given option destination is the one
461that counts. For clarity, try to use one method or the other of setting default
462values, not both.
463
464
465.. _optparse-generating-help:
466
467Generating help
468^^^^^^^^^^^^^^^
469
470:mod:`optparse`'s ability to generate help and usage text automatically is
471useful for creating user-friendly command-line interfaces. All you have to do
Georg Brandl15a515f2009-09-17 22:11:49 +0000472is supply a :attr:`~Option.help` value for each option, and optionally a short
473usage message for your whole program. Here's an OptionParser populated with
Georg Brandl116aa622007-08-15 14:28:22 +0000474user-friendly (documented) options::
475
476 usage = "usage: %prog [options] arg1 arg2"
477 parser = OptionParser(usage=usage)
478 parser.add_option("-v", "--verbose",
479 action="store_true", dest="verbose", default=True,
480 help="make lots of noise [default]")
481 parser.add_option("-q", "--quiet",
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000482 action="store_false", dest="verbose",
Georg Brandl116aa622007-08-15 14:28:22 +0000483 help="be vewwy quiet (I'm hunting wabbits)")
484 parser.add_option("-f", "--filename",
Georg Brandlee8783d2009-09-16 16:00:31 +0000485 metavar="FILE", help="write output to FILE")
Georg Brandl116aa622007-08-15 14:28:22 +0000486 parser.add_option("-m", "--mode",
487 default="intermediate",
488 help="interaction mode: novice, intermediate, "
489 "or expert [default: %default]")
490
Éric Araujo713d3032010-11-18 16:38:46 +0000491If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
Georg Brandl116aa622007-08-15 14:28:22 +0000492command-line, or if you just call :meth:`parser.print_help`, it prints the
Ezio Melotti383ae952010-01-03 09:06:02 +0000493following to standard output:
494
495.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000496
Georg Brandl121ff822011-01-02 14:23:43 +0000497 Usage: <yourscript> [options] arg1 arg2
Georg Brandl116aa622007-08-15 14:28:22 +0000498
Georg Brandl121ff822011-01-02 14:23:43 +0000499 Options:
Georg Brandl116aa622007-08-15 14:28:22 +0000500 -h, --help show this help message and exit
501 -v, --verbose make lots of noise [default]
502 -q, --quiet be vewwy quiet (I'm hunting wabbits)
503 -f FILE, --filename=FILE
504 write output to FILE
505 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
506 expert [default: intermediate]
507
508(If the help output is triggered by a help option, :mod:`optparse` exits after
509printing the help text.)
510
511There's a lot going on here to help :mod:`optparse` generate the best possible
512help message:
513
514* the script defines its own usage message::
515
516 usage = "usage: %prog [options] arg1 arg2"
517
Éric Araujo713d3032010-11-18 16:38:46 +0000518 :mod:`optparse` expands ``%prog`` in the usage string to the name of the
Georg Brandl15a515f2009-09-17 22:11:49 +0000519 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
520 is then printed before the detailed option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandl121ff822011-01-02 14:23:43 +0000523 default: ``"Usage: %prog [options]"``, which is fine if your script doesn't
Georg Brandl15a515f2009-09-17 22:11:49 +0000524 take any positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526* every option defines a help string, and doesn't worry about line-wrapping---
527 :mod:`optparse` takes care of wrapping lines and making the help output look
528 good.
529
530* options that take a value indicate this fact in their automatically-generated
531 help message, e.g. for the "mode" option::
532
533 -m MODE, --mode=MODE
534
535 Here, "MODE" is called the meta-variable: it stands for the argument that the
Éric Araujo713d3032010-11-18 16:38:46 +0000536 user is expected to supply to ``-m``/``--mode``. By default,
Georg Brandl116aa622007-08-15 14:28:22 +0000537 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandl15a515f2009-09-17 22:11:49 +0000538 that for the meta-variable. Sometimes, that's not what you want---for
Éric Araujo713d3032010-11-18 16:38:46 +0000539 example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
Georg Brandl15a515f2009-09-17 22:11:49 +0000540 resulting in this automatically-generated option description::
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542 -f FILE, --filename=FILE
543
Georg Brandl15a515f2009-09-17 22:11:49 +0000544 This is important for more than just saving space, though: the manually
Éric Araujo713d3032010-11-18 16:38:46 +0000545 written help text uses the meta-variable ``FILE`` to clue the user in that
546 there's a connection between the semi-formal syntax ``-f FILE`` and the informal
Georg Brandl15a515f2009-09-17 22:11:49 +0000547 semantic description "write output to FILE". This is a simple but effective
548 way to make your help text a lot clearer and more useful for end users.
Georg Brandl116aa622007-08-15 14:28:22 +0000549
550* options that have a default value can include ``%default`` in the help
551 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
552 default value. If an option has no default value (or the default value is
553 ``None``), ``%default`` expands to ``none``.
554
Georg Brandl121ff822011-01-02 14:23:43 +0000555Grouping Options
556++++++++++++++++
557
Georg Brandl15a515f2009-09-17 22:11:49 +0000558When dealing with many options, it is convenient to group these options for
559better help output. An :class:`OptionParser` can contain several option groups,
560each of which can contain several options.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000561
Georg Brandl121ff822011-01-02 14:23:43 +0000562An option group is obtained using the class :class:`OptionGroup`:
563
564.. class:: OptionGroup(parser, title, description=None)
565
566 where
567
568 * parser is the :class:`OptionParser` instance the group will be insterted in
569 to
570 * title is the group title
571 * description, optional, is a long description of the group
572
573:class:`OptionGroup` inherits from :class:`OptionContainer` (like
574:class:`OptionParser`) and so the :meth:`add_option` method can be used to add
575an option to the group.
576
577Once all the options are declared, using the :class:`OptionParser` method
578:meth:`add_option_group` the group is added to the previously defined parser.
579
580Continuing with the parser defined in the previous section, adding an
581:class:`OptionGroup` to a parser is easy::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000582
583 group = OptionGroup(parser, "Dangerous Options",
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000584 "Caution: use these options at your own risk. "
585 "It is believed that some of them bite.")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000586 group.add_option("-g", action="store_true", help="Group option.")
587 parser.add_option_group(group)
588
Ezio Melotti383ae952010-01-03 09:06:02 +0000589This would result in the following help output:
590
591.. code-block:: text
Christian Heimesfdab48e2008-01-20 09:06:41 +0000592
Georg Brandl121ff822011-01-02 14:23:43 +0000593 Usage: <yourscript> [options] arg1 arg2
Christian Heimesfdab48e2008-01-20 09:06:41 +0000594
Georg Brandl121ff822011-01-02 14:23:43 +0000595 Options:
596 -h, --help show this help message and exit
597 -v, --verbose make lots of noise [default]
598 -q, --quiet be vewwy quiet (I'm hunting wabbits)
599 -f FILE, --filename=FILE
600 write output to FILE
601 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
602 expert [default: intermediate]
Christian Heimesfdab48e2008-01-20 09:06:41 +0000603
Georg Brandl121ff822011-01-02 14:23:43 +0000604 Dangerous Options:
605 Caution: use these options at your own risk. It is believed that some
606 of them bite.
607
608 -g Group option.
609
Eli Benderskyeeae1492011-11-16 06:02:21 +0200610A bit more complete example might involve using more than one group: still
611extending the previous example::
Georg Brandl121ff822011-01-02 14:23:43 +0000612
613 group = OptionGroup(parser, "Dangerous Options",
614 "Caution: use these options at your own risk. "
615 "It is believed that some of them bite.")
616 group.add_option("-g", action="store_true", help="Group option.")
617 parser.add_option_group(group)
618
619 group = OptionGroup(parser, "Debug Options")
620 group.add_option("-d", "--debug", action="store_true",
621 help="Print debug information")
622 group.add_option("-s", "--sql", action="store_true",
623 help="Print all SQL statements executed")
624 group.add_option("-e", action="store_true", help="Print every action done")
625 parser.add_option_group(group)
626
627that results in the following output:
628
629.. code-block:: text
630
631 Usage: <yourscript> [options] arg1 arg2
632
633 Options:
634 -h, --help show this help message and exit
635 -v, --verbose make lots of noise [default]
636 -q, --quiet be vewwy quiet (I'm hunting wabbits)
637 -f FILE, --filename=FILE
638 write output to FILE
639 -m MODE, --mode=MODE interaction mode: novice, intermediate, or expert
640 [default: intermediate]
641
642 Dangerous Options:
643 Caution: use these options at your own risk. It is believed that some
644 of them bite.
645
646 -g Group option.
647
648 Debug Options:
649 -d, --debug Print debug information
650 -s, --sql Print all SQL statements executed
651 -e Print every action done
652
653Another interesting method, in particular when working programmatically with
654option groups is:
655
656.. method:: OptionParser.get_option_group(opt_str)
657
Eli Benderskye2503582011-07-30 11:14:32 +0300658 Return the :class:`OptionGroup` to which the short or long option
659 string *opt_str* (e.g. ``'-o'`` or ``'--option'``) belongs. If
660 there's no such :class:`OptionGroup`, return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000661
662.. _optparse-printing-version-string:
663
664Printing a version string
665^^^^^^^^^^^^^^^^^^^^^^^^^
666
667Similar to the brief usage string, :mod:`optparse` can also print a version
668string for your program. You have to supply the string as the ``version``
669argument to OptionParser::
670
671 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
672
Éric Araujo713d3032010-11-18 16:38:46 +0000673``%prog`` is expanded just like it is in ``usage``. Apart from that,
Georg Brandl116aa622007-08-15 14:28:22 +0000674``version`` can contain anything you like. When you supply it, :mod:`optparse`
Éric Araujo713d3032010-11-18 16:38:46 +0000675automatically adds a ``--version`` option to your parser. If it encounters
Georg Brandl116aa622007-08-15 14:28:22 +0000676this option on the command line, it expands your ``version`` string (by
Éric Araujo713d3032010-11-18 16:38:46 +0000677replacing ``%prog``), prints it to stdout, and exits.
Georg Brandl116aa622007-08-15 14:28:22 +0000678
679For example, if your script is called ``/usr/bin/foo``::
680
681 $ /usr/bin/foo --version
682 foo 1.0
683
Ezio Melotti1ce43192010-01-04 21:53:17 +0000684The following two methods can be used to print and get the ``version`` string:
685
686.. method:: OptionParser.print_version(file=None)
687
688 Print the version message for the current program (``self.version``) to
689 *file* (default stdout). As with :meth:`print_usage`, any occurrence
Éric Araujo713d3032010-11-18 16:38:46 +0000690 of ``%prog`` in ``self.version`` is replaced with the name of the current
Ezio Melotti1ce43192010-01-04 21:53:17 +0000691 program. Does nothing if ``self.version`` is empty or undefined.
692
693.. method:: OptionParser.get_version()
694
695 Same as :meth:`print_version` but returns the version string instead of
696 printing it.
697
Georg Brandl116aa622007-08-15 14:28:22 +0000698
699.. _optparse-how-optparse-handles-errors:
700
701How :mod:`optparse` handles errors
702^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
703
704There are two broad classes of errors that :mod:`optparse` has to worry about:
705programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandl15a515f2009-09-17 22:11:49 +0000706calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
707option attributes, missing option attributes, etc. These are dealt with in the
708usual way: raise an exception (either :exc:`optparse.OptionError` or
709:exc:`TypeError`) and let the program crash.
Georg Brandl116aa622007-08-15 14:28:22 +0000710
711Handling user errors is much more important, since they are guaranteed to happen
712no matter how stable your code is. :mod:`optparse` can automatically detect
Éric Araujo713d3032010-11-18 16:38:46 +0000713some user errors, such as bad option arguments (passing ``-n 4x`` where
714``-n`` takes an integer argument), missing arguments (``-n`` at the end
715of the command line, where ``-n`` takes an argument of any type). Also,
Georg Brandl15a515f2009-09-17 22:11:49 +0000716you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl116aa622007-08-15 14:28:22 +0000717condition::
718
719 (options, args) = parser.parse_args()
720 [...]
721 if options.a and options.b:
722 parser.error("options -a and -b are mutually exclusive")
723
724In either case, :mod:`optparse` handles the error the same way: it prints the
725program's usage message and an error message to standard error and exits with
726error status 2.
727
Éric Araujo713d3032010-11-18 16:38:46 +0000728Consider the first example above, where the user passes ``4x`` to an option
Georg Brandl116aa622007-08-15 14:28:22 +0000729that takes an integer::
730
731 $ /usr/bin/foo -n 4x
Georg Brandl121ff822011-01-02 14:23:43 +0000732 Usage: foo [options]
Georg Brandl116aa622007-08-15 14:28:22 +0000733
734 foo: error: option -n: invalid integer value: '4x'
735
736Or, where the user fails to pass a value at all::
737
738 $ /usr/bin/foo -n
Georg Brandl121ff822011-01-02 14:23:43 +0000739 Usage: foo [options]
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741 foo: error: -n option requires an argument
742
743:mod:`optparse`\ -generated error messages take care always to mention the
744option involved in the error; be sure to do the same when calling
Georg Brandl15a515f2009-09-17 22:11:49 +0000745:func:`OptionParser.error` from your application code.
Georg Brandl116aa622007-08-15 14:28:22 +0000746
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000747If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000748you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
749and/or :meth:`~OptionParser.error` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000750
751
752.. _optparse-putting-it-all-together:
753
754Putting it all together
755^^^^^^^^^^^^^^^^^^^^^^^
756
757Here's what :mod:`optparse`\ -based scripts usually look like::
758
759 from optparse import OptionParser
760 [...]
761 def main():
762 usage = "usage: %prog [options] arg"
763 parser = OptionParser(usage)
764 parser.add_option("-f", "--file", dest="filename",
765 help="read data from FILENAME")
766 parser.add_option("-v", "--verbose",
767 action="store_true", dest="verbose")
768 parser.add_option("-q", "--quiet",
769 action="store_false", dest="verbose")
770 [...]
771 (options, args) = parser.parse_args()
772 if len(args) != 1:
773 parser.error("incorrect number of arguments")
774 if options.verbose:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000775 print("reading %s..." % options.filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000776 [...]
777
778 if __name__ == "__main__":
779 main()
780
Georg Brandl116aa622007-08-15 14:28:22 +0000781
782.. _optparse-reference-guide:
783
784Reference Guide
785---------------
786
787
788.. _optparse-creating-parser:
789
790Creating the parser
791^^^^^^^^^^^^^^^^^^^
792
Georg Brandl15a515f2009-09-17 22:11:49 +0000793The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000794
Georg Brandl15a515f2009-09-17 22:11:49 +0000795.. class:: OptionParser(...)
Georg Brandl116aa622007-08-15 14:28:22 +0000796
Georg Brandl15a515f2009-09-17 22:11:49 +0000797 The OptionParser constructor has no required arguments, but a number of
798 optional keyword arguments. You should always pass them as keyword
799 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl116aa622007-08-15 14:28:22 +0000800
801 ``usage`` (default: ``"%prog [options]"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000802 The usage summary to print when your program is run incorrectly or with a
803 help option. When :mod:`optparse` prints the usage string, it expands
804 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
805 passed that keyword argument). To suppress a usage message, pass the
806 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl116aa622007-08-15 14:28:22 +0000807
808 ``option_list`` (default: ``[]``)
809 A list of Option objects to populate the parser with. The options in
Georg Brandl15a515f2009-09-17 22:11:49 +0000810 ``option_list`` are added after any options in ``standard_option_list`` (a
811 class attribute that may be set by OptionParser subclasses), but before
812 any version or help options. Deprecated; use :meth:`add_option` after
813 creating the parser instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000814
815 ``option_class`` (default: optparse.Option)
816 Class to use when adding options to the parser in :meth:`add_option`.
817
818 ``version`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000819 A version string to print when the user supplies a version option. If you
820 supply a true value for ``version``, :mod:`optparse` automatically adds a
Éric Araujo713d3032010-11-18 16:38:46 +0000821 version option with the single option string ``--version``. The
822 substring ``%prog`` is expanded the same as for ``usage``.
Georg Brandl116aa622007-08-15 14:28:22 +0000823
824 ``conflict_handler`` (default: ``"error"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000825 Specifies what to do when options with conflicting option strings are
826 added to the parser; see section
827 :ref:`optparse-conflicts-between-options`.
Georg Brandl116aa622007-08-15 14:28:22 +0000828
829 ``description`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000830 A paragraph of text giving a brief overview of your program.
831 :mod:`optparse` reformats this paragraph to fit the current terminal width
832 and prints it when the user requests help (after ``usage``, but before the
833 list of options).
Georg Brandl116aa622007-08-15 14:28:22 +0000834
Georg Brandl15a515f2009-09-17 22:11:49 +0000835 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
836 An instance of optparse.HelpFormatter that will be used for printing help
837 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl116aa622007-08-15 14:28:22 +0000838 IndentedHelpFormatter and TitledHelpFormatter.
839
840 ``add_help_option`` (default: ``True``)
Éric Araujo713d3032010-11-18 16:38:46 +0000841 If true, :mod:`optparse` will add a help option (with option strings ``-h``
842 and ``--help``) to the parser.
Georg Brandl116aa622007-08-15 14:28:22 +0000843
844 ``prog``
Éric Araujo713d3032010-11-18 16:38:46 +0000845 The string to use when expanding ``%prog`` in ``usage`` and ``version``
Georg Brandl116aa622007-08-15 14:28:22 +0000846 instead of ``os.path.basename(sys.argv[0])``.
847
Senthil Kumaran5b58f5e2010-03-23 11:00:53 +0000848 ``epilog`` (default: ``None``)
849 A paragraph of help text to print after the option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851.. _optparse-populating-parser:
852
853Populating the parser
854^^^^^^^^^^^^^^^^^^^^^
855
856There are several ways to populate the parser with options. The preferred way
Georg Brandl15a515f2009-09-17 22:11:49 +0000857is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl116aa622007-08-15 14:28:22 +0000858:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
859
860* pass it an Option instance (as returned by :func:`make_option`)
861
862* pass it any combination of positional and keyword arguments that are
Georg Brandl15a515f2009-09-17 22:11:49 +0000863 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
864 will create the Option instance for you
Georg Brandl116aa622007-08-15 14:28:22 +0000865
866The other alternative is to pass a list of pre-constructed Option instances to
867the OptionParser constructor, as in::
868
869 option_list = [
870 make_option("-f", "--filename",
871 action="store", type="string", dest="filename"),
872 make_option("-q", "--quiet",
873 action="store_false", dest="verbose"),
874 ]
875 parser = OptionParser(option_list=option_list)
876
877(:func:`make_option` is a factory function for creating Option instances;
878currently it is an alias for the Option constructor. A future version of
879:mod:`optparse` may split Option into several classes, and :func:`make_option`
880will pick the right class to instantiate. Do not instantiate Option directly.)
881
882
883.. _optparse-defining-options:
884
885Defining options
886^^^^^^^^^^^^^^^^
887
888Each Option instance represents a set of synonymous command-line option strings,
Éric Araujo713d3032010-11-18 16:38:46 +0000889e.g. ``-f`` and ``--file``. You can specify any number of short or
Georg Brandl116aa622007-08-15 14:28:22 +0000890long option strings, but you must specify at least one overall option string.
891
Georg Brandl15a515f2009-09-17 22:11:49 +0000892The canonical way to create an :class:`Option` instance is with the
893:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl116aa622007-08-15 14:28:22 +0000894
Georg Brandl15a515f2009-09-17 22:11:49 +0000895.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000896
Georg Brandl15a515f2009-09-17 22:11:49 +0000897 To define an option with only a short option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000898
Georg Brandl15a515f2009-09-17 22:11:49 +0000899 parser.add_option("-f", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000900
Georg Brandl15a515f2009-09-17 22:11:49 +0000901 And to define an option with only a long option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000902
Georg Brandl15a515f2009-09-17 22:11:49 +0000903 parser.add_option("--foo", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000904
Georg Brandl15a515f2009-09-17 22:11:49 +0000905 The keyword arguments define attributes of the new Option object. The most
906 important option attribute is :attr:`~Option.action`, and it largely
907 determines which other attributes are relevant or required. If you pass
908 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
909 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl116aa622007-08-15 14:28:22 +0000910
Georg Brandl15a515f2009-09-17 22:11:49 +0000911 An option's *action* determines what :mod:`optparse` does when it encounters
912 this option on the command-line. The standard option actions hard-coded into
913 :mod:`optparse` are:
Georg Brandl116aa622007-08-15 14:28:22 +0000914
Georg Brandl15a515f2009-09-17 22:11:49 +0000915 ``"store"``
916 store this option's argument (default)
Georg Brandl116aa622007-08-15 14:28:22 +0000917
Georg Brandl15a515f2009-09-17 22:11:49 +0000918 ``"store_const"``
919 store a constant value
Georg Brandl116aa622007-08-15 14:28:22 +0000920
Georg Brandl15a515f2009-09-17 22:11:49 +0000921 ``"store_true"``
922 store a true value
Georg Brandl116aa622007-08-15 14:28:22 +0000923
Georg Brandl15a515f2009-09-17 22:11:49 +0000924 ``"store_false"``
925 store a false value
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Georg Brandl15a515f2009-09-17 22:11:49 +0000927 ``"append"``
928 append this option's argument to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000929
Georg Brandl15a515f2009-09-17 22:11:49 +0000930 ``"append_const"``
931 append a constant value to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000932
Georg Brandl15a515f2009-09-17 22:11:49 +0000933 ``"count"``
934 increment a counter by one
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Georg Brandl15a515f2009-09-17 22:11:49 +0000936 ``"callback"``
937 call a specified function
Georg Brandl116aa622007-08-15 14:28:22 +0000938
Georg Brandl15a515f2009-09-17 22:11:49 +0000939 ``"help"``
940 print a usage message including all options and the documentation for them
Georg Brandl116aa622007-08-15 14:28:22 +0000941
Georg Brandl15a515f2009-09-17 22:11:49 +0000942 (If you don't supply an action, the default is ``"store"``. For this action,
943 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
944 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000945
946As you can see, most actions involve storing or updating a value somewhere.
947:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandl15a515f2009-09-17 22:11:49 +0000948``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl116aa622007-08-15 14:28:22 +0000949arguments (and various other values) are stored as attributes of this object,
Georg Brandl15a515f2009-09-17 22:11:49 +0000950according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000951
Georg Brandl15a515f2009-09-17 22:11:49 +0000952For example, when you call ::
Georg Brandl116aa622007-08-15 14:28:22 +0000953
954 parser.parse_args()
955
956one of the first things :mod:`optparse` does is create the ``options`` object::
957
958 options = Values()
959
Georg Brandl15a515f2009-09-17 22:11:49 +0000960If one of the options in this parser is defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +0000961
962 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
963
964and the command-line being parsed includes any of the following::
965
966 -ffoo
967 -f foo
968 --file=foo
969 --file foo
970
Georg Brandl15a515f2009-09-17 22:11:49 +0000971then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl116aa622007-08-15 14:28:22 +0000972
973 options.filename = "foo"
974
Georg Brandl15a515f2009-09-17 22:11:49 +0000975The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
976as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
977one that makes sense for *all* options.
978
979
980.. _optparse-option-attributes:
981
982Option attributes
983^^^^^^^^^^^^^^^^^
984
985The following option attributes may be passed as keyword arguments to
986:meth:`OptionParser.add_option`. If you pass an option attribute that is not
987relevant to a particular option, or fail to pass a required option attribute,
988:mod:`optparse` raises :exc:`OptionError`.
989
990.. attribute:: Option.action
991
992 (default: ``"store"``)
993
994 Determines :mod:`optparse`'s behaviour when this option is seen on the
995 command line; the available options are documented :ref:`here
996 <optparse-standard-option-actions>`.
997
998.. attribute:: Option.type
999
1000 (default: ``"string"``)
1001
1002 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
1003 the available option types are documented :ref:`here
1004 <optparse-standard-option-types>`.
1005
1006.. attribute:: Option.dest
1007
1008 (default: derived from option strings)
1009
1010 If the option's action implies writing or modifying a value somewhere, this
1011 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
1012 attribute of the ``options`` object that :mod:`optparse` builds as it parses
1013 the command line.
1014
1015.. attribute:: Option.default
1016
1017 The value to use for this option's destination if the option is not seen on
1018 the command line. See also :meth:`OptionParser.set_defaults`.
1019
1020.. attribute:: Option.nargs
1021
1022 (default: 1)
1023
1024 How many arguments of type :attr:`~Option.type` should be consumed when this
1025 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
1026 :attr:`~Option.dest`.
1027
1028.. attribute:: Option.const
1029
1030 For actions that store a constant value, the constant value to store.
1031
1032.. attribute:: Option.choices
1033
1034 For options of type ``"choice"``, the list of strings the user may choose
1035 from.
1036
1037.. attribute:: Option.callback
1038
1039 For options with action ``"callback"``, the callable to call when this option
1040 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1041 arguments passed to the callable.
1042
1043.. attribute:: Option.callback_args
1044 Option.callback_kwargs
1045
1046 Additional positional and keyword arguments to pass to ``callback`` after the
1047 four standard callback arguments.
1048
1049.. attribute:: Option.help
1050
1051 Help text to print for this option when listing all available options after
Éric Araujo713d3032010-11-18 16:38:46 +00001052 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
Georg Brandl15a515f2009-09-17 22:11:49 +00001053 no help text is supplied, the option will be listed without help text. To
1054 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
1055
1056.. attribute:: Option.metavar
1057
1058 (default: derived from option strings)
1059
1060 Stand-in for the option argument(s) to use when printing help text. See
1061 section :ref:`optparse-tutorial` for an example.
Georg Brandl116aa622007-08-15 14:28:22 +00001062
1063
1064.. _optparse-standard-option-actions:
1065
1066Standard option actions
1067^^^^^^^^^^^^^^^^^^^^^^^
1068
1069The various option actions all have slightly different requirements and effects.
1070Most actions have several relevant option attributes which you may specify to
1071guide :mod:`optparse`'s behaviour; a few have required attributes, which you
1072must specify for any option using that action.
1073
Georg Brandl15a515f2009-09-17 22:11:49 +00001074* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1075 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001076
1077 The option must be followed by an argument, which is converted to a value
Georg Brandl15a515f2009-09-17 22:11:49 +00001078 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1079 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1080 command line; all will be converted according to :attr:`~Option.type` and
1081 stored to :attr:`~Option.dest` as a tuple. See the
1082 :ref:`optparse-standard-option-types` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001083
Georg Brandl15a515f2009-09-17 22:11:49 +00001084 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1085 defaults to ``"choice"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001086
Georg Brandl15a515f2009-09-17 22:11:49 +00001087 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001088
Georg Brandl15a515f2009-09-17 22:11:49 +00001089 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
Éric Araujo713d3032010-11-18 16:38:46 +00001090 from the first long option string (e.g., ``--foo-bar`` implies
Georg Brandl15a515f2009-09-17 22:11:49 +00001091 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
Éric Araujo713d3032010-11-18 16:38:46 +00001092 destination from the first short option string (e.g., ``-f`` implies ``f``).
Georg Brandl116aa622007-08-15 14:28:22 +00001093
1094 Example::
1095
1096 parser.add_option("-f")
1097 parser.add_option("-p", type="float", nargs=3, dest="point")
1098
Georg Brandl15a515f2009-09-17 22:11:49 +00001099 As it parses the command line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001100
1101 -f foo.txt -p 1 -3.5 4 -fbar.txt
1102
Georg Brandl15a515f2009-09-17 22:11:49 +00001103 :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +00001104
1105 options.f = "foo.txt"
1106 options.point = (1.0, -3.5, 4.0)
1107 options.f = "bar.txt"
1108
Georg Brandl15a515f2009-09-17 22:11:49 +00001109* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1110 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001111
Georg Brandl15a515f2009-09-17 22:11:49 +00001112 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001113
1114 Example::
1115
1116 parser.add_option("-q", "--quiet",
1117 action="store_const", const=0, dest="verbose")
1118 parser.add_option("-v", "--verbose",
1119 action="store_const", const=1, dest="verbose")
1120 parser.add_option("--noisy",
1121 action="store_const", const=2, dest="verbose")
1122
Éric Araujo713d3032010-11-18 16:38:46 +00001123 If ``--noisy`` is seen, :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +00001124
1125 options.verbose = 2
1126
Georg Brandl15a515f2009-09-17 22:11:49 +00001127* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001128
Georg Brandl15a515f2009-09-17 22:11:49 +00001129 A special case of ``"store_const"`` that stores a true value to
1130 :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001131
Georg Brandl15a515f2009-09-17 22:11:49 +00001132* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001133
Georg Brandl15a515f2009-09-17 22:11:49 +00001134 Like ``"store_true"``, but stores a false value.
Georg Brandl116aa622007-08-15 14:28:22 +00001135
1136 Example::
1137
1138 parser.add_option("--clobber", action="store_true", dest="clobber")
1139 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1140
Georg Brandl15a515f2009-09-17 22:11:49 +00001141* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1142 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001143
1144 The option must be followed by an argument, which is appended to the list in
Georg Brandl15a515f2009-09-17 22:11:49 +00001145 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1146 supplied, an empty list is automatically created when :mod:`optparse` first
1147 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1148 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1149 is appended to :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001150
Georg Brandl15a515f2009-09-17 22:11:49 +00001151 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1152 for the ``"store"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001153
1154 Example::
1155
1156 parser.add_option("-t", "--tracks", action="append", type="int")
1157
Éric Araujo713d3032010-11-18 16:38:46 +00001158 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
Georg Brandl116aa622007-08-15 14:28:22 +00001159 of::
1160
1161 options.tracks = []
1162 options.tracks.append(int("3"))
1163
Éric Araujo713d3032010-11-18 16:38:46 +00001164 If, a little later on, ``--tracks=4`` is seen, it does::
Georg Brandl116aa622007-08-15 14:28:22 +00001165
1166 options.tracks.append(int("4"))
1167
R David Murray14d66a92012-09-08 16:45:35 -04001168 The ``append`` action calls the ``append`` method on the current value of the
1169 option. This means that any default value specified must have an ``append``
1170 method. It also means that if the default value is non-empty, the default
1171 elements will be present in the parsed value for the option, with any values
1172 from the command line appended after those default values::
1173
1174 >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
1175 >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
1176 >>> opts.files
1177 ['~/.mypkg/defaults', 'overrides.mypkg']
1178
Georg Brandl15a515f2009-09-17 22:11:49 +00001179* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1180 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001181
Georg Brandl15a515f2009-09-17 22:11:49 +00001182 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1183 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1184 ``None``, and an empty list is automatically created the first time the option
1185 is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +00001186
Georg Brandl15a515f2009-09-17 22:11:49 +00001187* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001188
Georg Brandl15a515f2009-09-17 22:11:49 +00001189 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1190 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1191 first time.
Georg Brandl116aa622007-08-15 14:28:22 +00001192
1193 Example::
1194
1195 parser.add_option("-v", action="count", dest="verbosity")
1196
Éric Araujo713d3032010-11-18 16:38:46 +00001197 The first time ``-v`` is seen on the command line, :mod:`optparse` does the
Georg Brandl116aa622007-08-15 14:28:22 +00001198 equivalent of::
1199
1200 options.verbosity = 0
1201 options.verbosity += 1
1202
Éric Araujo713d3032010-11-18 16:38:46 +00001203 Every subsequent occurrence of ``-v`` results in ::
Georg Brandl116aa622007-08-15 14:28:22 +00001204
1205 options.verbosity += 1
1206
Georg Brandl15a515f2009-09-17 22:11:49 +00001207* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1208 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1209 :attr:`~Option.callback_kwargs`]
Georg Brandl116aa622007-08-15 14:28:22 +00001210
Georg Brandl15a515f2009-09-17 22:11:49 +00001211 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001212
1213 func(option, opt_str, value, parser, *args, **kwargs)
1214
1215 See section :ref:`optparse-option-callbacks` for more detail.
1216
Georg Brandl15a515f2009-09-17 22:11:49 +00001217* ``"help"``
Georg Brandl116aa622007-08-15 14:28:22 +00001218
Georg Brandl15a515f2009-09-17 22:11:49 +00001219 Prints a complete help message for all the options in the current option
1220 parser. The help message is constructed from the ``usage`` string passed to
1221 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1222 option.
Georg Brandl116aa622007-08-15 14:28:22 +00001223
Georg Brandl15a515f2009-09-17 22:11:49 +00001224 If no :attr:`~Option.help` string is supplied for an option, it will still be
1225 listed in the help message. To omit an option entirely, use the special value
1226 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl116aa622007-08-15 14:28:22 +00001227
Georg Brandl15a515f2009-09-17 22:11:49 +00001228 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1229 OptionParsers, so you do not normally need to create one.
Georg Brandl116aa622007-08-15 14:28:22 +00001230
1231 Example::
1232
1233 from optparse import OptionParser, SUPPRESS_HELP
1234
Georg Brandlee8783d2009-09-16 16:00:31 +00001235 # usually, a help option is added automatically, but that can
1236 # be suppressed using the add_help_option argument
1237 parser = OptionParser(add_help_option=False)
1238
1239 parser.add_option("-h", "--help", action="help")
Georg Brandl116aa622007-08-15 14:28:22 +00001240 parser.add_option("-v", action="store_true", dest="verbose",
1241 help="Be moderately verbose")
1242 parser.add_option("--file", dest="filename",
Georg Brandlee8783d2009-09-16 16:00:31 +00001243 help="Input file to read data from")
Georg Brandl116aa622007-08-15 14:28:22 +00001244 parser.add_option("--secret", help=SUPPRESS_HELP)
1245
Éric Araujo713d3032010-11-18 16:38:46 +00001246 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
Georg Brandl15a515f2009-09-17 22:11:49 +00001247 it will print something like the following help message to stdout (assuming
Ezio Melotti383ae952010-01-03 09:06:02 +00001248 ``sys.argv[0]`` is ``"foo.py"``):
1249
1250 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +00001251
Georg Brandl121ff822011-01-02 14:23:43 +00001252 Usage: foo.py [options]
Georg Brandl116aa622007-08-15 14:28:22 +00001253
Georg Brandl121ff822011-01-02 14:23:43 +00001254 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001255 -h, --help Show this help message and exit
1256 -v Be moderately verbose
1257 --file=FILENAME Input file to read data from
1258
1259 After printing the help message, :mod:`optparse` terminates your process with
1260 ``sys.exit(0)``.
1261
Georg Brandl15a515f2009-09-17 22:11:49 +00001262* ``"version"``
Georg Brandl116aa622007-08-15 14:28:22 +00001263
Georg Brandl15a515f2009-09-17 22:11:49 +00001264 Prints the version number supplied to the OptionParser to stdout and exits.
1265 The version number is actually formatted and printed by the
1266 ``print_version()`` method of OptionParser. Generally only relevant if the
1267 ``version`` argument is supplied to the OptionParser constructor. As with
1268 :attr:`~Option.help` options, you will rarely create ``version`` options,
1269 since :mod:`optparse` automatically adds them when needed.
Georg Brandl116aa622007-08-15 14:28:22 +00001270
1271
1272.. _optparse-standard-option-types:
1273
1274Standard option types
1275^^^^^^^^^^^^^^^^^^^^^
1276
Georg Brandl15a515f2009-09-17 22:11:49 +00001277:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1278``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1279option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +00001280
1281Arguments to string options are not checked or converted in any way: the text on
1282the command line is stored in the destination (or passed to the callback) as-is.
1283
Georg Brandl15a515f2009-09-17 22:11:49 +00001284Integer arguments (type ``"int"``) are parsed as follows:
Georg Brandl116aa622007-08-15 14:28:22 +00001285
1286* if the number starts with ``0x``, it is parsed as a hexadecimal number
1287
1288* if the number starts with ``0``, it is parsed as an octal number
1289
Georg Brandl9afde1c2007-11-01 20:32:30 +00001290* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl116aa622007-08-15 14:28:22 +00001291
1292* otherwise, the number is parsed as a decimal number
1293
1294
Georg Brandl15a515f2009-09-17 22:11:49 +00001295The conversion is done by calling :func:`int` with the appropriate base (2, 8,
129610, or 16). If this fails, so will :mod:`optparse`, although with a more useful
Georg Brandl5c106642007-11-29 17:41:05 +00001297error message.
Georg Brandl116aa622007-08-15 14:28:22 +00001298
Georg Brandl15a515f2009-09-17 22:11:49 +00001299``"float"`` and ``"complex"`` option arguments are converted directly with
1300:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl116aa622007-08-15 14:28:22 +00001301
Georg Brandl15a515f2009-09-17 22:11:49 +00001302``"choice"`` options are a subtype of ``"string"`` options. The
Georg Brandl682d7e02010-10-06 10:26:05 +00001303:attr:`~Option.choices` option attribute (a sequence of strings) defines the
Georg Brandl15a515f2009-09-17 22:11:49 +00001304set of allowed option arguments. :func:`optparse.check_choice` compares
1305user-supplied option arguments against this master list and raises
1306:exc:`OptionValueError` if an invalid string is given.
Georg Brandl116aa622007-08-15 14:28:22 +00001307
1308
1309.. _optparse-parsing-arguments:
1310
1311Parsing arguments
1312^^^^^^^^^^^^^^^^^
1313
1314The whole point of creating and populating an OptionParser is to call its
1315:meth:`parse_args` method::
1316
1317 (options, args) = parser.parse_args(args=None, values=None)
1318
1319where the input parameters are
1320
1321``args``
1322 the list of arguments to process (default: ``sys.argv[1:]``)
1323
1324``values``
Georg Brandl09410122010-08-01 06:53:28 +00001325 a :class:`optparse.Values` object to store option arguments in (default: a
1326 new instance of :class:`Values`) -- if you give an existing object, the
1327 option defaults will not be initialized on it
Georg Brandl116aa622007-08-15 14:28:22 +00001328
1329and the return values are
1330
1331``options``
Georg Brandla6053b42009-09-01 08:11:14 +00001332 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl116aa622007-08-15 14:28:22 +00001333 instance created by :mod:`optparse`
1334
1335``args``
1336 the leftover positional arguments after all options have been processed
1337
1338The most common usage is to supply neither keyword argument. If you supply
Georg Brandl15a515f2009-09-17 22:11:49 +00001339``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl116aa622007-08-15 14:28:22 +00001340for every option argument stored to an option destination) and returned by
1341:meth:`parse_args`.
1342
1343If :meth:`parse_args` encounters any errors in the argument list, it calls the
1344OptionParser's :meth:`error` method with an appropriate end-user error message.
1345This ultimately terminates your process with an exit status of 2 (the
1346traditional Unix exit status for command-line errors).
1347
1348
1349.. _optparse-querying-manipulating-option-parser:
1350
1351Querying and manipulating your option parser
1352^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1353
Georg Brandl15a515f2009-09-17 22:11:49 +00001354The default behavior of the option parser can be customized slightly, and you
1355can also poke around your option parser and see what's there. OptionParser
1356provides several methods to help you out:
Georg Brandl116aa622007-08-15 14:28:22 +00001357
Georg Brandl15a515f2009-09-17 22:11:49 +00001358.. method:: OptionParser.disable_interspersed_args()
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001359
Éric Araujo713d3032010-11-18 16:38:46 +00001360 Set parsing to stop on the first non-option. For example, if ``-a`` and
1361 ``-b`` are both simple options that take no arguments, :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001362 normally accepts this syntax::
Georg Brandl116aa622007-08-15 14:28:22 +00001363
Georg Brandl15a515f2009-09-17 22:11:49 +00001364 prog -a arg1 -b arg2
1365
1366 and treats it as equivalent to ::
1367
1368 prog -a -b arg1 arg2
1369
1370 To disable this feature, call :meth:`disable_interspersed_args`. This
1371 restores traditional Unix syntax, where option parsing stops with the first
1372 non-option argument.
1373
1374 Use this if you have a command processor which runs another command which has
1375 options of its own and you want to make sure these options don't get
1376 confused. For example, each command might have a different set of options.
1377
1378.. method:: OptionParser.enable_interspersed_args()
1379
1380 Set parsing to not stop on the first non-option, allowing interspersing
1381 switches with command arguments. This is the default behavior.
1382
1383.. method:: OptionParser.get_option(opt_str)
1384
1385 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl116aa622007-08-15 14:28:22 +00001386 no options have that option string.
1387
Georg Brandl15a515f2009-09-17 22:11:49 +00001388.. method:: OptionParser.has_option(opt_str)
1389
1390 Return true if the OptionParser has an option with option string *opt_str*
Éric Araujo713d3032010-11-18 16:38:46 +00001391 (e.g., ``-q`` or ``--verbose``).
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001392
Georg Brandl15a515f2009-09-17 22:11:49 +00001393.. method:: OptionParser.remove_option(opt_str)
1394
1395 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1396 option is removed. If that option provided any other option strings, all of
1397 those option strings become invalid. If *opt_str* does not occur in any
1398 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001399
1400
1401.. _optparse-conflicts-between-options:
1402
1403Conflicts between options
1404^^^^^^^^^^^^^^^^^^^^^^^^^
1405
1406If you're not careful, it's easy to define options with conflicting option
1407strings::
1408
1409 parser.add_option("-n", "--dry-run", ...)
1410 [...]
1411 parser.add_option("-n", "--noisy", ...)
1412
1413(This is particularly true if you've defined your own OptionParser subclass with
1414some standard options.)
1415
1416Every time you add an option, :mod:`optparse` checks for conflicts with existing
1417options. If it finds any, it invokes the current conflict-handling mechanism.
1418You can set the conflict-handling mechanism either in the constructor::
1419
1420 parser = OptionParser(..., conflict_handler=handler)
1421
1422or with a separate call::
1423
1424 parser.set_conflict_handler(handler)
1425
1426The available conflict handlers are:
1427
Georg Brandl15a515f2009-09-17 22:11:49 +00001428 ``"error"`` (default)
1429 assume option conflicts are a programming error and raise
1430 :exc:`OptionConflictError`
Georg Brandl116aa622007-08-15 14:28:22 +00001431
Georg Brandl15a515f2009-09-17 22:11:49 +00001432 ``"resolve"``
Georg Brandl116aa622007-08-15 14:28:22 +00001433 resolve option conflicts intelligently (see below)
1434
1435
Benjamin Petersone5384b02008-10-04 22:00:42 +00001436As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl116aa622007-08-15 14:28:22 +00001437intelligently and add conflicting options to it::
1438
1439 parser = OptionParser(conflict_handler="resolve")
1440 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1441 parser.add_option("-n", "--noisy", ..., help="be noisy")
1442
1443At this point, :mod:`optparse` detects that a previously-added option is already
Éric Araujo713d3032010-11-18 16:38:46 +00001444using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1445it resolves the situation by removing ``-n`` from the earlier option's list of
1446option strings. Now ``--dry-run`` is the only way for the user to activate
Georg Brandl116aa622007-08-15 14:28:22 +00001447that option. If the user asks for help, the help message will reflect that::
1448
Georg Brandl121ff822011-01-02 14:23:43 +00001449 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001450 --dry-run do no harm
1451 [...]
1452 -n, --noisy be noisy
1453
1454It's possible to whittle away the option strings for a previously-added option
1455until there are none left, and the user has no way of invoking that option from
1456the command-line. In that case, :mod:`optparse` removes that option completely,
1457so it doesn't show up in help text or anywhere else. Carrying on with our
1458existing OptionParser::
1459
1460 parser.add_option("--dry-run", ..., help="new dry-run option")
1461
Éric Araujo713d3032010-11-18 16:38:46 +00001462At this point, the original ``-n``/``--dry-run`` option is no longer
Georg Brandl116aa622007-08-15 14:28:22 +00001463accessible, so :mod:`optparse` removes it, leaving this help text::
1464
Georg Brandl121ff822011-01-02 14:23:43 +00001465 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001466 [...]
1467 -n, --noisy be noisy
1468 --dry-run new dry-run option
1469
1470
1471.. _optparse-cleanup:
1472
1473Cleanup
1474^^^^^^^
1475
1476OptionParser instances have several cyclic references. This should not be a
1477problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandl15a515f2009-09-17 22:11:49 +00001478references explicitly by calling :meth:`~OptionParser.destroy` on your
1479OptionParser once you are done with it. This is particularly useful in
1480long-running applications where large object graphs are reachable from your
1481OptionParser.
Georg Brandl116aa622007-08-15 14:28:22 +00001482
1483
1484.. _optparse-other-methods:
1485
1486Other methods
1487^^^^^^^^^^^^^
1488
1489OptionParser supports several other public methods:
1490
Georg Brandl15a515f2009-09-17 22:11:49 +00001491.. method:: OptionParser.set_usage(usage)
Georg Brandl116aa622007-08-15 14:28:22 +00001492
Georg Brandl15a515f2009-09-17 22:11:49 +00001493 Set the usage string according to the rules described above for the ``usage``
1494 constructor keyword argument. Passing ``None`` sets the default usage
1495 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl116aa622007-08-15 14:28:22 +00001496
Ezio Melotti1ce43192010-01-04 21:53:17 +00001497.. method:: OptionParser.print_usage(file=None)
1498
1499 Print the usage message for the current program (``self.usage``) to *file*
Éric Araujo713d3032010-11-18 16:38:46 +00001500 (default stdout). Any occurrence of the string ``%prog`` in ``self.usage``
Ezio Melotti1ce43192010-01-04 21:53:17 +00001501 is replaced with the name of the current program. Does nothing if
1502 ``self.usage`` is empty or not defined.
1503
1504.. method:: OptionParser.get_usage()
1505
1506 Same as :meth:`print_usage` but returns the usage string instead of
1507 printing it.
1508
Georg Brandl15a515f2009-09-17 22:11:49 +00001509.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +00001510
Georg Brandl15a515f2009-09-17 22:11:49 +00001511 Set default values for several option destinations at once. Using
1512 :meth:`set_defaults` is the preferred way to set default values for options,
1513 since multiple options can share the same destination. For example, if
1514 several "mode" options all set the same destination, any one of them can set
1515 the default, and the last one wins::
Georg Brandl116aa622007-08-15 14:28:22 +00001516
Georg Brandl15a515f2009-09-17 22:11:49 +00001517 parser.add_option("--advanced", action="store_const",
1518 dest="mode", const="advanced",
1519 default="novice") # overridden below
1520 parser.add_option("--novice", action="store_const",
1521 dest="mode", const="novice",
1522 default="advanced") # overrides above setting
Georg Brandl116aa622007-08-15 14:28:22 +00001523
Georg Brandl15a515f2009-09-17 22:11:49 +00001524 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl116aa622007-08-15 14:28:22 +00001525
Georg Brandl15a515f2009-09-17 22:11:49 +00001526 parser.set_defaults(mode="advanced")
1527 parser.add_option("--advanced", action="store_const",
1528 dest="mode", const="advanced")
1529 parser.add_option("--novice", action="store_const",
1530 dest="mode", const="novice")
Georg Brandl116aa622007-08-15 14:28:22 +00001531
Georg Brandl116aa622007-08-15 14:28:22 +00001532
1533.. _optparse-option-callbacks:
1534
1535Option Callbacks
1536----------------
1537
1538When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1539needs, you have two choices: extend :mod:`optparse` or define a callback option.
1540Extending :mod:`optparse` is more general, but overkill for a lot of simple
1541cases. Quite often a simple callback is all you need.
1542
1543There are two steps to defining a callback option:
1544
Georg Brandl15a515f2009-09-17 22:11:49 +00001545* define the option itself using the ``"callback"`` action
Georg Brandl116aa622007-08-15 14:28:22 +00001546
1547* write the callback; this is a function (or method) that takes at least four
1548 arguments, as described below
1549
1550
1551.. _optparse-defining-callback-option:
1552
1553Defining a callback option
1554^^^^^^^^^^^^^^^^^^^^^^^^^^
1555
1556As always, the easiest way to define a callback option is by using the
Georg Brandl15a515f2009-09-17 22:11:49 +00001557:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1558only option attribute you must specify is ``callback``, the function to call::
Georg Brandl116aa622007-08-15 14:28:22 +00001559
1560 parser.add_option("-c", action="callback", callback=my_callback)
1561
1562``callback`` is a function (or other callable object), so you must have already
1563defined ``my_callback()`` when you create this callback option. In this simple
Éric Araujo713d3032010-11-18 16:38:46 +00001564case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
Georg Brandl116aa622007-08-15 14:28:22 +00001565which usually means that the option takes no arguments---the mere presence of
Éric Araujo713d3032010-11-18 16:38:46 +00001566``-c`` on the command-line is all it needs to know. In some
Georg Brandl116aa622007-08-15 14:28:22 +00001567circumstances, though, you might want your callback to consume an arbitrary
1568number of command-line arguments. This is where writing callbacks gets tricky;
1569it's covered later in this section.
1570
1571:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandl15a515f2009-09-17 22:11:49 +00001572will only pass additional arguments if you specify them via
1573:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1574minimal callback function signature is::
Georg Brandl116aa622007-08-15 14:28:22 +00001575
1576 def my_callback(option, opt, value, parser):
1577
1578The four arguments to a callback are described below.
1579
1580There are several other option attributes that you can supply when you define a
1581callback option:
1582
Georg Brandl15a515f2009-09-17 22:11:49 +00001583:attr:`~Option.type`
1584 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1585 instructs :mod:`optparse` to consume one argument and convert it to
1586 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1587 though, :mod:`optparse` passes it to your callback function.
Georg Brandl116aa622007-08-15 14:28:22 +00001588
Georg Brandl15a515f2009-09-17 22:11:49 +00001589:attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001590 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001591 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1592 :attr:`~Option.type`. It then passes a tuple of converted values to your
1593 callback.
Georg Brandl116aa622007-08-15 14:28:22 +00001594
Georg Brandl15a515f2009-09-17 22:11:49 +00001595:attr:`~Option.callback_args`
Georg Brandl116aa622007-08-15 14:28:22 +00001596 a tuple of extra positional arguments to pass to the callback
1597
Georg Brandl15a515f2009-09-17 22:11:49 +00001598:attr:`~Option.callback_kwargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001599 a dictionary of extra keyword arguments to pass to the callback
1600
1601
1602.. _optparse-how-callbacks-called:
1603
1604How callbacks are called
1605^^^^^^^^^^^^^^^^^^^^^^^^
1606
1607All callbacks are called as follows::
1608
1609 func(option, opt_str, value, parser, *args, **kwargs)
1610
1611where
1612
1613``option``
1614 is the Option instance that's calling the callback
1615
1616``opt_str``
1617 is the option string seen on the command-line that's triggering the callback.
Georg Brandl15a515f2009-09-17 22:11:49 +00001618 (If an abbreviated long option was used, ``opt_str`` will be the full,
Éric Araujo713d3032010-11-18 16:38:46 +00001619 canonical option string---e.g. if the user puts ``--foo`` on the
1620 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
Georg Brandl15a515f2009-09-17 22:11:49 +00001621 ``"--foobar"``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001622
1623``value``
1624 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001625 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1626 the type implied by the option's type. If :attr:`~Option.type` for this option is
1627 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001628 > 1, ``value`` will be a tuple of values of the appropriate type.
1629
1630``parser``
Georg Brandl15a515f2009-09-17 22:11:49 +00001631 is the OptionParser instance driving the whole thing, mainly useful because
1632 you can access some other interesting data through its instance attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001633
1634 ``parser.largs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001635 the current list of leftover arguments, ie. arguments that have been
1636 consumed but are neither options nor option arguments. Feel free to modify
1637 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1638 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001639
1640 ``parser.rargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001641 the current list of remaining arguments, ie. with ``opt_str`` and
1642 ``value`` (if applicable) removed, and only the arguments following them
1643 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1644 arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001645
1646 ``parser.values``
1647 the object where option values are by default stored (an instance of
Georg Brandl15a515f2009-09-17 22:11:49 +00001648 optparse.OptionValues). This lets callbacks use the same mechanism as the
1649 rest of :mod:`optparse` for storing option values; you don't need to mess
1650 around with globals or closures. You can also access or modify the
1651 value(s) of any options already encountered on the command-line.
Georg Brandl116aa622007-08-15 14:28:22 +00001652
1653``args``
Georg Brandl15a515f2009-09-17 22:11:49 +00001654 is a tuple of arbitrary positional arguments supplied via the
1655 :attr:`~Option.callback_args` option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001656
1657``kwargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001658 is a dictionary of arbitrary keyword arguments supplied via
1659 :attr:`~Option.callback_kwargs`.
Georg Brandl116aa622007-08-15 14:28:22 +00001660
1661
1662.. _optparse-raising-errors-in-callback:
1663
1664Raising errors in a callback
1665^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1666
Georg Brandl15a515f2009-09-17 22:11:49 +00001667The callback function should raise :exc:`OptionValueError` if there are any
1668problems with the option or its argument(s). :mod:`optparse` catches this and
1669terminates the program, printing the error message you supply to stderr. Your
1670message should be clear, concise, accurate, and mention the option at fault.
1671Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl116aa622007-08-15 14:28:22 +00001672
1673
1674.. _optparse-callback-example-1:
1675
1676Callback example 1: trivial callback
1677^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1678
1679Here's an example of a callback option that takes no arguments, and simply
1680records that the option was seen::
1681
1682 def record_foo_seen(option, opt_str, value, parser):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001683 parser.values.saw_foo = True
Georg Brandl116aa622007-08-15 14:28:22 +00001684
1685 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1686
Georg Brandl15a515f2009-09-17 22:11:49 +00001687Of course, you could do that with the ``"store_true"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001688
1689
1690.. _optparse-callback-example-2:
1691
1692Callback example 2: check option order
1693^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1694
Éric Araujo713d3032010-11-18 16:38:46 +00001695Here's a slightly more interesting example: record the fact that ``-a`` is
1696seen, but blow up if it comes after ``-b`` in the command-line. ::
Georg Brandl116aa622007-08-15 14:28:22 +00001697
1698 def check_order(option, opt_str, value, parser):
1699 if parser.values.b:
1700 raise OptionValueError("can't use -a after -b")
1701 parser.values.a = 1
1702 [...]
1703 parser.add_option("-a", action="callback", callback=check_order)
1704 parser.add_option("-b", action="store_true", dest="b")
1705
1706
1707.. _optparse-callback-example-3:
1708
1709Callback example 3: check option order (generalized)
1710^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1711
1712If you want to re-use this callback for several similar options (set a flag, but
Éric Araujo713d3032010-11-18 16:38:46 +00001713blow up if ``-b`` has already been seen), it needs a bit of work: the error
Georg Brandl116aa622007-08-15 14:28:22 +00001714message and the flag that it sets must be generalized. ::
1715
1716 def check_order(option, opt_str, value, parser):
1717 if parser.values.b:
1718 raise OptionValueError("can't use %s after -b" % opt_str)
1719 setattr(parser.values, option.dest, 1)
1720 [...]
1721 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1722 parser.add_option("-b", action="store_true", dest="b")
1723 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1724
1725
1726.. _optparse-callback-example-4:
1727
1728Callback example 4: check arbitrary condition
1729^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1730
1731Of course, you could put any condition in there---you're not limited to checking
1732the values of already-defined options. For example, if you have options that
1733should not be called when the moon is full, all you have to do is this::
1734
1735 def check_moon(option, opt_str, value, parser):
1736 if is_moon_full():
1737 raise OptionValueError("%s option invalid when moon is full"
1738 % opt_str)
1739 setattr(parser.values, option.dest, 1)
1740 [...]
1741 parser.add_option("--foo",
1742 action="callback", callback=check_moon, dest="foo")
1743
1744(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1745
1746
1747.. _optparse-callback-example-5:
1748
1749Callback example 5: fixed arguments
1750^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1751
1752Things get slightly more interesting when you define callback options that take
1753a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandl15a515f2009-09-17 22:11:49 +00001754is similar to defining a ``"store"`` or ``"append"`` option: if you define
1755:attr:`~Option.type`, then the option takes one argument that must be
1756convertible to that type; if you further define :attr:`~Option.nargs`, then the
1757option takes :attr:`~Option.nargs` arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001758
Georg Brandl15a515f2009-09-17 22:11:49 +00001759Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl116aa622007-08-15 14:28:22 +00001760
1761 def store_value(option, opt_str, value, parser):
1762 setattr(parser.values, option.dest, value)
1763 [...]
1764 parser.add_option("--foo",
1765 action="callback", callback=store_value,
1766 type="int", nargs=3, dest="foo")
1767
1768Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1769them to integers for you; all you have to do is store them. (Or whatever;
1770obviously you don't need a callback for this example.)
1771
1772
1773.. _optparse-callback-example-6:
1774
1775Callback example 6: variable arguments
1776^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1777
1778Things get hairy when you want an option to take a variable number of arguments.
1779For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1780built-in capabilities for it. And you have to deal with certain intricacies of
1781conventional Unix command-line parsing that :mod:`optparse` normally handles for
1782you. In particular, callbacks should implement the conventional rules for bare
Éric Araujo713d3032010-11-18 16:38:46 +00001783``--`` and ``-`` arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001784
Éric Araujo713d3032010-11-18 16:38:46 +00001785* either ``--`` or ``-`` can be option arguments
Georg Brandl116aa622007-08-15 14:28:22 +00001786
Éric Araujo713d3032010-11-18 16:38:46 +00001787* bare ``--`` (if not the argument to some option): halt command-line
1788 processing and discard the ``--``
Georg Brandl116aa622007-08-15 14:28:22 +00001789
Éric Araujo713d3032010-11-18 16:38:46 +00001790* bare ``-`` (if not the argument to some option): halt command-line
1791 processing but keep the ``-`` (append it to ``parser.largs``)
Georg Brandl116aa622007-08-15 14:28:22 +00001792
1793If you want an option that takes a variable number of arguments, there are
1794several subtle, tricky issues to worry about. The exact implementation you
1795choose will be based on which trade-offs you're willing to make for your
1796application (which is why :mod:`optparse` doesn't support this sort of thing
1797directly).
1798
1799Nevertheless, here's a stab at a callback for an option with variable
1800arguments::
1801
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001802 def vararg_callback(option, opt_str, value, parser):
1803 assert value is None
1804 value = []
Georg Brandl116aa622007-08-15 14:28:22 +00001805
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001806 def floatable(str):
1807 try:
1808 float(str)
1809 return True
1810 except ValueError:
1811 return False
Georg Brandl116aa622007-08-15 14:28:22 +00001812
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001813 for arg in parser.rargs:
1814 # stop on --foo like options
1815 if arg[:2] == "--" and len(arg) > 2:
1816 break
1817 # stop on -a, but not on -3 or -3.0
1818 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1819 break
1820 value.append(arg)
1821
1822 del parser.rargs[:len(value)]
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001823 setattr(parser.values, option.dest, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001824
1825 [...]
Benjamin Petersonae5360b2008-09-08 23:05:23 +00001826 parser.add_option("-c", "--callback", dest="vararg_attr",
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001827 action="callback", callback=vararg_callback)
Georg Brandl116aa622007-08-15 14:28:22 +00001828
Georg Brandl116aa622007-08-15 14:28:22 +00001829
1830.. _optparse-extending-optparse:
1831
1832Extending :mod:`optparse`
1833-------------------------
1834
1835Since the two major controlling factors in how :mod:`optparse` interprets
1836command-line options are the action and type of each option, the most likely
1837direction of extension is to add new actions and new types.
1838
1839
1840.. _optparse-adding-new-types:
1841
1842Adding new types
1843^^^^^^^^^^^^^^^^
1844
1845To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandl15a515f2009-09-17 22:11:49 +00001846:class:`Option` class. This class has a couple of attributes that define
1847:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl116aa622007-08-15 14:28:22 +00001848
Georg Brandl15a515f2009-09-17 22:11:49 +00001849.. attribute:: Option.TYPES
Georg Brandl116aa622007-08-15 14:28:22 +00001850
Georg Brandl15a515f2009-09-17 22:11:49 +00001851 A tuple of type names; in your subclass, simply define a new tuple
1852 :attr:`TYPES` that builds on the standard one.
Georg Brandl116aa622007-08-15 14:28:22 +00001853
Georg Brandl15a515f2009-09-17 22:11:49 +00001854.. attribute:: Option.TYPE_CHECKER
Georg Brandl116aa622007-08-15 14:28:22 +00001855
Georg Brandl15a515f2009-09-17 22:11:49 +00001856 A dictionary mapping type names to type-checking functions. A type-checking
1857 function has the following signature::
Georg Brandl116aa622007-08-15 14:28:22 +00001858
Georg Brandl15a515f2009-09-17 22:11:49 +00001859 def check_mytype(option, opt, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001860
Georg Brandl15a515f2009-09-17 22:11:49 +00001861 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
Éric Araujo713d3032010-11-18 16:38:46 +00001862 (e.g., ``-f``), and ``value`` is the string from the command line that must
Georg Brandl15a515f2009-09-17 22:11:49 +00001863 be checked and converted to your desired type. ``check_mytype()`` should
1864 return an object of the hypothetical type ``mytype``. The value returned by
1865 a type-checking function will wind up in the OptionValues instance returned
1866 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1867 ``value`` parameter.
1868
1869 Your type-checking function should raise :exc:`OptionValueError` if it
1870 encounters any problems. :exc:`OptionValueError` takes a single string
1871 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1872 method, which in turn prepends the program name and the string ``"error:"``
1873 and prints everything to stderr before terminating the process.
1874
1875Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl116aa622007-08-15 14:28:22 +00001876parse Python-style complex numbers on the command line. (This is even sillier
1877than it used to be, because :mod:`optparse` 1.3 added built-in support for
1878complex numbers, but never mind.)
1879
1880First, the necessary imports::
1881
1882 from copy import copy
1883 from optparse import Option, OptionValueError
1884
1885You need to define your type-checker first, since it's referred to later (in the
Georg Brandl15a515f2009-09-17 22:11:49 +00001886:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl116aa622007-08-15 14:28:22 +00001887
1888 def check_complex(option, opt, value):
1889 try:
1890 return complex(value)
1891 except ValueError:
1892 raise OptionValueError(
1893 "option %s: invalid complex value: %r" % (opt, value))
1894
1895Finally, the Option subclass::
1896
1897 class MyOption (Option):
1898 TYPES = Option.TYPES + ("complex",)
1899 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1900 TYPE_CHECKER["complex"] = check_complex
1901
1902(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandl15a515f2009-09-17 22:11:49 +00001903up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1904Option class. This being Python, nothing stops you from doing that except good
1905manners and common sense.)
Georg Brandl116aa622007-08-15 14:28:22 +00001906
1907That's it! Now you can write a script that uses the new option type just like
1908any other :mod:`optparse`\ -based script, except you have to instruct your
1909OptionParser to use MyOption instead of Option::
1910
1911 parser = OptionParser(option_class=MyOption)
1912 parser.add_option("-c", type="complex")
1913
1914Alternately, you can build your own option list and pass it to OptionParser; if
1915you don't use :meth:`add_option` in the above way, you don't need to tell
1916OptionParser which option class to use::
1917
1918 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1919 parser = OptionParser(option_list=option_list)
1920
1921
1922.. _optparse-adding-new-actions:
1923
1924Adding new actions
1925^^^^^^^^^^^^^^^^^^
1926
1927Adding new actions is a bit trickier, because you have to understand that
1928:mod:`optparse` has a couple of classifications for actions:
1929
1930"store" actions
1931 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandl15a515f2009-09-17 22:11:49 +00001932 current OptionValues instance; these options require a :attr:`~Option.dest`
1933 attribute to be supplied to the Option constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001934
1935"typed" actions
Georg Brandl15a515f2009-09-17 22:11:49 +00001936 actions that take a value from the command line and expect it to be of a
1937 certain type; or rather, a string that can be converted to a certain type.
1938 These options require a :attr:`~Option.type` attribute to the Option
1939 constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001940
Georg Brandl15a515f2009-09-17 22:11:49 +00001941These are overlapping sets: some default "store" actions are ``"store"``,
1942``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1943actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001944
1945When you add an action, you need to categorize it by listing it in at least one
1946of the following class attributes of Option (all are lists of strings):
1947
Georg Brandl15a515f2009-09-17 22:11:49 +00001948.. attribute:: Option.ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001949
Georg Brandl15a515f2009-09-17 22:11:49 +00001950 All actions must be listed in ACTIONS.
Georg Brandl116aa622007-08-15 14:28:22 +00001951
Georg Brandl15a515f2009-09-17 22:11:49 +00001952.. attribute:: Option.STORE_ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001953
Georg Brandl15a515f2009-09-17 22:11:49 +00001954 "store" actions are additionally listed here.
1955
1956.. attribute:: Option.TYPED_ACTIONS
1957
1958 "typed" actions are additionally listed here.
1959
1960.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1961
1962 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl116aa622007-08-15 14:28:22 +00001963 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001964 assigns the default type, ``"string"``, to options with no explicit type
1965 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001966
1967In order to actually implement your new action, you must override Option's
1968:meth:`take_action` method and add a case that recognizes your action.
1969
Georg Brandl15a515f2009-09-17 22:11:49 +00001970For example, let's add an ``"extend"`` action. This is similar to the standard
1971``"append"`` action, but instead of taking a single value from the command-line
1972and appending it to an existing list, ``"extend"`` will take multiple values in
1973a single comma-delimited string, and extend an existing list with them. That
Éric Araujo713d3032010-11-18 16:38:46 +00001974is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
Georg Brandl15a515f2009-09-17 22:11:49 +00001975line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001976
1977 --names=foo,bar --names blah --names ding,dong
1978
1979would result in a list ::
1980
1981 ["foo", "bar", "blah", "ding", "dong"]
1982
1983Again we define a subclass of Option::
1984
Ezio Melotti383ae952010-01-03 09:06:02 +00001985 class MyOption(Option):
Georg Brandl116aa622007-08-15 14:28:22 +00001986
1987 ACTIONS = Option.ACTIONS + ("extend",)
1988 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1989 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1990 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1991
1992 def take_action(self, action, dest, opt, value, values, parser):
1993 if action == "extend":
1994 lvalue = value.split(",")
1995 values.ensure_value(dest, []).extend(lvalue)
1996 else:
1997 Option.take_action(
1998 self, action, dest, opt, value, values, parser)
1999
2000Features of note:
2001
Georg Brandl15a515f2009-09-17 22:11:49 +00002002* ``"extend"`` both expects a value on the command-line and stores that value
2003 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
2004 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00002005
Georg Brandl15a515f2009-09-17 22:11:49 +00002006* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
2007 ``"extend"`` actions, we put the ``"extend"`` action in
2008 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl116aa622007-08-15 14:28:22 +00002009
2010* :meth:`MyOption.take_action` implements just this one new action, and passes
2011 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00002012 actions.
Georg Brandl116aa622007-08-15 14:28:22 +00002013
Georg Brandl15a515f2009-09-17 22:11:49 +00002014* ``values`` is an instance of the optparse_parser.Values class, which provides
2015 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
2016 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00002017
2018 values.ensure_value(attr, value)
2019
2020 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandl15a515f2009-09-17 22:11:49 +00002021 ensure_value() first sets it to ``value``, and then returns 'value. This is
2022 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
2023 of which accumulate data in a variable and expect that variable to be of a
2024 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl116aa622007-08-15 14:28:22 +00002025 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandl15a515f2009-09-17 22:11:49 +00002026 about setting a default value for the option destinations in question; they
2027 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl116aa622007-08-15 14:28:22 +00002028 getting it right when it's needed.