blob: 2a7d51325c4c45163198745bae290581a0451cbc [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:
7
8.. deprecated:: 2.7
9 The :mod:`optparse` module is deprecated and will not be developed further;
10 development will continue with the :mod:`argparse` module.
11
Georg Brandl116aa622007-08-15 14:28:22 +000012.. moduleauthor:: Greg Ward <gward@python.net>
Georg Brandl116aa622007-08-15 14:28:22 +000013.. sectionauthor:: Greg Ward <gward@python.net>
14
15
Georg Brandl15a515f2009-09-17 22:11:49 +000016:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
17command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
18more declarative style of command-line parsing: you create an instance of
19:class:`OptionParser`, populate it with options, and parse the command
20line. :mod:`optparse` allows users to specify options in the conventional
21GNU/POSIX syntax, and additionally generates usage and help messages for you.
Georg Brandl116aa622007-08-15 14:28:22 +000022
Georg Brandl15a515f2009-09-17 22:11:49 +000023Here's an example of using :mod:`optparse` in a simple script::
Georg Brandl116aa622007-08-15 14:28:22 +000024
25 from optparse import OptionParser
26 [...]
27 parser = OptionParser()
28 parser.add_option("-f", "--file", dest="filename",
29 help="write report to FILE", metavar="FILE")
30 parser.add_option("-q", "--quiet",
31 action="store_false", dest="verbose", default=True,
32 help="don't print status messages to stdout")
33
34 (options, args) = parser.parse_args()
35
36With these few lines of code, users of your script can now do the "usual thing"
37on the command-line, for example::
38
39 <yourscript> --file=outfile -q
40
Georg Brandl15a515f2009-09-17 22:11:49 +000041As it parses the command line, :mod:`optparse` sets attributes of the
42``options`` object returned by :meth:`parse_args` based on user-supplied
43command-line values. When :meth:`parse_args` returns from parsing this command
44line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
45``False``. :mod:`optparse` supports both long and short options, allows short
Georg Brandl116aa622007-08-15 14:28:22 +000046options to be merged together, and allows options to be associated with their
47arguments in a variety of ways. Thus, the following command lines are all
48equivalent to the above example::
49
50 <yourscript> -f outfile --quiet
51 <yourscript> --quiet --file outfile
52 <yourscript> -q -foutfile
53 <yourscript> -qfoutfile
54
55Additionally, users can run one of ::
56
57 <yourscript> -h
58 <yourscript> --help
59
Ezio Melotti383ae952010-01-03 09:06:02 +000060and :mod:`optparse` will print out a brief summary of your script's options:
61
62.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +000063
Georg Brandl121ff822011-01-02 14:23:43 +000064 Usage: <yourscript> [options]
Georg Brandl116aa622007-08-15 14:28:22 +000065
Georg Brandl121ff822011-01-02 14:23:43 +000066 Options:
Georg Brandl116aa622007-08-15 14:28:22 +000067 -h, --help show this help message and exit
68 -f FILE, --file=FILE write report to FILE
69 -q, --quiet don't print status messages to stdout
70
71where the value of *yourscript* is determined at runtime (normally from
72``sys.argv[0]``).
73
Georg Brandl116aa622007-08-15 14:28:22 +000074
75.. _optparse-background:
76
77Background
78----------
79
80:mod:`optparse` was explicitly designed to encourage the creation of programs
81with straightforward, conventional command-line interfaces. To that end, it
82supports only the most common command-line syntax and semantics conventionally
83used under Unix. If you are unfamiliar with these conventions, read this
84section to acquaint yourself with them.
85
86
87.. _optparse-terminology:
88
89Terminology
90^^^^^^^^^^^
91
92argument
Georg Brandl15a515f2009-09-17 22:11:49 +000093 a string entered on the command-line, and passed by the shell to ``execl()``
94 or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
95 (``sys.argv[0]`` is the name of the program being executed). Unix shells
96 also use the term "word".
Georg Brandl116aa622007-08-15 14:28:22 +000097
98 It is occasionally desirable to substitute an argument list other than
99 ``sys.argv[1:]``, so you should read "argument" as "an element of
100 ``sys.argv[1:]``, or of some other list provided as a substitute for
101 ``sys.argv[1:]``".
102
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000103option
Georg Brandl15a515f2009-09-17 22:11:49 +0000104 an argument used to supply extra information to guide or customize the
105 execution of a program. There are many different syntaxes for options; the
106 traditional Unix syntax is a hyphen ("-") followed by a single letter,
Éric Araujo713d3032010-11-18 16:38:46 +0000107 e.g. ``-x`` or ``-F``. Also, traditional Unix syntax allows multiple
108 options to be merged into a single argument, e.g. ``-x -F`` is equivalent
109 to ``-xF``. The GNU project introduced ``--`` followed by a series of
110 hyphen-separated words, e.g. ``--file`` or ``--dry-run``. These are the
Georg Brandl15a515f2009-09-17 22:11:49 +0000111 only two option syntaxes provided by :mod:`optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113 Some other option syntaxes that the world has seen include:
114
Éric Araujo713d3032010-11-18 16:38:46 +0000115 * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
Georg Brandl116aa622007-08-15 14:28:22 +0000116 as multiple options merged into a single argument)
117
Éric Araujo713d3032010-11-18 16:38:46 +0000118 * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
Georg Brandl116aa622007-08-15 14:28:22 +0000119 equivalent to the previous syntax, but they aren't usually seen in the same
120 program)
121
122 * a plus sign followed by a single letter, or a few letters, or a word, e.g.
Éric Araujo713d3032010-11-18 16:38:46 +0000123 ``+f``, ``+rgb``
Georg Brandl116aa622007-08-15 14:28:22 +0000124
Éric Araujo713d3032010-11-18 16:38:46 +0000125 * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``,
126 ``/file``
Georg Brandl116aa622007-08-15 14:28:22 +0000127
Georg Brandl15a515f2009-09-17 22:11:49 +0000128 These option syntaxes are not supported by :mod:`optparse`, and they never
129 will be. This is deliberate: the first three are non-standard on any
130 environment, and the last only makes sense if you're exclusively targeting
131 VMS, MS-DOS, and/or Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133option argument
Georg Brandl15a515f2009-09-17 22:11:49 +0000134 an argument that follows an option, is closely associated with that option,
135 and is consumed from the argument list when that option is. With
136 :mod:`optparse`, option arguments may either be in a separate argument from
Ezio Melotti383ae952010-01-03 09:06:02 +0000137 their option:
138
139 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141 -f foo
142 --file foo
143
Ezio Melotti383ae952010-01-03 09:06:02 +0000144 or included in the same argument:
145
146 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148 -ffoo
149 --file=foo
150
Georg Brandl15a515f2009-09-17 22:11:49 +0000151 Typically, a given option either takes an argument or it doesn't. Lots of
152 people want an "optional option arguments" feature, meaning that some options
153 will take an argument if they see it, and won't if they don't. This is
Éric Araujo713d3032010-11-18 16:38:46 +0000154 somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
155 an optional argument and ``-b`` is another option entirely, how do we
156 interpret ``-ab``? Because of this ambiguity, :mod:`optparse` does not
Georg Brandl15a515f2009-09-17 22:11:49 +0000157 support this feature.
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159positional argument
160 something leftover in the argument list after options have been parsed, i.e.
Georg Brandl15a515f2009-09-17 22:11:49 +0000161 after options and their arguments have been parsed and removed from the
162 argument list.
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164required option
165 an option that must be supplied on the command-line; note that the phrase
166 "required option" is self-contradictory in English. :mod:`optparse` doesn't
Georg Brandl15a515f2009-09-17 22:11:49 +0000167 prevent you from implementing required options, but doesn't give you much
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000168 help at it either.
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170For example, consider this hypothetical command-line::
171
172 prog -v --report /tmp/report.txt foo bar
173
Éric Araujo713d3032010-11-18 16:38:46 +0000174``-v`` and ``--report`` are both options. Assuming that ``--report``
175takes one argument, ``/tmp/report.txt`` is an option argument. ``foo`` and
176``bar`` are positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178
179.. _optparse-what-options-for:
180
181What are options for?
182^^^^^^^^^^^^^^^^^^^^^
183
184Options are used to provide extra information to tune or customize the execution
185of a program. In case it wasn't clear, options are usually *optional*. A
186program should be able to run just fine with no options whatsoever. (Pick a
187random program from the Unix or GNU toolsets. Can it run without any options at
188all and still make sense? The main exceptions are ``find``, ``tar``, and
189``dd``\ ---all of which are mutant oddballs that have been rightly criticized
190for their non-standard syntax and confusing interfaces.)
191
192Lots of people want their programs to have "required options". Think about it.
193If it's required, then it's *not optional*! If there is a piece of information
194that your program absolutely requires in order to run successfully, that's what
195positional arguments are for.
196
197As an example of good command-line interface design, consider the humble ``cp``
198utility, for copying files. It doesn't make much sense to try to copy files
199without supplying a destination and at least one source. Hence, ``cp`` fails if
200you run it with no arguments. However, it has a flexible, useful syntax that
201does not require any options at all::
202
203 cp SOURCE DEST
204 cp SOURCE ... DEST-DIR
205
206You can get pretty far with just that. Most ``cp`` implementations provide a
207bunch of options to tweak exactly how the files are copied: you can preserve
208mode and modification time, avoid following symlinks, ask before clobbering
209existing files, etc. But none of this distracts from the core mission of
210``cp``, which is to copy either one file to another, or several files to another
211directory.
212
213
214.. _optparse-what-positional-arguments-for:
215
216What are positional arguments for?
217^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
218
219Positional arguments are for those pieces of information that your program
220absolutely, positively requires to run.
221
222A good user interface should have as few absolute requirements as possible. If
223your program requires 17 distinct pieces of information in order to run
224successfully, it doesn't much matter *how* you get that information from the
225user---most people will give up and walk away before they successfully run the
226program. This applies whether the user interface is a command-line, a
227configuration file, or a GUI: if you make that many demands on your users, most
228of them will simply give up.
229
230In short, try to minimize the amount of information that users are absolutely
231required to supply---use sensible defaults whenever possible. Of course, you
232also want to make your programs reasonably flexible. That's what options are
233for. Again, it doesn't matter if they are entries in a config file, widgets in
234the "Preferences" dialog of a GUI, or command-line options---the more options
235you implement, the more flexible your program is, and the more complicated its
236implementation becomes. Too much flexibility has drawbacks as well, of course;
237too many options can overwhelm users and make your code much harder to maintain.
238
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240.. _optparse-tutorial:
241
242Tutorial
243--------
244
245While :mod:`optparse` is quite flexible and powerful, it's also straightforward
246to use in most cases. This section covers the code patterns that are common to
247any :mod:`optparse`\ -based program.
248
249First, you need to import the OptionParser class; then, early in the main
250program, create an OptionParser instance::
251
252 from optparse import OptionParser
253 [...]
254 parser = OptionParser()
255
256Then you can start defining options. The basic syntax is::
257
258 parser.add_option(opt_str, ...,
259 attr=value, ...)
260
Éric Araujo713d3032010-11-18 16:38:46 +0000261Each option has one or more option strings, such as ``-f`` or ``--file``,
Georg Brandl116aa622007-08-15 14:28:22 +0000262and several option attributes that tell :mod:`optparse` what to expect and what
263to do when it encounters that option on the command line.
264
265Typically, each option will have one short option string and one long option
266string, e.g.::
267
268 parser.add_option("-f", "--file", ...)
269
270You're free to define as many short option strings and as many long option
271strings as you like (including zero), as long as there is at least one option
272string overall.
273
274The option strings passed to :meth:`add_option` are effectively labels for the
275option defined by that call. For brevity, we will frequently refer to
276*encountering an option* on the command line; in reality, :mod:`optparse`
277encounters *option strings* and looks up options from them.
278
279Once all of your options are defined, instruct :mod:`optparse` to parse your
280program's command line::
281
282 (options, args) = parser.parse_args()
283
284(If you like, you can pass a custom argument list to :meth:`parse_args`, but
285that's rarely necessary: by default it uses ``sys.argv[1:]``.)
286
287:meth:`parse_args` returns two values:
288
289* ``options``, an object containing values for all of your options---e.g. if
Éric Araujo713d3032010-11-18 16:38:46 +0000290 ``--file`` takes a single string argument, then ``options.file`` will be the
Georg Brandl116aa622007-08-15 14:28:22 +0000291 filename supplied by the user, or ``None`` if the user did not supply that
292 option
293
294* ``args``, the list of positional arguments leftover after parsing options
295
296This tutorial section only covers the four most important option attributes:
Georg Brandl15a515f2009-09-17 22:11:49 +0000297:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
298(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
299most fundamental.
Georg Brandl116aa622007-08-15 14:28:22 +0000300
301
302.. _optparse-understanding-option-actions:
303
304Understanding option actions
305^^^^^^^^^^^^^^^^^^^^^^^^^^^^
306
307Actions tell :mod:`optparse` what to do when it encounters an option on the
308command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
309adding new actions is an advanced topic covered in section
Georg Brandl15a515f2009-09-17 22:11:49 +0000310:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
311a value in some variable---for example, take a string from the command line and
312store it in an attribute of ``options``.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314If you don't specify an option action, :mod:`optparse` defaults to ``store``.
315
316
317.. _optparse-store-action:
318
319The store action
320^^^^^^^^^^^^^^^^
321
322The most common option action is ``store``, which tells :mod:`optparse` to take
323the next argument (or the remainder of the current argument), ensure that it is
324of the correct type, and store it to your chosen destination.
325
326For example::
327
328 parser.add_option("-f", "--file",
329 action="store", type="string", dest="filename")
330
331Now let's make up a fake command line and ask :mod:`optparse` to parse it::
332
333 args = ["-f", "foo.txt"]
334 (options, args) = parser.parse_args(args)
335
Éric Araujo713d3032010-11-18 16:38:46 +0000336When :mod:`optparse` sees the option string ``-f``, it consumes the next
337argument, ``foo.txt``, and stores it in ``options.filename``. So, after this
Georg Brandl116aa622007-08-15 14:28:22 +0000338call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
339
340Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
341Here's an option that expects an integer argument::
342
343 parser.add_option("-n", type="int", dest="num")
344
345Note that this option has no long option string, which is perfectly acceptable.
346Also, there's no explicit action, since the default is ``store``.
347
348Let's parse another fake command-line. This time, we'll jam the option argument
Éric Araujo713d3032010-11-18 16:38:46 +0000349right up against the option: since ``-n42`` (one argument) is equivalent to
350``-n 42`` (two arguments), the code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352 (options, args) = parser.parse_args(["-n42"])
Georg Brandl6911e3c2007-09-04 07:15:32 +0000353 print(options.num)
Georg Brandl116aa622007-08-15 14:28:22 +0000354
Éric Araujo713d3032010-11-18 16:38:46 +0000355will print ``42``.
Georg Brandl116aa622007-08-15 14:28:22 +0000356
357If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
358the fact that the default action is ``store``, that means our first example can
359be a lot shorter::
360
361 parser.add_option("-f", "--file", dest="filename")
362
363If you don't supply a destination, :mod:`optparse` figures out a sensible
364default from the option strings: if the first long option string is
Éric Araujo713d3032010-11-18 16:38:46 +0000365``--foo-bar``, then the default destination is ``foo_bar``. If there are no
Georg Brandl116aa622007-08-15 14:28:22 +0000366long option strings, :mod:`optparse` looks at the first short option string: the
Éric Araujo713d3032010-11-18 16:38:46 +0000367default destination for ``-f`` is ``f``.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
Georg Brandl5c106642007-11-29 17:41:05 +0000369:mod:`optparse` also includes the built-in ``complex`` type. Adding
Georg Brandl116aa622007-08-15 14:28:22 +0000370types is covered in section :ref:`optparse-extending-optparse`.
371
372
373.. _optparse-handling-boolean-options:
374
375Handling boolean (flag) options
376^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
377
378Flag options---set a variable to true or false when a particular option is seen
379---are quite common. :mod:`optparse` supports them with two separate actions,
380``store_true`` and ``store_false``. For example, you might have a ``verbose``
Éric Araujo713d3032010-11-18 16:38:46 +0000381flag that is turned on with ``-v`` and off with ``-q``::
Georg Brandl116aa622007-08-15 14:28:22 +0000382
383 parser.add_option("-v", action="store_true", dest="verbose")
384 parser.add_option("-q", action="store_false", dest="verbose")
385
386Here we have two different options with the same destination, which is perfectly
387OK. (It just means you have to be a bit careful when setting default values---
388see below.)
389
Éric Araujo713d3032010-11-18 16:38:46 +0000390When :mod:`optparse` encounters ``-v`` on the command line, it sets
391``options.verbose`` to ``True``; when it encounters ``-q``,
Georg Brandl116aa622007-08-15 14:28:22 +0000392``options.verbose`` is set to ``False``.
393
394
395.. _optparse-other-actions:
396
397Other actions
398^^^^^^^^^^^^^
399
400Some other actions supported by :mod:`optparse` are:
401
Georg Brandl15a515f2009-09-17 22:11:49 +0000402``"store_const"``
Georg Brandl116aa622007-08-15 14:28:22 +0000403 store a constant value
404
Georg Brandl15a515f2009-09-17 22:11:49 +0000405``"append"``
Georg Brandl116aa622007-08-15 14:28:22 +0000406 append this option's argument to a list
407
Georg Brandl15a515f2009-09-17 22:11:49 +0000408``"count"``
Georg Brandl116aa622007-08-15 14:28:22 +0000409 increment a counter by one
410
Georg Brandl15a515f2009-09-17 22:11:49 +0000411``"callback"``
Georg Brandl116aa622007-08-15 14:28:22 +0000412 call a specified function
413
414These are covered in section :ref:`optparse-reference-guide`, Reference Guide
415and section :ref:`optparse-option-callbacks`.
416
417
418.. _optparse-default-values:
419
420Default values
421^^^^^^^^^^^^^^
422
423All of the above examples involve setting some variable (the "destination") when
424certain command-line options are seen. What happens if those options are never
425seen? Since we didn't supply any defaults, they are all set to ``None``. This
426is usually fine, but sometimes you want more control. :mod:`optparse` lets you
427supply a default value for each destination, which is assigned before the
428command line is parsed.
429
430First, consider the verbose/quiet example. If we want :mod:`optparse` to set
Éric Araujo713d3032010-11-18 16:38:46 +0000431``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
Georg Brandl116aa622007-08-15 14:28:22 +0000432
433 parser.add_option("-v", action="store_true", dest="verbose", default=True)
434 parser.add_option("-q", action="store_false", dest="verbose")
435
436Since default values apply to the *destination* rather than to any particular
437option, and these two options happen to have the same destination, this is
438exactly equivalent::
439
440 parser.add_option("-v", action="store_true", dest="verbose")
441 parser.add_option("-q", action="store_false", dest="verbose", default=True)
442
443Consider this::
444
445 parser.add_option("-v", action="store_true", dest="verbose", default=False)
446 parser.add_option("-q", action="store_false", dest="verbose", default=True)
447
448Again, the default value for ``verbose`` will be ``True``: the last default
449value supplied for any particular destination is the one that counts.
450
451A clearer way to specify default values is the :meth:`set_defaults` method of
452OptionParser, which you can call at any time before calling :meth:`parse_args`::
453
454 parser.set_defaults(verbose=True)
455 parser.add_option(...)
456 (options, args) = parser.parse_args()
457
458As before, the last value specified for a given option destination is the one
459that counts. For clarity, try to use one method or the other of setting default
460values, not both.
461
462
463.. _optparse-generating-help:
464
465Generating help
466^^^^^^^^^^^^^^^
467
468:mod:`optparse`'s ability to generate help and usage text automatically is
469useful for creating user-friendly command-line interfaces. All you have to do
Georg Brandl15a515f2009-09-17 22:11:49 +0000470is supply a :attr:`~Option.help` value for each option, and optionally a short
471usage message for your whole program. Here's an OptionParser populated with
Georg Brandl116aa622007-08-15 14:28:22 +0000472user-friendly (documented) options::
473
474 usage = "usage: %prog [options] arg1 arg2"
475 parser = OptionParser(usage=usage)
476 parser.add_option("-v", "--verbose",
477 action="store_true", dest="verbose", default=True,
478 help="make lots of noise [default]")
479 parser.add_option("-q", "--quiet",
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000480 action="store_false", dest="verbose",
Georg Brandl116aa622007-08-15 14:28:22 +0000481 help="be vewwy quiet (I'm hunting wabbits)")
482 parser.add_option("-f", "--filename",
Georg Brandlee8783d2009-09-16 16:00:31 +0000483 metavar="FILE", help="write output to FILE")
Georg Brandl116aa622007-08-15 14:28:22 +0000484 parser.add_option("-m", "--mode",
485 default="intermediate",
486 help="interaction mode: novice, intermediate, "
487 "or expert [default: %default]")
488
Éric Araujo713d3032010-11-18 16:38:46 +0000489If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
Georg Brandl116aa622007-08-15 14:28:22 +0000490command-line, or if you just call :meth:`parser.print_help`, it prints the
Ezio Melotti383ae952010-01-03 09:06:02 +0000491following to standard output:
492
493.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000494
Georg Brandl121ff822011-01-02 14:23:43 +0000495 Usage: <yourscript> [options] arg1 arg2
Georg Brandl116aa622007-08-15 14:28:22 +0000496
Georg Brandl121ff822011-01-02 14:23:43 +0000497 Options:
Georg Brandl116aa622007-08-15 14:28:22 +0000498 -h, --help show this help message and exit
499 -v, --verbose make lots of noise [default]
500 -q, --quiet be vewwy quiet (I'm hunting wabbits)
501 -f FILE, --filename=FILE
502 write output to FILE
503 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
504 expert [default: intermediate]
505
506(If the help output is triggered by a help option, :mod:`optparse` exits after
507printing the help text.)
508
509There's a lot going on here to help :mod:`optparse` generate the best possible
510help message:
511
512* the script defines its own usage message::
513
514 usage = "usage: %prog [options] arg1 arg2"
515
Éric Araujo713d3032010-11-18 16:38:46 +0000516 :mod:`optparse` expands ``%prog`` in the usage string to the name of the
Georg Brandl15a515f2009-09-17 22:11:49 +0000517 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
518 is then printed before the detailed option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000519
520 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandl121ff822011-01-02 14:23:43 +0000521 default: ``"Usage: %prog [options]"``, which is fine if your script doesn't
Georg Brandl15a515f2009-09-17 22:11:49 +0000522 take any positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524* every option defines a help string, and doesn't worry about line-wrapping---
525 :mod:`optparse` takes care of wrapping lines and making the help output look
526 good.
527
528* options that take a value indicate this fact in their automatically-generated
529 help message, e.g. for the "mode" option::
530
531 -m MODE, --mode=MODE
532
533 Here, "MODE" is called the meta-variable: it stands for the argument that the
Éric Araujo713d3032010-11-18 16:38:46 +0000534 user is expected to supply to ``-m``/``--mode``. By default,
Georg Brandl116aa622007-08-15 14:28:22 +0000535 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandl15a515f2009-09-17 22:11:49 +0000536 that for the meta-variable. Sometimes, that's not what you want---for
Éric Araujo713d3032010-11-18 16:38:46 +0000537 example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
Georg Brandl15a515f2009-09-17 22:11:49 +0000538 resulting in this automatically-generated option description::
Georg Brandl116aa622007-08-15 14:28:22 +0000539
540 -f FILE, --filename=FILE
541
Georg Brandl15a515f2009-09-17 22:11:49 +0000542 This is important for more than just saving space, though: the manually
Éric Araujo713d3032010-11-18 16:38:46 +0000543 written help text uses the meta-variable ``FILE`` to clue the user in that
544 there's a connection between the semi-formal syntax ``-f FILE`` and the informal
Georg Brandl15a515f2009-09-17 22:11:49 +0000545 semantic description "write output to FILE". This is a simple but effective
546 way to make your help text a lot clearer and more useful for end users.
Georg Brandl116aa622007-08-15 14:28:22 +0000547
548* options that have a default value can include ``%default`` in the help
549 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
550 default value. If an option has no default value (or the default value is
551 ``None``), ``%default`` expands to ``none``.
552
Georg Brandl121ff822011-01-02 14:23:43 +0000553Grouping Options
554++++++++++++++++
555
Georg Brandl15a515f2009-09-17 22:11:49 +0000556When dealing with many options, it is convenient to group these options for
557better help output. An :class:`OptionParser` can contain several option groups,
558each of which can contain several options.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000559
Georg Brandl121ff822011-01-02 14:23:43 +0000560An option group is obtained using the class :class:`OptionGroup`:
561
562.. class:: OptionGroup(parser, title, description=None)
563
564 where
565
566 * parser is the :class:`OptionParser` instance the group will be insterted in
567 to
568 * title is the group title
569 * description, optional, is a long description of the group
570
571:class:`OptionGroup` inherits from :class:`OptionContainer` (like
572:class:`OptionParser`) and so the :meth:`add_option` method can be used to add
573an option to the group.
574
575Once all the options are declared, using the :class:`OptionParser` method
576:meth:`add_option_group` the group is added to the previously defined parser.
577
578Continuing with the parser defined in the previous section, adding an
579:class:`OptionGroup` to a parser is easy::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000580
581 group = OptionGroup(parser, "Dangerous Options",
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000582 "Caution: use these options at your own risk. "
583 "It is believed that some of them bite.")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000584 group.add_option("-g", action="store_true", help="Group option.")
585 parser.add_option_group(group)
586
Ezio Melotti383ae952010-01-03 09:06:02 +0000587This would result in the following help output:
588
589.. code-block:: text
Christian Heimesfdab48e2008-01-20 09:06:41 +0000590
Georg Brandl121ff822011-01-02 14:23:43 +0000591 Usage: <yourscript> [options] arg1 arg2
Christian Heimesfdab48e2008-01-20 09:06:41 +0000592
Georg Brandl121ff822011-01-02 14:23:43 +0000593 Options:
594 -h, --help show this help message and exit
595 -v, --verbose make lots of noise [default]
596 -q, --quiet be vewwy quiet (I'm hunting wabbits)
597 -f FILE, --filename=FILE
598 write output to FILE
599 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
600 expert [default: intermediate]
Christian Heimesfdab48e2008-01-20 09:06:41 +0000601
Georg Brandl121ff822011-01-02 14:23:43 +0000602 Dangerous Options:
603 Caution: use these options at your own risk. It is believed that some
604 of them bite.
605
606 -g Group option.
607
608A bit more complete example might invole using more than one group: still
609extendind the previous example::
610
611 group = OptionGroup(parser, "Dangerous Options",
612 "Caution: use these options at your own risk. "
613 "It is believed that some of them bite.")
614 group.add_option("-g", action="store_true", help="Group option.")
615 parser.add_option_group(group)
616
617 group = OptionGroup(parser, "Debug Options")
618 group.add_option("-d", "--debug", action="store_true",
619 help="Print debug information")
620 group.add_option("-s", "--sql", action="store_true",
621 help="Print all SQL statements executed")
622 group.add_option("-e", action="store_true", help="Print every action done")
623 parser.add_option_group(group)
624
625that results in the following output:
626
627.. code-block:: text
628
629 Usage: <yourscript> [options] arg1 arg2
630
631 Options:
632 -h, --help show this help message and exit
633 -v, --verbose make lots of noise [default]
634 -q, --quiet be vewwy quiet (I'm hunting wabbits)
635 -f FILE, --filename=FILE
636 write output to FILE
637 -m MODE, --mode=MODE interaction mode: novice, intermediate, or expert
638 [default: intermediate]
639
640 Dangerous Options:
641 Caution: use these options at your own risk. It is believed that some
642 of them bite.
643
644 -g Group option.
645
646 Debug Options:
647 -d, --debug Print debug information
648 -s, --sql Print all SQL statements executed
649 -e Print every action done
650
651Another interesting method, in particular when working programmatically with
652option groups is:
653
654.. method:: OptionParser.get_option_group(opt_str)
655
656 Return, if defined, the :class:`OptionGroup` that has the title or the long
657 description equals to *opt_str*
Georg Brandl116aa622007-08-15 14:28:22 +0000658
659.. _optparse-printing-version-string:
660
661Printing a version string
662^^^^^^^^^^^^^^^^^^^^^^^^^
663
664Similar to the brief usage string, :mod:`optparse` can also print a version
665string for your program. You have to supply the string as the ``version``
666argument to OptionParser::
667
668 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
669
Éric Araujo713d3032010-11-18 16:38:46 +0000670``%prog`` is expanded just like it is in ``usage``. Apart from that,
Georg Brandl116aa622007-08-15 14:28:22 +0000671``version`` can contain anything you like. When you supply it, :mod:`optparse`
Éric Araujo713d3032010-11-18 16:38:46 +0000672automatically adds a ``--version`` option to your parser. If it encounters
Georg Brandl116aa622007-08-15 14:28:22 +0000673this option on the command line, it expands your ``version`` string (by
Éric Araujo713d3032010-11-18 16:38:46 +0000674replacing ``%prog``), prints it to stdout, and exits.
Georg Brandl116aa622007-08-15 14:28:22 +0000675
676For example, if your script is called ``/usr/bin/foo``::
677
678 $ /usr/bin/foo --version
679 foo 1.0
680
Ezio Melotti1ce43192010-01-04 21:53:17 +0000681The following two methods can be used to print and get the ``version`` string:
682
683.. method:: OptionParser.print_version(file=None)
684
685 Print the version message for the current program (``self.version``) to
686 *file* (default stdout). As with :meth:`print_usage`, any occurrence
Éric Araujo713d3032010-11-18 16:38:46 +0000687 of ``%prog`` in ``self.version`` is replaced with the name of the current
Ezio Melotti1ce43192010-01-04 21:53:17 +0000688 program. Does nothing if ``self.version`` is empty or undefined.
689
690.. method:: OptionParser.get_version()
691
692 Same as :meth:`print_version` but returns the version string instead of
693 printing it.
694
Georg Brandl116aa622007-08-15 14:28:22 +0000695
696.. _optparse-how-optparse-handles-errors:
697
698How :mod:`optparse` handles errors
699^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
700
701There are two broad classes of errors that :mod:`optparse` has to worry about:
702programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandl15a515f2009-09-17 22:11:49 +0000703calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
704option attributes, missing option attributes, etc. These are dealt with in the
705usual way: raise an exception (either :exc:`optparse.OptionError` or
706:exc:`TypeError`) and let the program crash.
Georg Brandl116aa622007-08-15 14:28:22 +0000707
708Handling user errors is much more important, since they are guaranteed to happen
709no matter how stable your code is. :mod:`optparse` can automatically detect
Éric Araujo713d3032010-11-18 16:38:46 +0000710some user errors, such as bad option arguments (passing ``-n 4x`` where
711``-n`` takes an integer argument), missing arguments (``-n`` at the end
712of the command line, where ``-n`` takes an argument of any type). Also,
Georg Brandl15a515f2009-09-17 22:11:49 +0000713you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl116aa622007-08-15 14:28:22 +0000714condition::
715
716 (options, args) = parser.parse_args()
717 [...]
718 if options.a and options.b:
719 parser.error("options -a and -b are mutually exclusive")
720
721In either case, :mod:`optparse` handles the error the same way: it prints the
722program's usage message and an error message to standard error and exits with
723error status 2.
724
Éric Araujo713d3032010-11-18 16:38:46 +0000725Consider the first example above, where the user passes ``4x`` to an option
Georg Brandl116aa622007-08-15 14:28:22 +0000726that takes an integer::
727
728 $ /usr/bin/foo -n 4x
Georg Brandl121ff822011-01-02 14:23:43 +0000729 Usage: foo [options]
Georg Brandl116aa622007-08-15 14:28:22 +0000730
731 foo: error: option -n: invalid integer value: '4x'
732
733Or, where the user fails to pass a value at all::
734
735 $ /usr/bin/foo -n
Georg Brandl121ff822011-01-02 14:23:43 +0000736 Usage: foo [options]
Georg Brandl116aa622007-08-15 14:28:22 +0000737
738 foo: error: -n option requires an argument
739
740:mod:`optparse`\ -generated error messages take care always to mention the
741option involved in the error; be sure to do the same when calling
Georg Brandl15a515f2009-09-17 22:11:49 +0000742:func:`OptionParser.error` from your application code.
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000744If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000745you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
746and/or :meth:`~OptionParser.error` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000747
748
749.. _optparse-putting-it-all-together:
750
751Putting it all together
752^^^^^^^^^^^^^^^^^^^^^^^
753
754Here's what :mod:`optparse`\ -based scripts usually look like::
755
756 from optparse import OptionParser
757 [...]
758 def main():
759 usage = "usage: %prog [options] arg"
760 parser = OptionParser(usage)
761 parser.add_option("-f", "--file", dest="filename",
762 help="read data from FILENAME")
763 parser.add_option("-v", "--verbose",
764 action="store_true", dest="verbose")
765 parser.add_option("-q", "--quiet",
766 action="store_false", dest="verbose")
767 [...]
768 (options, args) = parser.parse_args()
769 if len(args) != 1:
770 parser.error("incorrect number of arguments")
771 if options.verbose:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000772 print("reading %s..." % options.filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000773 [...]
774
775 if __name__ == "__main__":
776 main()
777
Georg Brandl116aa622007-08-15 14:28:22 +0000778
779.. _optparse-reference-guide:
780
781Reference Guide
782---------------
783
784
785.. _optparse-creating-parser:
786
787Creating the parser
788^^^^^^^^^^^^^^^^^^^
789
Georg Brandl15a515f2009-09-17 22:11:49 +0000790The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000791
Georg Brandl15a515f2009-09-17 22:11:49 +0000792.. class:: OptionParser(...)
Georg Brandl116aa622007-08-15 14:28:22 +0000793
Georg Brandl15a515f2009-09-17 22:11:49 +0000794 The OptionParser constructor has no required arguments, but a number of
795 optional keyword arguments. You should always pass them as keyword
796 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl116aa622007-08-15 14:28:22 +0000797
798 ``usage`` (default: ``"%prog [options]"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000799 The usage summary to print when your program is run incorrectly or with a
800 help option. When :mod:`optparse` prints the usage string, it expands
801 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
802 passed that keyword argument). To suppress a usage message, pass the
803 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl116aa622007-08-15 14:28:22 +0000804
805 ``option_list`` (default: ``[]``)
806 A list of Option objects to populate the parser with. The options in
Georg Brandl15a515f2009-09-17 22:11:49 +0000807 ``option_list`` are added after any options in ``standard_option_list`` (a
808 class attribute that may be set by OptionParser subclasses), but before
809 any version or help options. Deprecated; use :meth:`add_option` after
810 creating the parser instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000811
812 ``option_class`` (default: optparse.Option)
813 Class to use when adding options to the parser in :meth:`add_option`.
814
815 ``version`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000816 A version string to print when the user supplies a version option. If you
817 supply a true value for ``version``, :mod:`optparse` automatically adds a
Éric Araujo713d3032010-11-18 16:38:46 +0000818 version option with the single option string ``--version``. The
819 substring ``%prog`` is expanded the same as for ``usage``.
Georg Brandl116aa622007-08-15 14:28:22 +0000820
821 ``conflict_handler`` (default: ``"error"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000822 Specifies what to do when options with conflicting option strings are
823 added to the parser; see section
824 :ref:`optparse-conflicts-between-options`.
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826 ``description`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000827 A paragraph of text giving a brief overview of your program.
828 :mod:`optparse` reformats this paragraph to fit the current terminal width
829 and prints it when the user requests help (after ``usage``, but before the
830 list of options).
Georg Brandl116aa622007-08-15 14:28:22 +0000831
Georg Brandl15a515f2009-09-17 22:11:49 +0000832 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
833 An instance of optparse.HelpFormatter that will be used for printing help
834 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl116aa622007-08-15 14:28:22 +0000835 IndentedHelpFormatter and TitledHelpFormatter.
836
837 ``add_help_option`` (default: ``True``)
Éric Araujo713d3032010-11-18 16:38:46 +0000838 If true, :mod:`optparse` will add a help option (with option strings ``-h``
839 and ``--help``) to the parser.
Georg Brandl116aa622007-08-15 14:28:22 +0000840
841 ``prog``
Éric Araujo713d3032010-11-18 16:38:46 +0000842 The string to use when expanding ``%prog`` in ``usage`` and ``version``
Georg Brandl116aa622007-08-15 14:28:22 +0000843 instead of ``os.path.basename(sys.argv[0])``.
844
Senthil Kumaran5b58f5e2010-03-23 11:00:53 +0000845 ``epilog`` (default: ``None``)
846 A paragraph of help text to print after the option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000847
848.. _optparse-populating-parser:
849
850Populating the parser
851^^^^^^^^^^^^^^^^^^^^^
852
853There are several ways to populate the parser with options. The preferred way
Georg Brandl15a515f2009-09-17 22:11:49 +0000854is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl116aa622007-08-15 14:28:22 +0000855:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
856
857* pass it an Option instance (as returned by :func:`make_option`)
858
859* pass it any combination of positional and keyword arguments that are
Georg Brandl15a515f2009-09-17 22:11:49 +0000860 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
861 will create the Option instance for you
Georg Brandl116aa622007-08-15 14:28:22 +0000862
863The other alternative is to pass a list of pre-constructed Option instances to
864the OptionParser constructor, as in::
865
866 option_list = [
867 make_option("-f", "--filename",
868 action="store", type="string", dest="filename"),
869 make_option("-q", "--quiet",
870 action="store_false", dest="verbose"),
871 ]
872 parser = OptionParser(option_list=option_list)
873
874(:func:`make_option` is a factory function for creating Option instances;
875currently it is an alias for the Option constructor. A future version of
876:mod:`optparse` may split Option into several classes, and :func:`make_option`
877will pick the right class to instantiate. Do not instantiate Option directly.)
878
879
880.. _optparse-defining-options:
881
882Defining options
883^^^^^^^^^^^^^^^^
884
885Each Option instance represents a set of synonymous command-line option strings,
Éric Araujo713d3032010-11-18 16:38:46 +0000886e.g. ``-f`` and ``--file``. You can specify any number of short or
Georg Brandl116aa622007-08-15 14:28:22 +0000887long option strings, but you must specify at least one overall option string.
888
Georg Brandl15a515f2009-09-17 22:11:49 +0000889The canonical way to create an :class:`Option` instance is with the
890:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl116aa622007-08-15 14:28:22 +0000891
Georg Brandl15a515f2009-09-17 22:11:49 +0000892.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000893
Georg Brandl15a515f2009-09-17 22:11:49 +0000894 To define an option with only a short option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000895
Georg Brandl15a515f2009-09-17 22:11:49 +0000896 parser.add_option("-f", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000897
Georg Brandl15a515f2009-09-17 22:11:49 +0000898 And to define an option with only a long option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000899
Georg Brandl15a515f2009-09-17 22:11:49 +0000900 parser.add_option("--foo", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000901
Georg Brandl15a515f2009-09-17 22:11:49 +0000902 The keyword arguments define attributes of the new Option object. The most
903 important option attribute is :attr:`~Option.action`, and it largely
904 determines which other attributes are relevant or required. If you pass
905 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
906 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl116aa622007-08-15 14:28:22 +0000907
Georg Brandl15a515f2009-09-17 22:11:49 +0000908 An option's *action* determines what :mod:`optparse` does when it encounters
909 this option on the command-line. The standard option actions hard-coded into
910 :mod:`optparse` are:
Georg Brandl116aa622007-08-15 14:28:22 +0000911
Georg Brandl15a515f2009-09-17 22:11:49 +0000912 ``"store"``
913 store this option's argument (default)
Georg Brandl116aa622007-08-15 14:28:22 +0000914
Georg Brandl15a515f2009-09-17 22:11:49 +0000915 ``"store_const"``
916 store a constant value
Georg Brandl116aa622007-08-15 14:28:22 +0000917
Georg Brandl15a515f2009-09-17 22:11:49 +0000918 ``"store_true"``
919 store a true value
Georg Brandl116aa622007-08-15 14:28:22 +0000920
Georg Brandl15a515f2009-09-17 22:11:49 +0000921 ``"store_false"``
922 store a false value
Georg Brandl116aa622007-08-15 14:28:22 +0000923
Georg Brandl15a515f2009-09-17 22:11:49 +0000924 ``"append"``
925 append this option's argument to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Georg Brandl15a515f2009-09-17 22:11:49 +0000927 ``"append_const"``
928 append a constant value to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000929
Georg Brandl15a515f2009-09-17 22:11:49 +0000930 ``"count"``
931 increment a counter by one
Georg Brandl116aa622007-08-15 14:28:22 +0000932
Georg Brandl15a515f2009-09-17 22:11:49 +0000933 ``"callback"``
934 call a specified function
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Georg Brandl15a515f2009-09-17 22:11:49 +0000936 ``"help"``
937 print a usage message including all options and the documentation for them
Georg Brandl116aa622007-08-15 14:28:22 +0000938
Georg Brandl15a515f2009-09-17 22:11:49 +0000939 (If you don't supply an action, the default is ``"store"``. For this action,
940 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
941 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000942
943As you can see, most actions involve storing or updating a value somewhere.
944:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandl15a515f2009-09-17 22:11:49 +0000945``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl116aa622007-08-15 14:28:22 +0000946arguments (and various other values) are stored as attributes of this object,
Georg Brandl15a515f2009-09-17 22:11:49 +0000947according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000948
Georg Brandl15a515f2009-09-17 22:11:49 +0000949For example, when you call ::
Georg Brandl116aa622007-08-15 14:28:22 +0000950
951 parser.parse_args()
952
953one of the first things :mod:`optparse` does is create the ``options`` object::
954
955 options = Values()
956
Georg Brandl15a515f2009-09-17 22:11:49 +0000957If one of the options in this parser is defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +0000958
959 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
960
961and the command-line being parsed includes any of the following::
962
963 -ffoo
964 -f foo
965 --file=foo
966 --file foo
967
Georg Brandl15a515f2009-09-17 22:11:49 +0000968then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl116aa622007-08-15 14:28:22 +0000969
970 options.filename = "foo"
971
Georg Brandl15a515f2009-09-17 22:11:49 +0000972The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
973as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
974one that makes sense for *all* options.
975
976
977.. _optparse-option-attributes:
978
979Option attributes
980^^^^^^^^^^^^^^^^^
981
982The following option attributes may be passed as keyword arguments to
983:meth:`OptionParser.add_option`. If you pass an option attribute that is not
984relevant to a particular option, or fail to pass a required option attribute,
985:mod:`optparse` raises :exc:`OptionError`.
986
987.. attribute:: Option.action
988
989 (default: ``"store"``)
990
991 Determines :mod:`optparse`'s behaviour when this option is seen on the
992 command line; the available options are documented :ref:`here
993 <optparse-standard-option-actions>`.
994
995.. attribute:: Option.type
996
997 (default: ``"string"``)
998
999 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
1000 the available option types are documented :ref:`here
1001 <optparse-standard-option-types>`.
1002
1003.. attribute:: Option.dest
1004
1005 (default: derived from option strings)
1006
1007 If the option's action implies writing or modifying a value somewhere, this
1008 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
1009 attribute of the ``options`` object that :mod:`optparse` builds as it parses
1010 the command line.
1011
1012.. attribute:: Option.default
1013
1014 The value to use for this option's destination if the option is not seen on
1015 the command line. See also :meth:`OptionParser.set_defaults`.
1016
1017.. attribute:: Option.nargs
1018
1019 (default: 1)
1020
1021 How many arguments of type :attr:`~Option.type` should be consumed when this
1022 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
1023 :attr:`~Option.dest`.
1024
1025.. attribute:: Option.const
1026
1027 For actions that store a constant value, the constant value to store.
1028
1029.. attribute:: Option.choices
1030
1031 For options of type ``"choice"``, the list of strings the user may choose
1032 from.
1033
1034.. attribute:: Option.callback
1035
1036 For options with action ``"callback"``, the callable to call when this option
1037 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1038 arguments passed to the callable.
1039
1040.. attribute:: Option.callback_args
1041 Option.callback_kwargs
1042
1043 Additional positional and keyword arguments to pass to ``callback`` after the
1044 four standard callback arguments.
1045
1046.. attribute:: Option.help
1047
1048 Help text to print for this option when listing all available options after
Éric Araujo713d3032010-11-18 16:38:46 +00001049 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
Georg Brandl15a515f2009-09-17 22:11:49 +00001050 no help text is supplied, the option will be listed without help text. To
1051 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
1052
1053.. attribute:: Option.metavar
1054
1055 (default: derived from option strings)
1056
1057 Stand-in for the option argument(s) to use when printing help text. See
1058 section :ref:`optparse-tutorial` for an example.
Georg Brandl116aa622007-08-15 14:28:22 +00001059
1060
1061.. _optparse-standard-option-actions:
1062
1063Standard option actions
1064^^^^^^^^^^^^^^^^^^^^^^^
1065
1066The various option actions all have slightly different requirements and effects.
1067Most actions have several relevant option attributes which you may specify to
1068guide :mod:`optparse`'s behaviour; a few have required attributes, which you
1069must specify for any option using that action.
1070
Georg Brandl15a515f2009-09-17 22:11:49 +00001071* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1072 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001073
1074 The option must be followed by an argument, which is converted to a value
Georg Brandl15a515f2009-09-17 22:11:49 +00001075 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1076 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1077 command line; all will be converted according to :attr:`~Option.type` and
1078 stored to :attr:`~Option.dest` as a tuple. See the
1079 :ref:`optparse-standard-option-types` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001080
Georg Brandl15a515f2009-09-17 22:11:49 +00001081 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1082 defaults to ``"choice"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001083
Georg Brandl15a515f2009-09-17 22:11:49 +00001084 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001085
Georg Brandl15a515f2009-09-17 22:11:49 +00001086 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
Éric Araujo713d3032010-11-18 16:38:46 +00001087 from the first long option string (e.g., ``--foo-bar`` implies
Georg Brandl15a515f2009-09-17 22:11:49 +00001088 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
Éric Araujo713d3032010-11-18 16:38:46 +00001089 destination from the first short option string (e.g., ``-f`` implies ``f``).
Georg Brandl116aa622007-08-15 14:28:22 +00001090
1091 Example::
1092
1093 parser.add_option("-f")
1094 parser.add_option("-p", type="float", nargs=3, dest="point")
1095
Georg Brandl15a515f2009-09-17 22:11:49 +00001096 As it parses the command line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001097
1098 -f foo.txt -p 1 -3.5 4 -fbar.txt
1099
Georg Brandl15a515f2009-09-17 22:11:49 +00001100 :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +00001101
1102 options.f = "foo.txt"
1103 options.point = (1.0, -3.5, 4.0)
1104 options.f = "bar.txt"
1105
Georg Brandl15a515f2009-09-17 22:11:49 +00001106* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1107 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001108
Georg Brandl15a515f2009-09-17 22:11:49 +00001109 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001110
1111 Example::
1112
1113 parser.add_option("-q", "--quiet",
1114 action="store_const", const=0, dest="verbose")
1115 parser.add_option("-v", "--verbose",
1116 action="store_const", const=1, dest="verbose")
1117 parser.add_option("--noisy",
1118 action="store_const", const=2, dest="verbose")
1119
Éric Araujo713d3032010-11-18 16:38:46 +00001120 If ``--noisy`` is seen, :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +00001121
1122 options.verbose = 2
1123
Georg Brandl15a515f2009-09-17 22:11:49 +00001124* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001125
Georg Brandl15a515f2009-09-17 22:11:49 +00001126 A special case of ``"store_const"`` that stores a true value to
1127 :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001128
Georg Brandl15a515f2009-09-17 22:11:49 +00001129* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001130
Georg Brandl15a515f2009-09-17 22:11:49 +00001131 Like ``"store_true"``, but stores a false value.
Georg Brandl116aa622007-08-15 14:28:22 +00001132
1133 Example::
1134
1135 parser.add_option("--clobber", action="store_true", dest="clobber")
1136 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1137
Georg Brandl15a515f2009-09-17 22:11:49 +00001138* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1139 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001140
1141 The option must be followed by an argument, which is appended to the list in
Georg Brandl15a515f2009-09-17 22:11:49 +00001142 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1143 supplied, an empty list is automatically created when :mod:`optparse` first
1144 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1145 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1146 is appended to :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001147
Georg Brandl15a515f2009-09-17 22:11:49 +00001148 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1149 for the ``"store"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001150
1151 Example::
1152
1153 parser.add_option("-t", "--tracks", action="append", type="int")
1154
Éric Araujo713d3032010-11-18 16:38:46 +00001155 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
Georg Brandl116aa622007-08-15 14:28:22 +00001156 of::
1157
1158 options.tracks = []
1159 options.tracks.append(int("3"))
1160
Éric Araujo713d3032010-11-18 16:38:46 +00001161 If, a little later on, ``--tracks=4`` is seen, it does::
Georg Brandl116aa622007-08-15 14:28:22 +00001162
1163 options.tracks.append(int("4"))
1164
Georg Brandl15a515f2009-09-17 22:11:49 +00001165* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1166 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001167
Georg Brandl15a515f2009-09-17 22:11:49 +00001168 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1169 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1170 ``None``, and an empty list is automatically created the first time the option
1171 is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +00001172
Georg Brandl15a515f2009-09-17 22:11:49 +00001173* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001174
Georg Brandl15a515f2009-09-17 22:11:49 +00001175 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1176 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1177 first time.
Georg Brandl116aa622007-08-15 14:28:22 +00001178
1179 Example::
1180
1181 parser.add_option("-v", action="count", dest="verbosity")
1182
Éric Araujo713d3032010-11-18 16:38:46 +00001183 The first time ``-v`` is seen on the command line, :mod:`optparse` does the
Georg Brandl116aa622007-08-15 14:28:22 +00001184 equivalent of::
1185
1186 options.verbosity = 0
1187 options.verbosity += 1
1188
Éric Araujo713d3032010-11-18 16:38:46 +00001189 Every subsequent occurrence of ``-v`` results in ::
Georg Brandl116aa622007-08-15 14:28:22 +00001190
1191 options.verbosity += 1
1192
Georg Brandl15a515f2009-09-17 22:11:49 +00001193* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1194 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1195 :attr:`~Option.callback_kwargs`]
Georg Brandl116aa622007-08-15 14:28:22 +00001196
Georg Brandl15a515f2009-09-17 22:11:49 +00001197 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001198
1199 func(option, opt_str, value, parser, *args, **kwargs)
1200
1201 See section :ref:`optparse-option-callbacks` for more detail.
1202
Georg Brandl15a515f2009-09-17 22:11:49 +00001203* ``"help"``
Georg Brandl116aa622007-08-15 14:28:22 +00001204
Georg Brandl15a515f2009-09-17 22:11:49 +00001205 Prints a complete help message for all the options in the current option
1206 parser. The help message is constructed from the ``usage`` string passed to
1207 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1208 option.
Georg Brandl116aa622007-08-15 14:28:22 +00001209
Georg Brandl15a515f2009-09-17 22:11:49 +00001210 If no :attr:`~Option.help` string is supplied for an option, it will still be
1211 listed in the help message. To omit an option entirely, use the special value
1212 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl116aa622007-08-15 14:28:22 +00001213
Georg Brandl15a515f2009-09-17 22:11:49 +00001214 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1215 OptionParsers, so you do not normally need to create one.
Georg Brandl116aa622007-08-15 14:28:22 +00001216
1217 Example::
1218
1219 from optparse import OptionParser, SUPPRESS_HELP
1220
Georg Brandlee8783d2009-09-16 16:00:31 +00001221 # usually, a help option is added automatically, but that can
1222 # be suppressed using the add_help_option argument
1223 parser = OptionParser(add_help_option=False)
1224
1225 parser.add_option("-h", "--help", action="help")
Georg Brandl116aa622007-08-15 14:28:22 +00001226 parser.add_option("-v", action="store_true", dest="verbose",
1227 help="Be moderately verbose")
1228 parser.add_option("--file", dest="filename",
Georg Brandlee8783d2009-09-16 16:00:31 +00001229 help="Input file to read data from")
Georg Brandl116aa622007-08-15 14:28:22 +00001230 parser.add_option("--secret", help=SUPPRESS_HELP)
1231
Éric Araujo713d3032010-11-18 16:38:46 +00001232 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
Georg Brandl15a515f2009-09-17 22:11:49 +00001233 it will print something like the following help message to stdout (assuming
Ezio Melotti383ae952010-01-03 09:06:02 +00001234 ``sys.argv[0]`` is ``"foo.py"``):
1235
1236 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +00001237
Georg Brandl121ff822011-01-02 14:23:43 +00001238 Usage: foo.py [options]
Georg Brandl116aa622007-08-15 14:28:22 +00001239
Georg Brandl121ff822011-01-02 14:23:43 +00001240 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001241 -h, --help Show this help message and exit
1242 -v Be moderately verbose
1243 --file=FILENAME Input file to read data from
1244
1245 After printing the help message, :mod:`optparse` terminates your process with
1246 ``sys.exit(0)``.
1247
Georg Brandl15a515f2009-09-17 22:11:49 +00001248* ``"version"``
Georg Brandl116aa622007-08-15 14:28:22 +00001249
Georg Brandl15a515f2009-09-17 22:11:49 +00001250 Prints the version number supplied to the OptionParser to stdout and exits.
1251 The version number is actually formatted and printed by the
1252 ``print_version()`` method of OptionParser. Generally only relevant if the
1253 ``version`` argument is supplied to the OptionParser constructor. As with
1254 :attr:`~Option.help` options, you will rarely create ``version`` options,
1255 since :mod:`optparse` automatically adds them when needed.
Georg Brandl116aa622007-08-15 14:28:22 +00001256
1257
1258.. _optparse-standard-option-types:
1259
1260Standard option types
1261^^^^^^^^^^^^^^^^^^^^^
1262
Georg Brandl15a515f2009-09-17 22:11:49 +00001263:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1264``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1265option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +00001266
1267Arguments to string options are not checked or converted in any way: the text on
1268the command line is stored in the destination (or passed to the callback) as-is.
1269
Georg Brandl15a515f2009-09-17 22:11:49 +00001270Integer arguments (type ``"int"``) are parsed as follows:
Georg Brandl116aa622007-08-15 14:28:22 +00001271
1272* if the number starts with ``0x``, it is parsed as a hexadecimal number
1273
1274* if the number starts with ``0``, it is parsed as an octal number
1275
Georg Brandl9afde1c2007-11-01 20:32:30 +00001276* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl116aa622007-08-15 14:28:22 +00001277
1278* otherwise, the number is parsed as a decimal number
1279
1280
Georg Brandl15a515f2009-09-17 22:11:49 +00001281The conversion is done by calling :func:`int` with the appropriate base (2, 8,
128210, or 16). If this fails, so will :mod:`optparse`, although with a more useful
Georg Brandl5c106642007-11-29 17:41:05 +00001283error message.
Georg Brandl116aa622007-08-15 14:28:22 +00001284
Georg Brandl15a515f2009-09-17 22:11:49 +00001285``"float"`` and ``"complex"`` option arguments are converted directly with
1286:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl116aa622007-08-15 14:28:22 +00001287
Georg Brandl15a515f2009-09-17 22:11:49 +00001288``"choice"`` options are a subtype of ``"string"`` options. The
Georg Brandl682d7e02010-10-06 10:26:05 +00001289:attr:`~Option.choices` option attribute (a sequence of strings) defines the
Georg Brandl15a515f2009-09-17 22:11:49 +00001290set of allowed option arguments. :func:`optparse.check_choice` compares
1291user-supplied option arguments against this master list and raises
1292:exc:`OptionValueError` if an invalid string is given.
Georg Brandl116aa622007-08-15 14:28:22 +00001293
1294
1295.. _optparse-parsing-arguments:
1296
1297Parsing arguments
1298^^^^^^^^^^^^^^^^^
1299
1300The whole point of creating and populating an OptionParser is to call its
1301:meth:`parse_args` method::
1302
1303 (options, args) = parser.parse_args(args=None, values=None)
1304
1305where the input parameters are
1306
1307``args``
1308 the list of arguments to process (default: ``sys.argv[1:]``)
1309
1310``values``
Georg Brandl09410122010-08-01 06:53:28 +00001311 a :class:`optparse.Values` object to store option arguments in (default: a
1312 new instance of :class:`Values`) -- if you give an existing object, the
1313 option defaults will not be initialized on it
Georg Brandl116aa622007-08-15 14:28:22 +00001314
1315and the return values are
1316
1317``options``
Georg Brandla6053b42009-09-01 08:11:14 +00001318 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl116aa622007-08-15 14:28:22 +00001319 instance created by :mod:`optparse`
1320
1321``args``
1322 the leftover positional arguments after all options have been processed
1323
1324The most common usage is to supply neither keyword argument. If you supply
Georg Brandl15a515f2009-09-17 22:11:49 +00001325``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl116aa622007-08-15 14:28:22 +00001326for every option argument stored to an option destination) and returned by
1327:meth:`parse_args`.
1328
1329If :meth:`parse_args` encounters any errors in the argument list, it calls the
1330OptionParser's :meth:`error` method with an appropriate end-user error message.
1331This ultimately terminates your process with an exit status of 2 (the
1332traditional Unix exit status for command-line errors).
1333
1334
1335.. _optparse-querying-manipulating-option-parser:
1336
1337Querying and manipulating your option parser
1338^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1339
Georg Brandl15a515f2009-09-17 22:11:49 +00001340The default behavior of the option parser can be customized slightly, and you
1341can also poke around your option parser and see what's there. OptionParser
1342provides several methods to help you out:
Georg Brandl116aa622007-08-15 14:28:22 +00001343
Georg Brandl15a515f2009-09-17 22:11:49 +00001344.. method:: OptionParser.disable_interspersed_args()
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001345
Éric Araujo713d3032010-11-18 16:38:46 +00001346 Set parsing to stop on the first non-option. For example, if ``-a`` and
1347 ``-b`` are both simple options that take no arguments, :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001348 normally accepts this syntax::
Georg Brandl116aa622007-08-15 14:28:22 +00001349
Georg Brandl15a515f2009-09-17 22:11:49 +00001350 prog -a arg1 -b arg2
1351
1352 and treats it as equivalent to ::
1353
1354 prog -a -b arg1 arg2
1355
1356 To disable this feature, call :meth:`disable_interspersed_args`. This
1357 restores traditional Unix syntax, where option parsing stops with the first
1358 non-option argument.
1359
1360 Use this if you have a command processor which runs another command which has
1361 options of its own and you want to make sure these options don't get
1362 confused. For example, each command might have a different set of options.
1363
1364.. method:: OptionParser.enable_interspersed_args()
1365
1366 Set parsing to not stop on the first non-option, allowing interspersing
1367 switches with command arguments. This is the default behavior.
1368
1369.. method:: OptionParser.get_option(opt_str)
1370
1371 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl116aa622007-08-15 14:28:22 +00001372 no options have that option string.
1373
Georg Brandl15a515f2009-09-17 22:11:49 +00001374.. method:: OptionParser.has_option(opt_str)
1375
1376 Return true if the OptionParser has an option with option string *opt_str*
Éric Araujo713d3032010-11-18 16:38:46 +00001377 (e.g., ``-q`` or ``--verbose``).
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001378
Georg Brandl15a515f2009-09-17 22:11:49 +00001379.. method:: OptionParser.remove_option(opt_str)
1380
1381 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1382 option is removed. If that option provided any other option strings, all of
1383 those option strings become invalid. If *opt_str* does not occur in any
1384 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001385
1386
1387.. _optparse-conflicts-between-options:
1388
1389Conflicts between options
1390^^^^^^^^^^^^^^^^^^^^^^^^^
1391
1392If you're not careful, it's easy to define options with conflicting option
1393strings::
1394
1395 parser.add_option("-n", "--dry-run", ...)
1396 [...]
1397 parser.add_option("-n", "--noisy", ...)
1398
1399(This is particularly true if you've defined your own OptionParser subclass with
1400some standard options.)
1401
1402Every time you add an option, :mod:`optparse` checks for conflicts with existing
1403options. If it finds any, it invokes the current conflict-handling mechanism.
1404You can set the conflict-handling mechanism either in the constructor::
1405
1406 parser = OptionParser(..., conflict_handler=handler)
1407
1408or with a separate call::
1409
1410 parser.set_conflict_handler(handler)
1411
1412The available conflict handlers are:
1413
Georg Brandl15a515f2009-09-17 22:11:49 +00001414 ``"error"`` (default)
1415 assume option conflicts are a programming error and raise
1416 :exc:`OptionConflictError`
Georg Brandl116aa622007-08-15 14:28:22 +00001417
Georg Brandl15a515f2009-09-17 22:11:49 +00001418 ``"resolve"``
Georg Brandl116aa622007-08-15 14:28:22 +00001419 resolve option conflicts intelligently (see below)
1420
1421
Benjamin Petersone5384b02008-10-04 22:00:42 +00001422As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl116aa622007-08-15 14:28:22 +00001423intelligently and add conflicting options to it::
1424
1425 parser = OptionParser(conflict_handler="resolve")
1426 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1427 parser.add_option("-n", "--noisy", ..., help="be noisy")
1428
1429At this point, :mod:`optparse` detects that a previously-added option is already
Éric Araujo713d3032010-11-18 16:38:46 +00001430using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1431it resolves the situation by removing ``-n`` from the earlier option's list of
1432option strings. Now ``--dry-run`` is the only way for the user to activate
Georg Brandl116aa622007-08-15 14:28:22 +00001433that option. If the user asks for help, the help message will reflect that::
1434
Georg Brandl121ff822011-01-02 14:23:43 +00001435 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001436 --dry-run do no harm
1437 [...]
1438 -n, --noisy be noisy
1439
1440It's possible to whittle away the option strings for a previously-added option
1441until there are none left, and the user has no way of invoking that option from
1442the command-line. In that case, :mod:`optparse` removes that option completely,
1443so it doesn't show up in help text or anywhere else. Carrying on with our
1444existing OptionParser::
1445
1446 parser.add_option("--dry-run", ..., help="new dry-run option")
1447
Éric Araujo713d3032010-11-18 16:38:46 +00001448At this point, the original ``-n``/``--dry-run`` option is no longer
Georg Brandl116aa622007-08-15 14:28:22 +00001449accessible, so :mod:`optparse` removes it, leaving this help text::
1450
Georg Brandl121ff822011-01-02 14:23:43 +00001451 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001452 [...]
1453 -n, --noisy be noisy
1454 --dry-run new dry-run option
1455
1456
1457.. _optparse-cleanup:
1458
1459Cleanup
1460^^^^^^^
1461
1462OptionParser instances have several cyclic references. This should not be a
1463problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandl15a515f2009-09-17 22:11:49 +00001464references explicitly by calling :meth:`~OptionParser.destroy` on your
1465OptionParser once you are done with it. This is particularly useful in
1466long-running applications where large object graphs are reachable from your
1467OptionParser.
Georg Brandl116aa622007-08-15 14:28:22 +00001468
1469
1470.. _optparse-other-methods:
1471
1472Other methods
1473^^^^^^^^^^^^^
1474
1475OptionParser supports several other public methods:
1476
Georg Brandl15a515f2009-09-17 22:11:49 +00001477.. method:: OptionParser.set_usage(usage)
Georg Brandl116aa622007-08-15 14:28:22 +00001478
Georg Brandl15a515f2009-09-17 22:11:49 +00001479 Set the usage string according to the rules described above for the ``usage``
1480 constructor keyword argument. Passing ``None`` sets the default usage
1481 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl116aa622007-08-15 14:28:22 +00001482
Ezio Melotti1ce43192010-01-04 21:53:17 +00001483.. method:: OptionParser.print_usage(file=None)
1484
1485 Print the usage message for the current program (``self.usage``) to *file*
Éric Araujo713d3032010-11-18 16:38:46 +00001486 (default stdout). Any occurrence of the string ``%prog`` in ``self.usage``
Ezio Melotti1ce43192010-01-04 21:53:17 +00001487 is replaced with the name of the current program. Does nothing if
1488 ``self.usage`` is empty or not defined.
1489
1490.. method:: OptionParser.get_usage()
1491
1492 Same as :meth:`print_usage` but returns the usage string instead of
1493 printing it.
1494
Georg Brandl15a515f2009-09-17 22:11:49 +00001495.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +00001496
Georg Brandl15a515f2009-09-17 22:11:49 +00001497 Set default values for several option destinations at once. Using
1498 :meth:`set_defaults` is the preferred way to set default values for options,
1499 since multiple options can share the same destination. For example, if
1500 several "mode" options all set the same destination, any one of them can set
1501 the default, and the last one wins::
Georg Brandl116aa622007-08-15 14:28:22 +00001502
Georg Brandl15a515f2009-09-17 22:11:49 +00001503 parser.add_option("--advanced", action="store_const",
1504 dest="mode", const="advanced",
1505 default="novice") # overridden below
1506 parser.add_option("--novice", action="store_const",
1507 dest="mode", const="novice",
1508 default="advanced") # overrides above setting
Georg Brandl116aa622007-08-15 14:28:22 +00001509
Georg Brandl15a515f2009-09-17 22:11:49 +00001510 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl116aa622007-08-15 14:28:22 +00001511
Georg Brandl15a515f2009-09-17 22:11:49 +00001512 parser.set_defaults(mode="advanced")
1513 parser.add_option("--advanced", action="store_const",
1514 dest="mode", const="advanced")
1515 parser.add_option("--novice", action="store_const",
1516 dest="mode", const="novice")
Georg Brandl116aa622007-08-15 14:28:22 +00001517
Georg Brandl116aa622007-08-15 14:28:22 +00001518
1519.. _optparse-option-callbacks:
1520
1521Option Callbacks
1522----------------
1523
1524When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1525needs, you have two choices: extend :mod:`optparse` or define a callback option.
1526Extending :mod:`optparse` is more general, but overkill for a lot of simple
1527cases. Quite often a simple callback is all you need.
1528
1529There are two steps to defining a callback option:
1530
Georg Brandl15a515f2009-09-17 22:11:49 +00001531* define the option itself using the ``"callback"`` action
Georg Brandl116aa622007-08-15 14:28:22 +00001532
1533* write the callback; this is a function (or method) that takes at least four
1534 arguments, as described below
1535
1536
1537.. _optparse-defining-callback-option:
1538
1539Defining a callback option
1540^^^^^^^^^^^^^^^^^^^^^^^^^^
1541
1542As always, the easiest way to define a callback option is by using the
Georg Brandl15a515f2009-09-17 22:11:49 +00001543:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1544only option attribute you must specify is ``callback``, the function to call::
Georg Brandl116aa622007-08-15 14:28:22 +00001545
1546 parser.add_option("-c", action="callback", callback=my_callback)
1547
1548``callback`` is a function (or other callable object), so you must have already
1549defined ``my_callback()`` when you create this callback option. In this simple
Éric Araujo713d3032010-11-18 16:38:46 +00001550case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
Georg Brandl116aa622007-08-15 14:28:22 +00001551which usually means that the option takes no arguments---the mere presence of
Éric Araujo713d3032010-11-18 16:38:46 +00001552``-c`` on the command-line is all it needs to know. In some
Georg Brandl116aa622007-08-15 14:28:22 +00001553circumstances, though, you might want your callback to consume an arbitrary
1554number of command-line arguments. This is where writing callbacks gets tricky;
1555it's covered later in this section.
1556
1557:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandl15a515f2009-09-17 22:11:49 +00001558will only pass additional arguments if you specify them via
1559:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1560minimal callback function signature is::
Georg Brandl116aa622007-08-15 14:28:22 +00001561
1562 def my_callback(option, opt, value, parser):
1563
1564The four arguments to a callback are described below.
1565
1566There are several other option attributes that you can supply when you define a
1567callback option:
1568
Georg Brandl15a515f2009-09-17 22:11:49 +00001569:attr:`~Option.type`
1570 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1571 instructs :mod:`optparse` to consume one argument and convert it to
1572 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1573 though, :mod:`optparse` passes it to your callback function.
Georg Brandl116aa622007-08-15 14:28:22 +00001574
Georg Brandl15a515f2009-09-17 22:11:49 +00001575:attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001576 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001577 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1578 :attr:`~Option.type`. It then passes a tuple of converted values to your
1579 callback.
Georg Brandl116aa622007-08-15 14:28:22 +00001580
Georg Brandl15a515f2009-09-17 22:11:49 +00001581:attr:`~Option.callback_args`
Georg Brandl116aa622007-08-15 14:28:22 +00001582 a tuple of extra positional arguments to pass to the callback
1583
Georg Brandl15a515f2009-09-17 22:11:49 +00001584:attr:`~Option.callback_kwargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001585 a dictionary of extra keyword arguments to pass to the callback
1586
1587
1588.. _optparse-how-callbacks-called:
1589
1590How callbacks are called
1591^^^^^^^^^^^^^^^^^^^^^^^^
1592
1593All callbacks are called as follows::
1594
1595 func(option, opt_str, value, parser, *args, **kwargs)
1596
1597where
1598
1599``option``
1600 is the Option instance that's calling the callback
1601
1602``opt_str``
1603 is the option string seen on the command-line that's triggering the callback.
Georg Brandl15a515f2009-09-17 22:11:49 +00001604 (If an abbreviated long option was used, ``opt_str`` will be the full,
Éric Araujo713d3032010-11-18 16:38:46 +00001605 canonical option string---e.g. if the user puts ``--foo`` on the
1606 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
Georg Brandl15a515f2009-09-17 22:11:49 +00001607 ``"--foobar"``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001608
1609``value``
1610 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001611 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1612 the type implied by the option's type. If :attr:`~Option.type` for this option is
1613 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001614 > 1, ``value`` will be a tuple of values of the appropriate type.
1615
1616``parser``
Georg Brandl15a515f2009-09-17 22:11:49 +00001617 is the OptionParser instance driving the whole thing, mainly useful because
1618 you can access some other interesting data through its instance attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001619
1620 ``parser.largs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001621 the current list of leftover arguments, ie. arguments that have been
1622 consumed but are neither options nor option arguments. Feel free to modify
1623 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1624 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001625
1626 ``parser.rargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001627 the current list of remaining arguments, ie. with ``opt_str`` and
1628 ``value`` (if applicable) removed, and only the arguments following them
1629 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1630 arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001631
1632 ``parser.values``
1633 the object where option values are by default stored (an instance of
Georg Brandl15a515f2009-09-17 22:11:49 +00001634 optparse.OptionValues). This lets callbacks use the same mechanism as the
1635 rest of :mod:`optparse` for storing option values; you don't need to mess
1636 around with globals or closures. You can also access or modify the
1637 value(s) of any options already encountered on the command-line.
Georg Brandl116aa622007-08-15 14:28:22 +00001638
1639``args``
Georg Brandl15a515f2009-09-17 22:11:49 +00001640 is a tuple of arbitrary positional arguments supplied via the
1641 :attr:`~Option.callback_args` option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001642
1643``kwargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001644 is a dictionary of arbitrary keyword arguments supplied via
1645 :attr:`~Option.callback_kwargs`.
Georg Brandl116aa622007-08-15 14:28:22 +00001646
1647
1648.. _optparse-raising-errors-in-callback:
1649
1650Raising errors in a callback
1651^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1652
Georg Brandl15a515f2009-09-17 22:11:49 +00001653The callback function should raise :exc:`OptionValueError` if there are any
1654problems with the option or its argument(s). :mod:`optparse` catches this and
1655terminates the program, printing the error message you supply to stderr. Your
1656message should be clear, concise, accurate, and mention the option at fault.
1657Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl116aa622007-08-15 14:28:22 +00001658
1659
1660.. _optparse-callback-example-1:
1661
1662Callback example 1: trivial callback
1663^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1664
1665Here's an example of a callback option that takes no arguments, and simply
1666records that the option was seen::
1667
1668 def record_foo_seen(option, opt_str, value, parser):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001669 parser.values.saw_foo = True
Georg Brandl116aa622007-08-15 14:28:22 +00001670
1671 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1672
Georg Brandl15a515f2009-09-17 22:11:49 +00001673Of course, you could do that with the ``"store_true"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001674
1675
1676.. _optparse-callback-example-2:
1677
1678Callback example 2: check option order
1679^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1680
Éric Araujo713d3032010-11-18 16:38:46 +00001681Here's a slightly more interesting example: record the fact that ``-a`` is
1682seen, but blow up if it comes after ``-b`` in the command-line. ::
Georg Brandl116aa622007-08-15 14:28:22 +00001683
1684 def check_order(option, opt_str, value, parser):
1685 if parser.values.b:
1686 raise OptionValueError("can't use -a after -b")
1687 parser.values.a = 1
1688 [...]
1689 parser.add_option("-a", action="callback", callback=check_order)
1690 parser.add_option("-b", action="store_true", dest="b")
1691
1692
1693.. _optparse-callback-example-3:
1694
1695Callback example 3: check option order (generalized)
1696^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1697
1698If you want to re-use this callback for several similar options (set a flag, but
Éric Araujo713d3032010-11-18 16:38:46 +00001699blow up if ``-b`` has already been seen), it needs a bit of work: the error
Georg Brandl116aa622007-08-15 14:28:22 +00001700message and the flag that it sets must be generalized. ::
1701
1702 def check_order(option, opt_str, value, parser):
1703 if parser.values.b:
1704 raise OptionValueError("can't use %s after -b" % opt_str)
1705 setattr(parser.values, option.dest, 1)
1706 [...]
1707 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1708 parser.add_option("-b", action="store_true", dest="b")
1709 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1710
1711
1712.. _optparse-callback-example-4:
1713
1714Callback example 4: check arbitrary condition
1715^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1716
1717Of course, you could put any condition in there---you're not limited to checking
1718the values of already-defined options. For example, if you have options that
1719should not be called when the moon is full, all you have to do is this::
1720
1721 def check_moon(option, opt_str, value, parser):
1722 if is_moon_full():
1723 raise OptionValueError("%s option invalid when moon is full"
1724 % opt_str)
1725 setattr(parser.values, option.dest, 1)
1726 [...]
1727 parser.add_option("--foo",
1728 action="callback", callback=check_moon, dest="foo")
1729
1730(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1731
1732
1733.. _optparse-callback-example-5:
1734
1735Callback example 5: fixed arguments
1736^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1737
1738Things get slightly more interesting when you define callback options that take
1739a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandl15a515f2009-09-17 22:11:49 +00001740is similar to defining a ``"store"`` or ``"append"`` option: if you define
1741:attr:`~Option.type`, then the option takes one argument that must be
1742convertible to that type; if you further define :attr:`~Option.nargs`, then the
1743option takes :attr:`~Option.nargs` arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001744
Georg Brandl15a515f2009-09-17 22:11:49 +00001745Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl116aa622007-08-15 14:28:22 +00001746
1747 def store_value(option, opt_str, value, parser):
1748 setattr(parser.values, option.dest, value)
1749 [...]
1750 parser.add_option("--foo",
1751 action="callback", callback=store_value,
1752 type="int", nargs=3, dest="foo")
1753
1754Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1755them to integers for you; all you have to do is store them. (Or whatever;
1756obviously you don't need a callback for this example.)
1757
1758
1759.. _optparse-callback-example-6:
1760
1761Callback example 6: variable arguments
1762^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1763
1764Things get hairy when you want an option to take a variable number of arguments.
1765For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1766built-in capabilities for it. And you have to deal with certain intricacies of
1767conventional Unix command-line parsing that :mod:`optparse` normally handles for
1768you. In particular, callbacks should implement the conventional rules for bare
Éric Araujo713d3032010-11-18 16:38:46 +00001769``--`` and ``-`` arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001770
Éric Araujo713d3032010-11-18 16:38:46 +00001771* either ``--`` or ``-`` can be option arguments
Georg Brandl116aa622007-08-15 14:28:22 +00001772
Éric Araujo713d3032010-11-18 16:38:46 +00001773* bare ``--`` (if not the argument to some option): halt command-line
1774 processing and discard the ``--``
Georg Brandl116aa622007-08-15 14:28:22 +00001775
Éric Araujo713d3032010-11-18 16:38:46 +00001776* bare ``-`` (if not the argument to some option): halt command-line
1777 processing but keep the ``-`` (append it to ``parser.largs``)
Georg Brandl116aa622007-08-15 14:28:22 +00001778
1779If you want an option that takes a variable number of arguments, there are
1780several subtle, tricky issues to worry about. The exact implementation you
1781choose will be based on which trade-offs you're willing to make for your
1782application (which is why :mod:`optparse` doesn't support this sort of thing
1783directly).
1784
1785Nevertheless, here's a stab at a callback for an option with variable
1786arguments::
1787
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001788 def vararg_callback(option, opt_str, value, parser):
1789 assert value is None
1790 value = []
Georg Brandl116aa622007-08-15 14:28:22 +00001791
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001792 def floatable(str):
1793 try:
1794 float(str)
1795 return True
1796 except ValueError:
1797 return False
Georg Brandl116aa622007-08-15 14:28:22 +00001798
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001799 for arg in parser.rargs:
1800 # stop on --foo like options
1801 if arg[:2] == "--" and len(arg) > 2:
1802 break
1803 # stop on -a, but not on -3 or -3.0
1804 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1805 break
1806 value.append(arg)
1807
1808 del parser.rargs[:len(value)]
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001809 setattr(parser.values, option.dest, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001810
1811 [...]
Benjamin Petersonae5360b2008-09-08 23:05:23 +00001812 parser.add_option("-c", "--callback", dest="vararg_attr",
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001813 action="callback", callback=vararg_callback)
Georg Brandl116aa622007-08-15 14:28:22 +00001814
Georg Brandl116aa622007-08-15 14:28:22 +00001815
1816.. _optparse-extending-optparse:
1817
1818Extending :mod:`optparse`
1819-------------------------
1820
1821Since the two major controlling factors in how :mod:`optparse` interprets
1822command-line options are the action and type of each option, the most likely
1823direction of extension is to add new actions and new types.
1824
1825
1826.. _optparse-adding-new-types:
1827
1828Adding new types
1829^^^^^^^^^^^^^^^^
1830
1831To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandl15a515f2009-09-17 22:11:49 +00001832:class:`Option` class. This class has a couple of attributes that define
1833:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl116aa622007-08-15 14:28:22 +00001834
Georg Brandl15a515f2009-09-17 22:11:49 +00001835.. attribute:: Option.TYPES
Georg Brandl116aa622007-08-15 14:28:22 +00001836
Georg Brandl15a515f2009-09-17 22:11:49 +00001837 A tuple of type names; in your subclass, simply define a new tuple
1838 :attr:`TYPES` that builds on the standard one.
Georg Brandl116aa622007-08-15 14:28:22 +00001839
Georg Brandl15a515f2009-09-17 22:11:49 +00001840.. attribute:: Option.TYPE_CHECKER
Georg Brandl116aa622007-08-15 14:28:22 +00001841
Georg Brandl15a515f2009-09-17 22:11:49 +00001842 A dictionary mapping type names to type-checking functions. A type-checking
1843 function has the following signature::
Georg Brandl116aa622007-08-15 14:28:22 +00001844
Georg Brandl15a515f2009-09-17 22:11:49 +00001845 def check_mytype(option, opt, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001846
Georg Brandl15a515f2009-09-17 22:11:49 +00001847 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
Éric Araujo713d3032010-11-18 16:38:46 +00001848 (e.g., ``-f``), and ``value`` is the string from the command line that must
Georg Brandl15a515f2009-09-17 22:11:49 +00001849 be checked and converted to your desired type. ``check_mytype()`` should
1850 return an object of the hypothetical type ``mytype``. The value returned by
1851 a type-checking function will wind up in the OptionValues instance returned
1852 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1853 ``value`` parameter.
1854
1855 Your type-checking function should raise :exc:`OptionValueError` if it
1856 encounters any problems. :exc:`OptionValueError` takes a single string
1857 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1858 method, which in turn prepends the program name and the string ``"error:"``
1859 and prints everything to stderr before terminating the process.
1860
1861Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl116aa622007-08-15 14:28:22 +00001862parse Python-style complex numbers on the command line. (This is even sillier
1863than it used to be, because :mod:`optparse` 1.3 added built-in support for
1864complex numbers, but never mind.)
1865
1866First, the necessary imports::
1867
1868 from copy import copy
1869 from optparse import Option, OptionValueError
1870
1871You need to define your type-checker first, since it's referred to later (in the
Georg Brandl15a515f2009-09-17 22:11:49 +00001872:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl116aa622007-08-15 14:28:22 +00001873
1874 def check_complex(option, opt, value):
1875 try:
1876 return complex(value)
1877 except ValueError:
1878 raise OptionValueError(
1879 "option %s: invalid complex value: %r" % (opt, value))
1880
1881Finally, the Option subclass::
1882
1883 class MyOption (Option):
1884 TYPES = Option.TYPES + ("complex",)
1885 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1886 TYPE_CHECKER["complex"] = check_complex
1887
1888(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandl15a515f2009-09-17 22:11:49 +00001889up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1890Option class. This being Python, nothing stops you from doing that except good
1891manners and common sense.)
Georg Brandl116aa622007-08-15 14:28:22 +00001892
1893That's it! Now you can write a script that uses the new option type just like
1894any other :mod:`optparse`\ -based script, except you have to instruct your
1895OptionParser to use MyOption instead of Option::
1896
1897 parser = OptionParser(option_class=MyOption)
1898 parser.add_option("-c", type="complex")
1899
1900Alternately, you can build your own option list and pass it to OptionParser; if
1901you don't use :meth:`add_option` in the above way, you don't need to tell
1902OptionParser which option class to use::
1903
1904 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1905 parser = OptionParser(option_list=option_list)
1906
1907
1908.. _optparse-adding-new-actions:
1909
1910Adding new actions
1911^^^^^^^^^^^^^^^^^^
1912
1913Adding new actions is a bit trickier, because you have to understand that
1914:mod:`optparse` has a couple of classifications for actions:
1915
1916"store" actions
1917 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandl15a515f2009-09-17 22:11:49 +00001918 current OptionValues instance; these options require a :attr:`~Option.dest`
1919 attribute to be supplied to the Option constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001920
1921"typed" actions
Georg Brandl15a515f2009-09-17 22:11:49 +00001922 actions that take a value from the command line and expect it to be of a
1923 certain type; or rather, a string that can be converted to a certain type.
1924 These options require a :attr:`~Option.type` attribute to the Option
1925 constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001926
Georg Brandl15a515f2009-09-17 22:11:49 +00001927These are overlapping sets: some default "store" actions are ``"store"``,
1928``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1929actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001930
1931When you add an action, you need to categorize it by listing it in at least one
1932of the following class attributes of Option (all are lists of strings):
1933
Georg Brandl15a515f2009-09-17 22:11:49 +00001934.. attribute:: Option.ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001935
Georg Brandl15a515f2009-09-17 22:11:49 +00001936 All actions must be listed in ACTIONS.
Georg Brandl116aa622007-08-15 14:28:22 +00001937
Georg Brandl15a515f2009-09-17 22:11:49 +00001938.. attribute:: Option.STORE_ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001939
Georg Brandl15a515f2009-09-17 22:11:49 +00001940 "store" actions are additionally listed here.
1941
1942.. attribute:: Option.TYPED_ACTIONS
1943
1944 "typed" actions are additionally listed here.
1945
1946.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1947
1948 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl116aa622007-08-15 14:28:22 +00001949 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001950 assigns the default type, ``"string"``, to options with no explicit type
1951 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001952
1953In order to actually implement your new action, you must override Option's
1954:meth:`take_action` method and add a case that recognizes your action.
1955
Georg Brandl15a515f2009-09-17 22:11:49 +00001956For example, let's add an ``"extend"`` action. This is similar to the standard
1957``"append"`` action, but instead of taking a single value from the command-line
1958and appending it to an existing list, ``"extend"`` will take multiple values in
1959a single comma-delimited string, and extend an existing list with them. That
Éric Araujo713d3032010-11-18 16:38:46 +00001960is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
Georg Brandl15a515f2009-09-17 22:11:49 +00001961line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001962
1963 --names=foo,bar --names blah --names ding,dong
1964
1965would result in a list ::
1966
1967 ["foo", "bar", "blah", "ding", "dong"]
1968
1969Again we define a subclass of Option::
1970
Ezio Melotti383ae952010-01-03 09:06:02 +00001971 class MyOption(Option):
Georg Brandl116aa622007-08-15 14:28:22 +00001972
1973 ACTIONS = Option.ACTIONS + ("extend",)
1974 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1975 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1976 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1977
1978 def take_action(self, action, dest, opt, value, values, parser):
1979 if action == "extend":
1980 lvalue = value.split(",")
1981 values.ensure_value(dest, []).extend(lvalue)
1982 else:
1983 Option.take_action(
1984 self, action, dest, opt, value, values, parser)
1985
1986Features of note:
1987
Georg Brandl15a515f2009-09-17 22:11:49 +00001988* ``"extend"`` both expects a value on the command-line and stores that value
1989 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1990 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001991
Georg Brandl15a515f2009-09-17 22:11:49 +00001992* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1993 ``"extend"`` actions, we put the ``"extend"`` action in
1994 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001995
1996* :meth:`MyOption.take_action` implements just this one new action, and passes
1997 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001998 actions.
Georg Brandl116aa622007-08-15 14:28:22 +00001999
Georg Brandl15a515f2009-09-17 22:11:49 +00002000* ``values`` is an instance of the optparse_parser.Values class, which provides
2001 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
2002 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00002003
2004 values.ensure_value(attr, value)
2005
2006 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandl15a515f2009-09-17 22:11:49 +00002007 ensure_value() first sets it to ``value``, and then returns 'value. This is
2008 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
2009 of which accumulate data in a variable and expect that variable to be of a
2010 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl116aa622007-08-15 14:28:22 +00002011 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandl15a515f2009-09-17 22:11:49 +00002012 about setting a default value for the option destinations in question; they
2013 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl116aa622007-08-15 14:28:22 +00002014 getting it right when it's needed.