blob: 87ec4de8d9ede5af5170b813f0f7581793f40293 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`optparse` --- More powerful command line option parser
2============================================================
3
4.. module:: optparse
5 :synopsis: More convenient, flexible, and powerful command-line parsing library.
6.. moduleauthor:: Greg Ward <gward@python.net>
Georg Brandl116aa622007-08-15 14:28:22 +00007.. sectionauthor:: Greg Ward <gward@python.net>
8
9
Georg Brandl6ba000c2009-09-17 22:17:38 +000010:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
11command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
12more declarative style of command-line parsing: you create an instance of
13:class:`OptionParser`, populate it with options, and parse the command
14line. :mod:`optparse` allows users to specify options in the conventional
15GNU/POSIX syntax, and additionally generates usage and help messages for you.
Georg Brandl116aa622007-08-15 14:28:22 +000016
Georg Brandl6ba000c2009-09-17 22:17:38 +000017Here's an example of using :mod:`optparse` in a simple script::
Georg Brandl116aa622007-08-15 14:28:22 +000018
19 from optparse import OptionParser
20 [...]
21 parser = OptionParser()
22 parser.add_option("-f", "--file", dest="filename",
23 help="write report to FILE", metavar="FILE")
24 parser.add_option("-q", "--quiet",
25 action="store_false", dest="verbose", default=True,
26 help="don't print status messages to stdout")
27
28 (options, args) = parser.parse_args()
29
30With these few lines of code, users of your script can now do the "usual thing"
31on the command-line, for example::
32
33 <yourscript> --file=outfile -q
34
Georg Brandl6ba000c2009-09-17 22:17:38 +000035As it parses the command line, :mod:`optparse` sets attributes of the
36``options`` object returned by :meth:`parse_args` based on user-supplied
37command-line values. When :meth:`parse_args` returns from parsing this command
38line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
39``False``. :mod:`optparse` supports both long and short options, allows short
Georg Brandl116aa622007-08-15 14:28:22 +000040options to be merged together, and allows options to be associated with their
41arguments in a variety of ways. Thus, the following command lines are all
42equivalent to the above example::
43
44 <yourscript> -f outfile --quiet
45 <yourscript> --quiet --file outfile
46 <yourscript> -q -foutfile
47 <yourscript> -qfoutfile
48
49Additionally, users can run one of ::
50
51 <yourscript> -h
52 <yourscript> --help
53
Ezio Melottide2cef52010-01-03 09:08:34 +000054and :mod:`optparse` will print out a brief summary of your script's options:
55
56.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +000057
Georg Brandl27743102011-02-25 10:18:11 +000058 Usage: <yourscript> [options]
Georg Brandl116aa622007-08-15 14:28:22 +000059
Georg Brandl27743102011-02-25 10:18:11 +000060 Options:
Georg Brandl116aa622007-08-15 14:28:22 +000061 -h, --help show this help message and exit
62 -f FILE, --file=FILE write report to FILE
63 -q, --quiet don't print status messages to stdout
64
65where the value of *yourscript* is determined at runtime (normally from
66``sys.argv[0]``).
67
Georg Brandl116aa622007-08-15 14:28:22 +000068
69.. _optparse-background:
70
71Background
72----------
73
74:mod:`optparse` was explicitly designed to encourage the creation of programs
75with straightforward, conventional command-line interfaces. To that end, it
76supports only the most common command-line syntax and semantics conventionally
77used under Unix. If you are unfamiliar with these conventions, read this
78section to acquaint yourself with them.
79
80
81.. _optparse-terminology:
82
83Terminology
84^^^^^^^^^^^
85
86argument
Georg Brandl6ba000c2009-09-17 22:17:38 +000087 a string entered on the command-line, and passed by the shell to ``execl()``
88 or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
89 (``sys.argv[0]`` is the name of the program being executed). Unix shells
90 also use the term "word".
Georg Brandl116aa622007-08-15 14:28:22 +000091
92 It is occasionally desirable to substitute an argument list other than
93 ``sys.argv[1:]``, so you should read "argument" as "an element of
94 ``sys.argv[1:]``, or of some other list provided as a substitute for
95 ``sys.argv[1:]``".
96
Benjamin Petersonae5360b2008-09-08 23:05:23 +000097option
Georg Brandl6ba000c2009-09-17 22:17:38 +000098 an argument used to supply extra information to guide or customize the
99 execution of a program. There are many different syntaxes for options; the
100 traditional Unix syntax is a hyphen ("-") followed by a single letter,
Éric Araujo3efdf062010-12-16 03:16:29 +0000101 e.g. ``-x`` or ``-F``. Also, traditional Unix syntax allows multiple
102 options to be merged into a single argument, e.g. ``-x -F`` is equivalent
103 to ``-xF``. The GNU project introduced ``--`` followed by a series of
104 hyphen-separated words, e.g. ``--file`` or ``--dry-run``. These are the
Georg Brandl6ba000c2009-09-17 22:17:38 +0000105 only two option syntaxes provided by :mod:`optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107 Some other option syntaxes that the world has seen include:
108
Éric Araujo3efdf062010-12-16 03:16:29 +0000109 * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
Georg Brandl116aa622007-08-15 14:28:22 +0000110 as multiple options merged into a single argument)
111
Éric Araujo3efdf062010-12-16 03:16:29 +0000112 * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
Georg Brandl116aa622007-08-15 14:28:22 +0000113 equivalent to the previous syntax, but they aren't usually seen in the same
114 program)
115
116 * a plus sign followed by a single letter, or a few letters, or a word, e.g.
Éric Araujo3efdf062010-12-16 03:16:29 +0000117 ``+f``, ``+rgb``
Georg Brandl116aa622007-08-15 14:28:22 +0000118
Éric Araujo3efdf062010-12-16 03:16:29 +0000119 * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``,
120 ``/file``
Georg Brandl116aa622007-08-15 14:28:22 +0000121
Georg Brandl6ba000c2009-09-17 22:17:38 +0000122 These option syntaxes are not supported by :mod:`optparse`, and they never
123 will be. This is deliberate: the first three are non-standard on any
124 environment, and the last only makes sense if you're exclusively targeting
125 VMS, MS-DOS, and/or Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127option argument
Georg Brandl6ba000c2009-09-17 22:17:38 +0000128 an argument that follows an option, is closely associated with that option,
129 and is consumed from the argument list when that option is. With
130 :mod:`optparse`, option arguments may either be in a separate argument from
Ezio Melottide2cef52010-01-03 09:08:34 +0000131 their option:
132
133 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135 -f foo
136 --file foo
137
Ezio Melottide2cef52010-01-03 09:08:34 +0000138 or included in the same argument:
139
140 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000141
142 -ffoo
143 --file=foo
144
Georg Brandl6ba000c2009-09-17 22:17:38 +0000145 Typically, a given option either takes an argument or it doesn't. Lots of
146 people want an "optional option arguments" feature, meaning that some options
147 will take an argument if they see it, and won't if they don't. This is
Éric Araujo3efdf062010-12-16 03:16:29 +0000148 somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
149 an optional argument and ``-b`` is another option entirely, how do we
150 interpret ``-ab``? Because of this ambiguity, :mod:`optparse` does not
Georg Brandl6ba000c2009-09-17 22:17:38 +0000151 support this feature.
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153positional argument
154 something leftover in the argument list after options have been parsed, i.e.
Georg Brandl6ba000c2009-09-17 22:17:38 +0000155 after options and their arguments have been parsed and removed from the
156 argument list.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158required option
159 an option that must be supplied on the command-line; note that the phrase
160 "required option" is self-contradictory in English. :mod:`optparse` doesn't
Georg Brandl6ba000c2009-09-17 22:17:38 +0000161 prevent you from implementing required options, but doesn't give you much
Benjamin Peterson68dbebc2009-12-31 03:30:26 +0000162 help at it either.
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164For example, consider this hypothetical command-line::
165
166 prog -v --report /tmp/report.txt foo bar
167
Éric Araujo3efdf062010-12-16 03:16:29 +0000168``-v`` and ``--report`` are both options. Assuming that ``--report``
169takes one argument, ``/tmp/report.txt`` is an option argument. ``foo`` and
170``bar`` are positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000171
172
173.. _optparse-what-options-for:
174
175What are options for?
176^^^^^^^^^^^^^^^^^^^^^
177
178Options are used to provide extra information to tune or customize the execution
179of a program. In case it wasn't clear, options are usually *optional*. A
180program should be able to run just fine with no options whatsoever. (Pick a
181random program from the Unix or GNU toolsets. Can it run without any options at
182all and still make sense? The main exceptions are ``find``, ``tar``, and
183``dd``\ ---all of which are mutant oddballs that have been rightly criticized
184for their non-standard syntax and confusing interfaces.)
185
186Lots of people want their programs to have "required options". Think about it.
187If it's required, then it's *not optional*! If there is a piece of information
188that your program absolutely requires in order to run successfully, that's what
189positional arguments are for.
190
191As an example of good command-line interface design, consider the humble ``cp``
192utility, for copying files. It doesn't make much sense to try to copy files
193without supplying a destination and at least one source. Hence, ``cp`` fails if
194you run it with no arguments. However, it has a flexible, useful syntax that
195does not require any options at all::
196
197 cp SOURCE DEST
198 cp SOURCE ... DEST-DIR
199
200You can get pretty far with just that. Most ``cp`` implementations provide a
201bunch of options to tweak exactly how the files are copied: you can preserve
202mode and modification time, avoid following symlinks, ask before clobbering
203existing files, etc. But none of this distracts from the core mission of
204``cp``, which is to copy either one file to another, or several files to another
205directory.
206
207
208.. _optparse-what-positional-arguments-for:
209
210What are positional arguments for?
211^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
212
213Positional arguments are for those pieces of information that your program
214absolutely, positively requires to run.
215
216A good user interface should have as few absolute requirements as possible. If
217your program requires 17 distinct pieces of information in order to run
218successfully, it doesn't much matter *how* you get that information from the
219user---most people will give up and walk away before they successfully run the
220program. This applies whether the user interface is a command-line, a
221configuration file, or a GUI: if you make that many demands on your users, most
222of them will simply give up.
223
224In short, try to minimize the amount of information that users are absolutely
225required to supply---use sensible defaults whenever possible. Of course, you
226also want to make your programs reasonably flexible. That's what options are
227for. Again, it doesn't matter if they are entries in a config file, widgets in
228the "Preferences" dialog of a GUI, or command-line options---the more options
229you implement, the more flexible your program is, and the more complicated its
230implementation becomes. Too much flexibility has drawbacks as well, of course;
231too many options can overwhelm users and make your code much harder to maintain.
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234.. _optparse-tutorial:
235
236Tutorial
237--------
238
239While :mod:`optparse` is quite flexible and powerful, it's also straightforward
240to use in most cases. This section covers the code patterns that are common to
241any :mod:`optparse`\ -based program.
242
243First, you need to import the OptionParser class; then, early in the main
244program, create an OptionParser instance::
245
246 from optparse import OptionParser
247 [...]
248 parser = OptionParser()
249
250Then you can start defining options. The basic syntax is::
251
252 parser.add_option(opt_str, ...,
253 attr=value, ...)
254
Éric Araujo3efdf062010-12-16 03:16:29 +0000255Each option has one or more option strings, such as ``-f`` or ``--file``,
Georg Brandl116aa622007-08-15 14:28:22 +0000256and several option attributes that tell :mod:`optparse` what to expect and what
257to do when it encounters that option on the command line.
258
259Typically, each option will have one short option string and one long option
260string, e.g.::
261
262 parser.add_option("-f", "--file", ...)
263
264You're free to define as many short option strings and as many long option
265strings as you like (including zero), as long as there is at least one option
266string overall.
267
268The option strings passed to :meth:`add_option` are effectively labels for the
269option defined by that call. For brevity, we will frequently refer to
270*encountering an option* on the command line; in reality, :mod:`optparse`
271encounters *option strings* and looks up options from them.
272
273Once all of your options are defined, instruct :mod:`optparse` to parse your
274program's command line::
275
276 (options, args) = parser.parse_args()
277
278(If you like, you can pass a custom argument list to :meth:`parse_args`, but
279that's rarely necessary: by default it uses ``sys.argv[1:]``.)
280
281:meth:`parse_args` returns two values:
282
283* ``options``, an object containing values for all of your options---e.g. if
Éric Araujo3efdf062010-12-16 03:16:29 +0000284 ``--file`` takes a single string argument, then ``options.file`` will be the
Georg Brandl116aa622007-08-15 14:28:22 +0000285 filename supplied by the user, or ``None`` if the user did not supply that
286 option
287
288* ``args``, the list of positional arguments leftover after parsing options
289
290This tutorial section only covers the four most important option attributes:
Georg Brandl6ba000c2009-09-17 22:17:38 +0000291:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
292(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
293most fundamental.
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295
296.. _optparse-understanding-option-actions:
297
298Understanding option actions
299^^^^^^^^^^^^^^^^^^^^^^^^^^^^
300
301Actions tell :mod:`optparse` what to do when it encounters an option on the
302command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
303adding new actions is an advanced topic covered in section
Georg Brandl6ba000c2009-09-17 22:17:38 +0000304:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
305a value in some variable---for example, take a string from the command line and
306store it in an attribute of ``options``.
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308If you don't specify an option action, :mod:`optparse` defaults to ``store``.
309
310
311.. _optparse-store-action:
312
313The store action
314^^^^^^^^^^^^^^^^
315
316The most common option action is ``store``, which tells :mod:`optparse` to take
317the next argument (or the remainder of the current argument), ensure that it is
318of the correct type, and store it to your chosen destination.
319
320For example::
321
322 parser.add_option("-f", "--file",
323 action="store", type="string", dest="filename")
324
325Now let's make up a fake command line and ask :mod:`optparse` to parse it::
326
327 args = ["-f", "foo.txt"]
328 (options, args) = parser.parse_args(args)
329
Éric Araujo3efdf062010-12-16 03:16:29 +0000330When :mod:`optparse` sees the option string ``-f``, it consumes the next
331argument, ``foo.txt``, and stores it in ``options.filename``. So, after this
Georg Brandl116aa622007-08-15 14:28:22 +0000332call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
333
334Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
335Here's an option that expects an integer argument::
336
337 parser.add_option("-n", type="int", dest="num")
338
339Note that this option has no long option string, which is perfectly acceptable.
340Also, there's no explicit action, since the default is ``store``.
341
342Let's parse another fake command-line. This time, we'll jam the option argument
Éric Araujo3efdf062010-12-16 03:16:29 +0000343right up against the option: since ``-n42`` (one argument) is equivalent to
344``-n 42`` (two arguments), the code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346 (options, args) = parser.parse_args(["-n42"])
Georg Brandl6911e3c2007-09-04 07:15:32 +0000347 print(options.num)
Georg Brandl116aa622007-08-15 14:28:22 +0000348
Éric Araujo3efdf062010-12-16 03:16:29 +0000349will print ``42``.
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
352the fact that the default action is ``store``, that means our first example can
353be a lot shorter::
354
355 parser.add_option("-f", "--file", dest="filename")
356
357If you don't supply a destination, :mod:`optparse` figures out a sensible
358default from the option strings: if the first long option string is
Éric Araujo3efdf062010-12-16 03:16:29 +0000359``--foo-bar``, then the default destination is ``foo_bar``. If there are no
Georg Brandl116aa622007-08-15 14:28:22 +0000360long option strings, :mod:`optparse` looks at the first short option string: the
Éric Araujo3efdf062010-12-16 03:16:29 +0000361default destination for ``-f`` is ``f``.
Georg Brandl116aa622007-08-15 14:28:22 +0000362
Georg Brandl5c106642007-11-29 17:41:05 +0000363:mod:`optparse` also includes the built-in ``complex`` type. Adding
Georg Brandl116aa622007-08-15 14:28:22 +0000364types is covered in section :ref:`optparse-extending-optparse`.
365
366
367.. _optparse-handling-boolean-options:
368
369Handling boolean (flag) options
370^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
371
372Flag options---set a variable to true or false when a particular option is seen
373---are quite common. :mod:`optparse` supports them with two separate actions,
374``store_true`` and ``store_false``. For example, you might have a ``verbose``
Éric Araujo3efdf062010-12-16 03:16:29 +0000375flag that is turned on with ``-v`` and off with ``-q``::
Georg Brandl116aa622007-08-15 14:28:22 +0000376
377 parser.add_option("-v", action="store_true", dest="verbose")
378 parser.add_option("-q", action="store_false", dest="verbose")
379
380Here we have two different options with the same destination, which is perfectly
381OK. (It just means you have to be a bit careful when setting default values---
382see below.)
383
Éric Araujo3efdf062010-12-16 03:16:29 +0000384When :mod:`optparse` encounters ``-v`` on the command line, it sets
385``options.verbose`` to ``True``; when it encounters ``-q``,
Georg Brandl116aa622007-08-15 14:28:22 +0000386``options.verbose`` is set to ``False``.
387
388
389.. _optparse-other-actions:
390
391Other actions
392^^^^^^^^^^^^^
393
394Some other actions supported by :mod:`optparse` are:
395
Georg Brandl6ba000c2009-09-17 22:17:38 +0000396``"store_const"``
Georg Brandl116aa622007-08-15 14:28:22 +0000397 store a constant value
398
Georg Brandl6ba000c2009-09-17 22:17:38 +0000399``"append"``
Georg Brandl116aa622007-08-15 14:28:22 +0000400 append this option's argument to a list
401
Georg Brandl6ba000c2009-09-17 22:17:38 +0000402``"count"``
Georg Brandl116aa622007-08-15 14:28:22 +0000403 increment a counter by one
404
Georg Brandl6ba000c2009-09-17 22:17:38 +0000405``"callback"``
Georg Brandl116aa622007-08-15 14:28:22 +0000406 call a specified function
407
408These are covered in section :ref:`optparse-reference-guide`, Reference Guide
409and section :ref:`optparse-option-callbacks`.
410
411
412.. _optparse-default-values:
413
414Default values
415^^^^^^^^^^^^^^
416
417All of the above examples involve setting some variable (the "destination") when
418certain command-line options are seen. What happens if those options are never
419seen? Since we didn't supply any defaults, they are all set to ``None``. This
420is usually fine, but sometimes you want more control. :mod:`optparse` lets you
421supply a default value for each destination, which is assigned before the
422command line is parsed.
423
424First, consider the verbose/quiet example. If we want :mod:`optparse` to set
Éric Araujo3efdf062010-12-16 03:16:29 +0000425``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
Georg Brandl116aa622007-08-15 14:28:22 +0000426
427 parser.add_option("-v", action="store_true", dest="verbose", default=True)
428 parser.add_option("-q", action="store_false", dest="verbose")
429
430Since default values apply to the *destination* rather than to any particular
431option, and these two options happen to have the same destination, this is
432exactly equivalent::
433
434 parser.add_option("-v", action="store_true", dest="verbose")
435 parser.add_option("-q", action="store_false", dest="verbose", default=True)
436
437Consider this::
438
439 parser.add_option("-v", action="store_true", dest="verbose", default=False)
440 parser.add_option("-q", action="store_false", dest="verbose", default=True)
441
442Again, the default value for ``verbose`` will be ``True``: the last default
443value supplied for any particular destination is the one that counts.
444
445A clearer way to specify default values is the :meth:`set_defaults` method of
446OptionParser, which you can call at any time before calling :meth:`parse_args`::
447
448 parser.set_defaults(verbose=True)
449 parser.add_option(...)
450 (options, args) = parser.parse_args()
451
452As before, the last value specified for a given option destination is the one
453that counts. For clarity, try to use one method or the other of setting default
454values, not both.
455
456
457.. _optparse-generating-help:
458
459Generating help
460^^^^^^^^^^^^^^^
461
462:mod:`optparse`'s ability to generate help and usage text automatically is
463useful for creating user-friendly command-line interfaces. All you have to do
Georg Brandl6ba000c2009-09-17 22:17:38 +0000464is supply a :attr:`~Option.help` value for each option, and optionally a short
465usage message for your whole program. Here's an OptionParser populated with
Georg Brandl116aa622007-08-15 14:28:22 +0000466user-friendly (documented) options::
467
468 usage = "usage: %prog [options] arg1 arg2"
469 parser = OptionParser(usage=usage)
470 parser.add_option("-v", "--verbose",
471 action="store_true", dest="verbose", default=True,
472 help="make lots of noise [default]")
473 parser.add_option("-q", "--quiet",
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000474 action="store_false", dest="verbose",
Georg Brandl116aa622007-08-15 14:28:22 +0000475 help="be vewwy quiet (I'm hunting wabbits)")
476 parser.add_option("-f", "--filename",
Georg Brandlb044b2a2009-09-16 16:05:59 +0000477 metavar="FILE", help="write output to FILE")
Georg Brandl116aa622007-08-15 14:28:22 +0000478 parser.add_option("-m", "--mode",
479 default="intermediate",
480 help="interaction mode: novice, intermediate, "
481 "or expert [default: %default]")
482
Éric Araujo3efdf062010-12-16 03:16:29 +0000483If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
Georg Brandl116aa622007-08-15 14:28:22 +0000484command-line, or if you just call :meth:`parser.print_help`, it prints the
Ezio Melottide2cef52010-01-03 09:08:34 +0000485following to standard output:
486
487.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000488
Georg Brandl27743102011-02-25 10:18:11 +0000489 Usage: <yourscript> [options] arg1 arg2
Georg Brandl116aa622007-08-15 14:28:22 +0000490
Georg Brandl27743102011-02-25 10:18:11 +0000491 Options:
Georg Brandl116aa622007-08-15 14:28:22 +0000492 -h, --help show this help message and exit
493 -v, --verbose make lots of noise [default]
494 -q, --quiet be vewwy quiet (I'm hunting wabbits)
495 -f FILE, --filename=FILE
496 write output to FILE
497 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
498 expert [default: intermediate]
499
500(If the help output is triggered by a help option, :mod:`optparse` exits after
501printing the help text.)
502
503There's a lot going on here to help :mod:`optparse` generate the best possible
504help message:
505
506* the script defines its own usage message::
507
508 usage = "usage: %prog [options] arg1 arg2"
509
Éric Araujo3efdf062010-12-16 03:16:29 +0000510 :mod:`optparse` expands ``%prog`` in the usage string to the name of the
Georg Brandl6ba000c2009-09-17 22:17:38 +0000511 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
512 is then printed before the detailed option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandl27743102011-02-25 10:18:11 +0000515 default: ``"Usage: %prog [options]"``, which is fine if your script doesn't
Georg Brandl6ba000c2009-09-17 22:17:38 +0000516 take any positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000517
518* every option defines a help string, and doesn't worry about line-wrapping---
519 :mod:`optparse` takes care of wrapping lines and making the help output look
520 good.
521
522* options that take a value indicate this fact in their automatically-generated
523 help message, e.g. for the "mode" option::
524
525 -m MODE, --mode=MODE
526
527 Here, "MODE" is called the meta-variable: it stands for the argument that the
Éric Araujo3efdf062010-12-16 03:16:29 +0000528 user is expected to supply to ``-m``/``--mode``. By default,
Georg Brandl116aa622007-08-15 14:28:22 +0000529 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandl6ba000c2009-09-17 22:17:38 +0000530 that for the meta-variable. Sometimes, that's not what you want---for
Éric Araujo3efdf062010-12-16 03:16:29 +0000531 example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
Georg Brandl6ba000c2009-09-17 22:17:38 +0000532 resulting in this automatically-generated option description::
Georg Brandl116aa622007-08-15 14:28:22 +0000533
534 -f FILE, --filename=FILE
535
Georg Brandl6ba000c2009-09-17 22:17:38 +0000536 This is important for more than just saving space, though: the manually
Éric Araujo3efdf062010-12-16 03:16:29 +0000537 written help text uses the meta-variable ``FILE`` to clue the user in that
538 there's a connection between the semi-formal syntax ``-f FILE`` and the informal
Georg Brandl6ba000c2009-09-17 22:17:38 +0000539 semantic description "write output to FILE". This is a simple but effective
540 way to make your help text a lot clearer and more useful for end users.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542* options that have a default value can include ``%default`` in the help
543 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
544 default value. If an option has no default value (or the default value is
545 ``None``), ``%default`` expands to ``none``.
546
Georg Brandl27743102011-02-25 10:18:11 +0000547Grouping Options
548++++++++++++++++
549
Georg Brandl6ba000c2009-09-17 22:17:38 +0000550When dealing with many options, it is convenient to group these options for
551better help output. An :class:`OptionParser` can contain several option groups,
552each of which can contain several options.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000553
Georg Brandl27743102011-02-25 10:18:11 +0000554An option group is obtained using the class :class:`OptionGroup`:
555
556.. class:: OptionGroup(parser, title, description=None)
557
558 where
559
560 * parser is the :class:`OptionParser` instance the group will be insterted in
561 to
562 * title is the group title
563 * description, optional, is a long description of the group
564
565:class:`OptionGroup` inherits from :class:`OptionContainer` (like
566:class:`OptionParser`) and so the :meth:`add_option` method can be used to add
567an option to the group.
568
569Once all the options are declared, using the :class:`OptionParser` method
570:meth:`add_option_group` the group is added to the previously defined parser.
571
572Continuing with the parser defined in the previous section, adding an
573:class:`OptionGroup` to a parser is easy::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000574
575 group = OptionGroup(parser, "Dangerous Options",
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000576 "Caution: use these options at your own risk. "
577 "It is believed that some of them bite.")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000578 group.add_option("-g", action="store_true", help="Group option.")
579 parser.add_option_group(group)
580
Ezio Melottide2cef52010-01-03 09:08:34 +0000581This would result in the following help output:
582
583.. code-block:: text
Christian Heimesfdab48e2008-01-20 09:06:41 +0000584
Georg Brandl27743102011-02-25 10:18:11 +0000585 Usage: <yourscript> [options] arg1 arg2
Christian Heimesfdab48e2008-01-20 09:06:41 +0000586
Georg Brandl27743102011-02-25 10:18:11 +0000587 Options:
588 -h, --help show this help message and exit
589 -v, --verbose make lots of noise [default]
590 -q, --quiet be vewwy quiet (I'm hunting wabbits)
591 -f FILE, --filename=FILE
592 write output to FILE
593 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
594 expert [default: intermediate]
Christian Heimesfdab48e2008-01-20 09:06:41 +0000595
Georg Brandl27743102011-02-25 10:18:11 +0000596 Dangerous Options:
597 Caution: use these options at your own risk. It is believed that some
598 of them bite.
599
600 -g Group option.
601
602A bit more complete example might invole using more than one group: still
603extendind the previous example::
604
605 group = OptionGroup(parser, "Dangerous Options",
606 "Caution: use these options at your own risk. "
607 "It is believed that some of them bite.")
608 group.add_option("-g", action="store_true", help="Group option.")
609 parser.add_option_group(group)
610
611 group = OptionGroup(parser, "Debug Options")
612 group.add_option("-d", "--debug", action="store_true",
613 help="Print debug information")
614 group.add_option("-s", "--sql", action="store_true",
615 help="Print all SQL statements executed")
616 group.add_option("-e", action="store_true", help="Print every action done")
617 parser.add_option_group(group)
618
619that results in the following output:
620
621.. code-block:: text
622
623 Usage: <yourscript> [options] arg1 arg2
624
625 Options:
626 -h, --help show this help message and exit
627 -v, --verbose make lots of noise [default]
628 -q, --quiet be vewwy quiet (I'm hunting wabbits)
629 -f FILE, --filename=FILE
630 write output to FILE
631 -m MODE, --mode=MODE interaction mode: novice, intermediate, or expert
632 [default: intermediate]
633
634 Dangerous Options:
635 Caution: use these options at your own risk. It is believed that some
636 of them bite.
637
638 -g Group option.
639
640 Debug Options:
641 -d, --debug Print debug information
642 -s, --sql Print all SQL statements executed
643 -e Print every action done
644
645Another interesting method, in particular when working programmatically with
646option groups is:
647
648.. method:: OptionParser.get_option_group(opt_str)
649
650 Return, if defined, the :class:`OptionGroup` that has the title or the long
651 description equals to *opt_str*
Georg Brandl116aa622007-08-15 14:28:22 +0000652
653.. _optparse-printing-version-string:
654
655Printing a version string
656^^^^^^^^^^^^^^^^^^^^^^^^^
657
658Similar to the brief usage string, :mod:`optparse` can also print a version
659string for your program. You have to supply the string as the ``version``
660argument to OptionParser::
661
662 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
663
Éric Araujo3efdf062010-12-16 03:16:29 +0000664``%prog`` is expanded just like it is in ``usage``. Apart from that,
Georg Brandl116aa622007-08-15 14:28:22 +0000665``version`` can contain anything you like. When you supply it, :mod:`optparse`
Éric Araujo3efdf062010-12-16 03:16:29 +0000666automatically adds a ``--version`` option to your parser. If it encounters
Georg Brandl116aa622007-08-15 14:28:22 +0000667this option on the command line, it expands your ``version`` string (by
Éric Araujo3efdf062010-12-16 03:16:29 +0000668replacing ``%prog``), prints it to stdout, and exits.
Georg Brandl116aa622007-08-15 14:28:22 +0000669
670For example, if your script is called ``/usr/bin/foo``::
671
672 $ /usr/bin/foo --version
673 foo 1.0
674
Ezio Melotti6ea2a3d2010-01-04 21:54:31 +0000675The following two methods can be used to print and get the ``version`` string:
676
677.. method:: OptionParser.print_version(file=None)
678
679 Print the version message for the current program (``self.version``) to
680 *file* (default stdout). As with :meth:`print_usage`, any occurrence
Éric Araujo3efdf062010-12-16 03:16:29 +0000681 of ``%prog`` in ``self.version`` is replaced with the name of the current
Ezio Melotti6ea2a3d2010-01-04 21:54:31 +0000682 program. Does nothing if ``self.version`` is empty or undefined.
683
684.. method:: OptionParser.get_version()
685
686 Same as :meth:`print_version` but returns the version string instead of
687 printing it.
688
Georg Brandl116aa622007-08-15 14:28:22 +0000689
690.. _optparse-how-optparse-handles-errors:
691
692How :mod:`optparse` handles errors
693^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
694
695There are two broad classes of errors that :mod:`optparse` has to worry about:
696programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandl6ba000c2009-09-17 22:17:38 +0000697calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
698option attributes, missing option attributes, etc. These are dealt with in the
699usual way: raise an exception (either :exc:`optparse.OptionError` or
700:exc:`TypeError`) and let the program crash.
Georg Brandl116aa622007-08-15 14:28:22 +0000701
702Handling user errors is much more important, since they are guaranteed to happen
703no matter how stable your code is. :mod:`optparse` can automatically detect
Éric Araujo3efdf062010-12-16 03:16:29 +0000704some user errors, such as bad option arguments (passing ``-n 4x`` where
705``-n`` takes an integer argument), missing arguments (``-n`` at the end
706of the command line, where ``-n`` takes an argument of any type). Also,
Georg Brandl6ba000c2009-09-17 22:17:38 +0000707you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl116aa622007-08-15 14:28:22 +0000708condition::
709
710 (options, args) = parser.parse_args()
711 [...]
712 if options.a and options.b:
713 parser.error("options -a and -b are mutually exclusive")
714
715In either case, :mod:`optparse` handles the error the same way: it prints the
716program's usage message and an error message to standard error and exits with
717error status 2.
718
Éric Araujo3efdf062010-12-16 03:16:29 +0000719Consider the first example above, where the user passes ``4x`` to an option
Georg Brandl116aa622007-08-15 14:28:22 +0000720that takes an integer::
721
722 $ /usr/bin/foo -n 4x
Georg Brandl27743102011-02-25 10:18:11 +0000723 Usage: foo [options]
Georg Brandl116aa622007-08-15 14:28:22 +0000724
725 foo: error: option -n: invalid integer value: '4x'
726
727Or, where the user fails to pass a value at all::
728
729 $ /usr/bin/foo -n
Georg Brandl27743102011-02-25 10:18:11 +0000730 Usage: foo [options]
Georg Brandl116aa622007-08-15 14:28:22 +0000731
732 foo: error: -n option requires an argument
733
734:mod:`optparse`\ -generated error messages take care always to mention the
735option involved in the error; be sure to do the same when calling
Georg Brandl6ba000c2009-09-17 22:17:38 +0000736:func:`OptionParser.error` from your application code.
Georg Brandl116aa622007-08-15 14:28:22 +0000737
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000738If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Georg Brandlbcc484e2009-08-13 11:51:54 +0000739you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
740and/or :meth:`~OptionParser.error` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000741
742
743.. _optparse-putting-it-all-together:
744
745Putting it all together
746^^^^^^^^^^^^^^^^^^^^^^^
747
748Here's what :mod:`optparse`\ -based scripts usually look like::
749
750 from optparse import OptionParser
751 [...]
752 def main():
753 usage = "usage: %prog [options] arg"
754 parser = OptionParser(usage)
755 parser.add_option("-f", "--file", dest="filename",
756 help="read data from FILENAME")
757 parser.add_option("-v", "--verbose",
758 action="store_true", dest="verbose")
759 parser.add_option("-q", "--quiet",
760 action="store_false", dest="verbose")
761 [...]
762 (options, args) = parser.parse_args()
763 if len(args) != 1:
764 parser.error("incorrect number of arguments")
765 if options.verbose:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000766 print("reading %s..." % options.filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000767 [...]
768
769 if __name__ == "__main__":
770 main()
771
Georg Brandl116aa622007-08-15 14:28:22 +0000772
773.. _optparse-reference-guide:
774
775Reference Guide
776---------------
777
778
779.. _optparse-creating-parser:
780
781Creating the parser
782^^^^^^^^^^^^^^^^^^^
783
Georg Brandl6ba000c2009-09-17 22:17:38 +0000784The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Georg Brandl6ba000c2009-09-17 22:17:38 +0000786.. class:: OptionParser(...)
Georg Brandl116aa622007-08-15 14:28:22 +0000787
Georg Brandl6ba000c2009-09-17 22:17:38 +0000788 The OptionParser constructor has no required arguments, but a number of
789 optional keyword arguments. You should always pass them as keyword
790 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl116aa622007-08-15 14:28:22 +0000791
792 ``usage`` (default: ``"%prog [options]"``)
Georg Brandl6ba000c2009-09-17 22:17:38 +0000793 The usage summary to print when your program is run incorrectly or with a
794 help option. When :mod:`optparse` prints the usage string, it expands
795 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
796 passed that keyword argument). To suppress a usage message, pass the
797 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl116aa622007-08-15 14:28:22 +0000798
799 ``option_list`` (default: ``[]``)
800 A list of Option objects to populate the parser with. The options in
Georg Brandl6ba000c2009-09-17 22:17:38 +0000801 ``option_list`` are added after any options in ``standard_option_list`` (a
802 class attribute that may be set by OptionParser subclasses), but before
803 any version or help options. Deprecated; use :meth:`add_option` after
804 creating the parser instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000805
806 ``option_class`` (default: optparse.Option)
807 Class to use when adding options to the parser in :meth:`add_option`.
808
809 ``version`` (default: ``None``)
Georg Brandl6ba000c2009-09-17 22:17:38 +0000810 A version string to print when the user supplies a version option. If you
811 supply a true value for ``version``, :mod:`optparse` automatically adds a
Éric Araujo3efdf062010-12-16 03:16:29 +0000812 version option with the single option string ``--version``. The
813 substring ``%prog`` is expanded the same as for ``usage``.
Georg Brandl116aa622007-08-15 14:28:22 +0000814
815 ``conflict_handler`` (default: ``"error"``)
Georg Brandl6ba000c2009-09-17 22:17:38 +0000816 Specifies what to do when options with conflicting option strings are
817 added to the parser; see section
818 :ref:`optparse-conflicts-between-options`.
Georg Brandl116aa622007-08-15 14:28:22 +0000819
820 ``description`` (default: ``None``)
Georg Brandl6ba000c2009-09-17 22:17:38 +0000821 A paragraph of text giving a brief overview of your program.
822 :mod:`optparse` reformats this paragraph to fit the current terminal width
823 and prints it when the user requests help (after ``usage``, but before the
824 list of options).
Georg Brandl116aa622007-08-15 14:28:22 +0000825
Georg Brandl6ba000c2009-09-17 22:17:38 +0000826 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
827 An instance of optparse.HelpFormatter that will be used for printing help
828 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl116aa622007-08-15 14:28:22 +0000829 IndentedHelpFormatter and TitledHelpFormatter.
830
831 ``add_help_option`` (default: ``True``)
Éric Araujo3efdf062010-12-16 03:16:29 +0000832 If true, :mod:`optparse` will add a help option (with option strings ``-h``
833 and ``--help``) to the parser.
Georg Brandl116aa622007-08-15 14:28:22 +0000834
835 ``prog``
Éric Araujo3efdf062010-12-16 03:16:29 +0000836 The string to use when expanding ``%prog`` in ``usage`` and ``version``
Georg Brandl116aa622007-08-15 14:28:22 +0000837 instead of ``os.path.basename(sys.argv[0])``.
838
Senthil Kumaran8935ed92010-03-29 19:25:37 +0000839 ``epilog`` (default: ``None``)
840 A paragraph of help text to print after the option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000841
842.. _optparse-populating-parser:
843
844Populating the parser
845^^^^^^^^^^^^^^^^^^^^^
846
847There are several ways to populate the parser with options. The preferred way
Georg Brandl6ba000c2009-09-17 22:17:38 +0000848is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl116aa622007-08-15 14:28:22 +0000849:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
850
851* pass it an Option instance (as returned by :func:`make_option`)
852
853* pass it any combination of positional and keyword arguments that are
Georg Brandl6ba000c2009-09-17 22:17:38 +0000854 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
855 will create the Option instance for you
Georg Brandl116aa622007-08-15 14:28:22 +0000856
857The other alternative is to pass a list of pre-constructed Option instances to
858the OptionParser constructor, as in::
859
860 option_list = [
861 make_option("-f", "--filename",
862 action="store", type="string", dest="filename"),
863 make_option("-q", "--quiet",
864 action="store_false", dest="verbose"),
865 ]
866 parser = OptionParser(option_list=option_list)
867
868(:func:`make_option` is a factory function for creating Option instances;
869currently it is an alias for the Option constructor. A future version of
870:mod:`optparse` may split Option into several classes, and :func:`make_option`
871will pick the right class to instantiate. Do not instantiate Option directly.)
872
873
874.. _optparse-defining-options:
875
876Defining options
877^^^^^^^^^^^^^^^^
878
879Each Option instance represents a set of synonymous command-line option strings,
Éric Araujo3efdf062010-12-16 03:16:29 +0000880e.g. ``-f`` and ``--file``. You can specify any number of short or
Georg Brandl116aa622007-08-15 14:28:22 +0000881long option strings, but you must specify at least one overall option string.
882
Georg Brandl6ba000c2009-09-17 22:17:38 +0000883The canonical way to create an :class:`Option` instance is with the
884:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl116aa622007-08-15 14:28:22 +0000885
Georg Brandl6ba000c2009-09-17 22:17:38 +0000886.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000887
Georg Brandl6ba000c2009-09-17 22:17:38 +0000888 To define an option with only a short option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000889
Georg Brandl6ba000c2009-09-17 22:17:38 +0000890 parser.add_option("-f", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000891
Georg Brandl6ba000c2009-09-17 22:17:38 +0000892 And to define an option with only a long option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000893
Georg Brandl6ba000c2009-09-17 22:17:38 +0000894 parser.add_option("--foo", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000895
Georg Brandl6ba000c2009-09-17 22:17:38 +0000896 The keyword arguments define attributes of the new Option object. The most
897 important option attribute is :attr:`~Option.action`, and it largely
898 determines which other attributes are relevant or required. If you pass
899 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
900 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl116aa622007-08-15 14:28:22 +0000901
Georg Brandl6ba000c2009-09-17 22:17:38 +0000902 An option's *action* determines what :mod:`optparse` does when it encounters
903 this option on the command-line. The standard option actions hard-coded into
904 :mod:`optparse` are:
Georg Brandl116aa622007-08-15 14:28:22 +0000905
Georg Brandl6ba000c2009-09-17 22:17:38 +0000906 ``"store"``
907 store this option's argument (default)
Georg Brandl116aa622007-08-15 14:28:22 +0000908
Georg Brandl6ba000c2009-09-17 22:17:38 +0000909 ``"store_const"``
910 store a constant value
Georg Brandl116aa622007-08-15 14:28:22 +0000911
Georg Brandl6ba000c2009-09-17 22:17:38 +0000912 ``"store_true"``
913 store a true value
Georg Brandl116aa622007-08-15 14:28:22 +0000914
Georg Brandl6ba000c2009-09-17 22:17:38 +0000915 ``"store_false"``
916 store a false value
Georg Brandl116aa622007-08-15 14:28:22 +0000917
Georg Brandl6ba000c2009-09-17 22:17:38 +0000918 ``"append"``
919 append this option's argument to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000920
Georg Brandl6ba000c2009-09-17 22:17:38 +0000921 ``"append_const"``
922 append a constant value to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000923
Georg Brandl6ba000c2009-09-17 22:17:38 +0000924 ``"count"``
925 increment a counter by one
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Georg Brandl6ba000c2009-09-17 22:17:38 +0000927 ``"callback"``
928 call a specified function
Georg Brandl116aa622007-08-15 14:28:22 +0000929
Georg Brandl6ba000c2009-09-17 22:17:38 +0000930 ``"help"``
931 print a usage message including all options and the documentation for them
Georg Brandl116aa622007-08-15 14:28:22 +0000932
Georg Brandl6ba000c2009-09-17 22:17:38 +0000933 (If you don't supply an action, the default is ``"store"``. For this action,
934 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
935 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000936
937As you can see, most actions involve storing or updating a value somewhere.
938:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandl6ba000c2009-09-17 22:17:38 +0000939``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl116aa622007-08-15 14:28:22 +0000940arguments (and various other values) are stored as attributes of this object,
Georg Brandl6ba000c2009-09-17 22:17:38 +0000941according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000942
Georg Brandl6ba000c2009-09-17 22:17:38 +0000943For example, when you call ::
Georg Brandl116aa622007-08-15 14:28:22 +0000944
945 parser.parse_args()
946
947one of the first things :mod:`optparse` does is create the ``options`` object::
948
949 options = Values()
950
Georg Brandl6ba000c2009-09-17 22:17:38 +0000951If one of the options in this parser is defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +0000952
953 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
954
955and the command-line being parsed includes any of the following::
956
957 -ffoo
958 -f foo
959 --file=foo
960 --file foo
961
Georg Brandl6ba000c2009-09-17 22:17:38 +0000962then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964 options.filename = "foo"
965
Georg Brandl6ba000c2009-09-17 22:17:38 +0000966The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
967as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
968one that makes sense for *all* options.
969
970
971.. _optparse-option-attributes:
972
973Option attributes
974^^^^^^^^^^^^^^^^^
975
976The following option attributes may be passed as keyword arguments to
977:meth:`OptionParser.add_option`. If you pass an option attribute that is not
978relevant to a particular option, or fail to pass a required option attribute,
979:mod:`optparse` raises :exc:`OptionError`.
980
981.. attribute:: Option.action
982
983 (default: ``"store"``)
984
985 Determines :mod:`optparse`'s behaviour when this option is seen on the
986 command line; the available options are documented :ref:`here
987 <optparse-standard-option-actions>`.
988
989.. attribute:: Option.type
990
991 (default: ``"string"``)
992
993 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
994 the available option types are documented :ref:`here
995 <optparse-standard-option-types>`.
996
997.. attribute:: Option.dest
998
999 (default: derived from option strings)
1000
1001 If the option's action implies writing or modifying a value somewhere, this
1002 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
1003 attribute of the ``options`` object that :mod:`optparse` builds as it parses
1004 the command line.
1005
1006.. attribute:: Option.default
1007
1008 The value to use for this option's destination if the option is not seen on
1009 the command line. See also :meth:`OptionParser.set_defaults`.
1010
1011.. attribute:: Option.nargs
1012
1013 (default: 1)
1014
1015 How many arguments of type :attr:`~Option.type` should be consumed when this
1016 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
1017 :attr:`~Option.dest`.
1018
1019.. attribute:: Option.const
1020
1021 For actions that store a constant value, the constant value to store.
1022
1023.. attribute:: Option.choices
1024
1025 For options of type ``"choice"``, the list of strings the user may choose
1026 from.
1027
1028.. attribute:: Option.callback
1029
1030 For options with action ``"callback"``, the callable to call when this option
1031 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1032 arguments passed to the callable.
1033
1034.. attribute:: Option.callback_args
1035 Option.callback_kwargs
1036
1037 Additional positional and keyword arguments to pass to ``callback`` after the
1038 four standard callback arguments.
1039
1040.. attribute:: Option.help
1041
1042 Help text to print for this option when listing all available options after
Éric Araujo3efdf062010-12-16 03:16:29 +00001043 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
Georg Brandl6ba000c2009-09-17 22:17:38 +00001044 no help text is supplied, the option will be listed without help text. To
1045 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
1046
1047.. attribute:: Option.metavar
1048
1049 (default: derived from option strings)
1050
1051 Stand-in for the option argument(s) to use when printing help text. See
1052 section :ref:`optparse-tutorial` for an example.
Georg Brandl116aa622007-08-15 14:28:22 +00001053
1054
1055.. _optparse-standard-option-actions:
1056
1057Standard option actions
1058^^^^^^^^^^^^^^^^^^^^^^^
1059
1060The various option actions all have slightly different requirements and effects.
1061Most actions have several relevant option attributes which you may specify to
1062guide :mod:`optparse`'s behaviour; a few have required attributes, which you
1063must specify for any option using that action.
1064
Georg Brandl6ba000c2009-09-17 22:17:38 +00001065* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1066 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001067
1068 The option must be followed by an argument, which is converted to a value
Georg Brandl6ba000c2009-09-17 22:17:38 +00001069 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1070 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1071 command line; all will be converted according to :attr:`~Option.type` and
1072 stored to :attr:`~Option.dest` as a tuple. See the
1073 :ref:`optparse-standard-option-types` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001074
Georg Brandl6ba000c2009-09-17 22:17:38 +00001075 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1076 defaults to ``"choice"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001077
Georg Brandl6ba000c2009-09-17 22:17:38 +00001078 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001079
Georg Brandl6ba000c2009-09-17 22:17:38 +00001080 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
Éric Araujo3efdf062010-12-16 03:16:29 +00001081 from the first long option string (e.g., ``--foo-bar`` implies
Georg Brandl6ba000c2009-09-17 22:17:38 +00001082 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
Éric Araujo3efdf062010-12-16 03:16:29 +00001083 destination from the first short option string (e.g., ``-f`` implies ``f``).
Georg Brandl116aa622007-08-15 14:28:22 +00001084
1085 Example::
1086
1087 parser.add_option("-f")
1088 parser.add_option("-p", type="float", nargs=3, dest="point")
1089
Georg Brandl6ba000c2009-09-17 22:17:38 +00001090 As it parses the command line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001091
1092 -f foo.txt -p 1 -3.5 4 -fbar.txt
1093
Georg Brandl6ba000c2009-09-17 22:17:38 +00001094 :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +00001095
1096 options.f = "foo.txt"
1097 options.point = (1.0, -3.5, 4.0)
1098 options.f = "bar.txt"
1099
Georg Brandl6ba000c2009-09-17 22:17:38 +00001100* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1101 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001102
Georg Brandl6ba000c2009-09-17 22:17:38 +00001103 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001104
1105 Example::
1106
1107 parser.add_option("-q", "--quiet",
1108 action="store_const", const=0, dest="verbose")
1109 parser.add_option("-v", "--verbose",
1110 action="store_const", const=1, dest="verbose")
1111 parser.add_option("--noisy",
1112 action="store_const", const=2, dest="verbose")
1113
Éric Araujo3efdf062010-12-16 03:16:29 +00001114 If ``--noisy`` is seen, :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +00001115
1116 options.verbose = 2
1117
Georg Brandl6ba000c2009-09-17 22:17:38 +00001118* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001119
Georg Brandl6ba000c2009-09-17 22:17:38 +00001120 A special case of ``"store_const"`` that stores a true value to
1121 :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001122
Georg Brandl6ba000c2009-09-17 22:17:38 +00001123* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001124
Georg Brandl6ba000c2009-09-17 22:17:38 +00001125 Like ``"store_true"``, but stores a false value.
Georg Brandl116aa622007-08-15 14:28:22 +00001126
1127 Example::
1128
1129 parser.add_option("--clobber", action="store_true", dest="clobber")
1130 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1131
Georg Brandl6ba000c2009-09-17 22:17:38 +00001132* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1133 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001134
1135 The option must be followed by an argument, which is appended to the list in
Georg Brandl6ba000c2009-09-17 22:17:38 +00001136 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1137 supplied, an empty list is automatically created when :mod:`optparse` first
1138 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1139 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1140 is appended to :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001141
Georg Brandl6ba000c2009-09-17 22:17:38 +00001142 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1143 for the ``"store"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001144
1145 Example::
1146
1147 parser.add_option("-t", "--tracks", action="append", type="int")
1148
Éric Araujo3efdf062010-12-16 03:16:29 +00001149 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
Georg Brandl116aa622007-08-15 14:28:22 +00001150 of::
1151
1152 options.tracks = []
1153 options.tracks.append(int("3"))
1154
Éric Araujo3efdf062010-12-16 03:16:29 +00001155 If, a little later on, ``--tracks=4`` is seen, it does::
Georg Brandl116aa622007-08-15 14:28:22 +00001156
1157 options.tracks.append(int("4"))
1158
Georg Brandl6ba000c2009-09-17 22:17:38 +00001159* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1160 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001161
Georg Brandl6ba000c2009-09-17 22:17:38 +00001162 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1163 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1164 ``None``, and an empty list is automatically created the first time the option
1165 is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +00001166
Georg Brandl6ba000c2009-09-17 22:17:38 +00001167* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001168
Georg Brandl6ba000c2009-09-17 22:17:38 +00001169 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1170 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1171 first time.
Georg Brandl116aa622007-08-15 14:28:22 +00001172
1173 Example::
1174
1175 parser.add_option("-v", action="count", dest="verbosity")
1176
Éric Araujo3efdf062010-12-16 03:16:29 +00001177 The first time ``-v`` is seen on the command line, :mod:`optparse` does the
Georg Brandl116aa622007-08-15 14:28:22 +00001178 equivalent of::
1179
1180 options.verbosity = 0
1181 options.verbosity += 1
1182
Éric Araujo3efdf062010-12-16 03:16:29 +00001183 Every subsequent occurrence of ``-v`` results in ::
Georg Brandl116aa622007-08-15 14:28:22 +00001184
1185 options.verbosity += 1
1186
Georg Brandl6ba000c2009-09-17 22:17:38 +00001187* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1188 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1189 :attr:`~Option.callback_kwargs`]
Georg Brandl116aa622007-08-15 14:28:22 +00001190
Georg Brandl6ba000c2009-09-17 22:17:38 +00001191 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001192
1193 func(option, opt_str, value, parser, *args, **kwargs)
1194
1195 See section :ref:`optparse-option-callbacks` for more detail.
1196
Georg Brandl6ba000c2009-09-17 22:17:38 +00001197* ``"help"``
Georg Brandl116aa622007-08-15 14:28:22 +00001198
Georg Brandl6ba000c2009-09-17 22:17:38 +00001199 Prints a complete help message for all the options in the current option
1200 parser. The help message is constructed from the ``usage`` string passed to
1201 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1202 option.
Georg Brandl116aa622007-08-15 14:28:22 +00001203
Georg Brandl6ba000c2009-09-17 22:17:38 +00001204 If no :attr:`~Option.help` string is supplied for an option, it will still be
1205 listed in the help message. To omit an option entirely, use the special value
1206 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl116aa622007-08-15 14:28:22 +00001207
Georg Brandl6ba000c2009-09-17 22:17:38 +00001208 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1209 OptionParsers, so you do not normally need to create one.
Georg Brandl116aa622007-08-15 14:28:22 +00001210
1211 Example::
1212
1213 from optparse import OptionParser, SUPPRESS_HELP
1214
Georg Brandlb044b2a2009-09-16 16:05:59 +00001215 # usually, a help option is added automatically, but that can
1216 # be suppressed using the add_help_option argument
1217 parser = OptionParser(add_help_option=False)
1218
1219 parser.add_option("-h", "--help", action="help")
Georg Brandl116aa622007-08-15 14:28:22 +00001220 parser.add_option("-v", action="store_true", dest="verbose",
1221 help="Be moderately verbose")
1222 parser.add_option("--file", dest="filename",
Georg Brandlb044b2a2009-09-16 16:05:59 +00001223 help="Input file to read data from")
Georg Brandl116aa622007-08-15 14:28:22 +00001224 parser.add_option("--secret", help=SUPPRESS_HELP)
1225
Éric Araujo3efdf062010-12-16 03:16:29 +00001226 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
Georg Brandl6ba000c2009-09-17 22:17:38 +00001227 it will print something like the following help message to stdout (assuming
Ezio Melottide2cef52010-01-03 09:08:34 +00001228 ``sys.argv[0]`` is ``"foo.py"``):
1229
1230 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +00001231
Georg Brandl27743102011-02-25 10:18:11 +00001232 Usage: foo.py [options]
Georg Brandl116aa622007-08-15 14:28:22 +00001233
Georg Brandl27743102011-02-25 10:18:11 +00001234 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001235 -h, --help Show this help message and exit
1236 -v Be moderately verbose
1237 --file=FILENAME Input file to read data from
1238
1239 After printing the help message, :mod:`optparse` terminates your process with
1240 ``sys.exit(0)``.
1241
Georg Brandl6ba000c2009-09-17 22:17:38 +00001242* ``"version"``
Georg Brandl116aa622007-08-15 14:28:22 +00001243
Georg Brandl6ba000c2009-09-17 22:17:38 +00001244 Prints the version number supplied to the OptionParser to stdout and exits.
1245 The version number is actually formatted and printed by the
1246 ``print_version()`` method of OptionParser. Generally only relevant if the
1247 ``version`` argument is supplied to the OptionParser constructor. As with
1248 :attr:`~Option.help` options, you will rarely create ``version`` options,
1249 since :mod:`optparse` automatically adds them when needed.
Georg Brandl116aa622007-08-15 14:28:22 +00001250
1251
1252.. _optparse-standard-option-types:
1253
1254Standard option types
1255^^^^^^^^^^^^^^^^^^^^^
1256
Georg Brandl6ba000c2009-09-17 22:17:38 +00001257:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1258``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1259option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +00001260
1261Arguments to string options are not checked or converted in any way: the text on
1262the command line is stored in the destination (or passed to the callback) as-is.
1263
Georg Brandl6ba000c2009-09-17 22:17:38 +00001264Integer arguments (type ``"int"``) are parsed as follows:
Georg Brandl116aa622007-08-15 14:28:22 +00001265
1266* if the number starts with ``0x``, it is parsed as a hexadecimal number
1267
1268* if the number starts with ``0``, it is parsed as an octal number
1269
Georg Brandl9afde1c2007-11-01 20:32:30 +00001270* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl116aa622007-08-15 14:28:22 +00001271
1272* otherwise, the number is parsed as a decimal number
1273
1274
Georg Brandl6ba000c2009-09-17 22:17:38 +00001275The conversion is done by calling :func:`int` with the appropriate base (2, 8,
127610, or 16). If this fails, so will :mod:`optparse`, although with a more useful
Georg Brandl5c106642007-11-29 17:41:05 +00001277error message.
Georg Brandl116aa622007-08-15 14:28:22 +00001278
Georg Brandl6ba000c2009-09-17 22:17:38 +00001279``"float"`` and ``"complex"`` option arguments are converted directly with
1280:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl116aa622007-08-15 14:28:22 +00001281
Georg Brandl6ba000c2009-09-17 22:17:38 +00001282``"choice"`` options are a subtype of ``"string"`` options. The
Georg Brandld098c3d2010-10-06 10:38:58 +00001283:attr:`~Option.choices` option attribute (a sequence of strings) defines the
Georg Brandl6ba000c2009-09-17 22:17:38 +00001284set of allowed option arguments. :func:`optparse.check_choice` compares
1285user-supplied option arguments against this master list and raises
1286:exc:`OptionValueError` if an invalid string is given.
Georg Brandl116aa622007-08-15 14:28:22 +00001287
1288
1289.. _optparse-parsing-arguments:
1290
1291Parsing arguments
1292^^^^^^^^^^^^^^^^^
1293
1294The whole point of creating and populating an OptionParser is to call its
1295:meth:`parse_args` method::
1296
1297 (options, args) = parser.parse_args(args=None, values=None)
1298
1299where the input parameters are
1300
1301``args``
1302 the list of arguments to process (default: ``sys.argv[1:]``)
1303
1304``values``
Georg Brandl44c58232010-08-01 19:04:55 +00001305 a :class:`optparse.Values` object to store option arguments in (default: a
1306 new instance of :class:`Values`) -- if you give an existing object, the
1307 option defaults will not be initialized on it
Georg Brandl116aa622007-08-15 14:28:22 +00001308
1309and the return values are
1310
1311``options``
Georg Brandl7baf6252009-09-01 08:13:16 +00001312 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl116aa622007-08-15 14:28:22 +00001313 instance created by :mod:`optparse`
1314
1315``args``
1316 the leftover positional arguments after all options have been processed
1317
1318The most common usage is to supply neither keyword argument. If you supply
Georg Brandl6ba000c2009-09-17 22:17:38 +00001319``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl116aa622007-08-15 14:28:22 +00001320for every option argument stored to an option destination) and returned by
1321:meth:`parse_args`.
1322
1323If :meth:`parse_args` encounters any errors in the argument list, it calls the
1324OptionParser's :meth:`error` method with an appropriate end-user error message.
1325This ultimately terminates your process with an exit status of 2 (the
1326traditional Unix exit status for command-line errors).
1327
1328
1329.. _optparse-querying-manipulating-option-parser:
1330
1331Querying and manipulating your option parser
1332^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1333
Georg Brandl6ba000c2009-09-17 22:17:38 +00001334The default behavior of the option parser can be customized slightly, and you
1335can also poke around your option parser and see what's there. OptionParser
1336provides several methods to help you out:
Georg Brandl116aa622007-08-15 14:28:22 +00001337
Georg Brandl6ba000c2009-09-17 22:17:38 +00001338.. method:: OptionParser.disable_interspersed_args()
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001339
Éric Araujo3efdf062010-12-16 03:16:29 +00001340 Set parsing to stop on the first non-option. For example, if ``-a`` and
1341 ``-b`` are both simple options that take no arguments, :mod:`optparse`
Georg Brandl6ba000c2009-09-17 22:17:38 +00001342 normally accepts this syntax::
Georg Brandl116aa622007-08-15 14:28:22 +00001343
Georg Brandl6ba000c2009-09-17 22:17:38 +00001344 prog -a arg1 -b arg2
1345
1346 and treats it as equivalent to ::
1347
1348 prog -a -b arg1 arg2
1349
1350 To disable this feature, call :meth:`disable_interspersed_args`. This
1351 restores traditional Unix syntax, where option parsing stops with the first
1352 non-option argument.
1353
1354 Use this if you have a command processor which runs another command which has
1355 options of its own and you want to make sure these options don't get
1356 confused. For example, each command might have a different set of options.
1357
1358.. method:: OptionParser.enable_interspersed_args()
1359
1360 Set parsing to not stop on the first non-option, allowing interspersing
1361 switches with command arguments. This is the default behavior.
1362
1363.. method:: OptionParser.get_option(opt_str)
1364
1365 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl116aa622007-08-15 14:28:22 +00001366 no options have that option string.
1367
Georg Brandl6ba000c2009-09-17 22:17:38 +00001368.. method:: OptionParser.has_option(opt_str)
1369
1370 Return true if the OptionParser has an option with option string *opt_str*
Éric Araujo3efdf062010-12-16 03:16:29 +00001371 (e.g., ``-q`` or ``--verbose``).
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001372
Georg Brandl6ba000c2009-09-17 22:17:38 +00001373.. method:: OptionParser.remove_option(opt_str)
1374
1375 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1376 option is removed. If that option provided any other option strings, all of
1377 those option strings become invalid. If *opt_str* does not occur in any
1378 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001379
1380
1381.. _optparse-conflicts-between-options:
1382
1383Conflicts between options
1384^^^^^^^^^^^^^^^^^^^^^^^^^
1385
1386If you're not careful, it's easy to define options with conflicting option
1387strings::
1388
1389 parser.add_option("-n", "--dry-run", ...)
1390 [...]
1391 parser.add_option("-n", "--noisy", ...)
1392
1393(This is particularly true if you've defined your own OptionParser subclass with
1394some standard options.)
1395
1396Every time you add an option, :mod:`optparse` checks for conflicts with existing
1397options. If it finds any, it invokes the current conflict-handling mechanism.
1398You can set the conflict-handling mechanism either in the constructor::
1399
1400 parser = OptionParser(..., conflict_handler=handler)
1401
1402or with a separate call::
1403
1404 parser.set_conflict_handler(handler)
1405
1406The available conflict handlers are:
1407
Georg Brandl6ba000c2009-09-17 22:17:38 +00001408 ``"error"`` (default)
1409 assume option conflicts are a programming error and raise
1410 :exc:`OptionConflictError`
Georg Brandl116aa622007-08-15 14:28:22 +00001411
Georg Brandl6ba000c2009-09-17 22:17:38 +00001412 ``"resolve"``
Georg Brandl116aa622007-08-15 14:28:22 +00001413 resolve option conflicts intelligently (see below)
1414
1415
Benjamin Petersone5384b02008-10-04 22:00:42 +00001416As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl116aa622007-08-15 14:28:22 +00001417intelligently and add conflicting options to it::
1418
1419 parser = OptionParser(conflict_handler="resolve")
1420 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1421 parser.add_option("-n", "--noisy", ..., help="be noisy")
1422
1423At this point, :mod:`optparse` detects that a previously-added option is already
Éric Araujo3efdf062010-12-16 03:16:29 +00001424using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1425it resolves the situation by removing ``-n`` from the earlier option's list of
1426option strings. Now ``--dry-run`` is the only way for the user to activate
Georg Brandl116aa622007-08-15 14:28:22 +00001427that option. If the user asks for help, the help message will reflect that::
1428
Georg Brandl27743102011-02-25 10:18:11 +00001429 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001430 --dry-run do no harm
1431 [...]
1432 -n, --noisy be noisy
1433
1434It's possible to whittle away the option strings for a previously-added option
1435until there are none left, and the user has no way of invoking that option from
1436the command-line. In that case, :mod:`optparse` removes that option completely,
1437so it doesn't show up in help text or anywhere else. Carrying on with our
1438existing OptionParser::
1439
1440 parser.add_option("--dry-run", ..., help="new dry-run option")
1441
Éric Araujo3efdf062010-12-16 03:16:29 +00001442At this point, the original ``-n``/``--dry-run`` option is no longer
Georg Brandl116aa622007-08-15 14:28:22 +00001443accessible, so :mod:`optparse` removes it, leaving this help text::
1444
Georg Brandl27743102011-02-25 10:18:11 +00001445 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001446 [...]
1447 -n, --noisy be noisy
1448 --dry-run new dry-run option
1449
1450
1451.. _optparse-cleanup:
1452
1453Cleanup
1454^^^^^^^
1455
1456OptionParser instances have several cyclic references. This should not be a
1457problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandl6ba000c2009-09-17 22:17:38 +00001458references explicitly by calling :meth:`~OptionParser.destroy` on your
1459OptionParser once you are done with it. This is particularly useful in
1460long-running applications where large object graphs are reachable from your
1461OptionParser.
Georg Brandl116aa622007-08-15 14:28:22 +00001462
1463
1464.. _optparse-other-methods:
1465
1466Other methods
1467^^^^^^^^^^^^^
1468
1469OptionParser supports several other public methods:
1470
Georg Brandl6ba000c2009-09-17 22:17:38 +00001471.. method:: OptionParser.set_usage(usage)
Georg Brandl116aa622007-08-15 14:28:22 +00001472
Georg Brandl6ba000c2009-09-17 22:17:38 +00001473 Set the usage string according to the rules described above for the ``usage``
1474 constructor keyword argument. Passing ``None`` sets the default usage
1475 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl116aa622007-08-15 14:28:22 +00001476
Ezio Melotti6ea2a3d2010-01-04 21:54:31 +00001477.. method:: OptionParser.print_usage(file=None)
1478
1479 Print the usage message for the current program (``self.usage``) to *file*
Éric Araujo3efdf062010-12-16 03:16:29 +00001480 (default stdout). Any occurrence of the string ``%prog`` in ``self.usage``
Ezio Melotti6ea2a3d2010-01-04 21:54:31 +00001481 is replaced with the name of the current program. Does nothing if
1482 ``self.usage`` is empty or not defined.
1483
1484.. method:: OptionParser.get_usage()
1485
1486 Same as :meth:`print_usage` but returns the usage string instead of
1487 printing it.
1488
Georg Brandl6ba000c2009-09-17 22:17:38 +00001489.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +00001490
Georg Brandl6ba000c2009-09-17 22:17:38 +00001491 Set default values for several option destinations at once. Using
1492 :meth:`set_defaults` is the preferred way to set default values for options,
1493 since multiple options can share the same destination. For example, if
1494 several "mode" options all set the same destination, any one of them can set
1495 the default, and the last one wins::
Georg Brandl116aa622007-08-15 14:28:22 +00001496
Georg Brandl6ba000c2009-09-17 22:17:38 +00001497 parser.add_option("--advanced", action="store_const",
1498 dest="mode", const="advanced",
1499 default="novice") # overridden below
1500 parser.add_option("--novice", action="store_const",
1501 dest="mode", const="novice",
1502 default="advanced") # overrides above setting
Georg Brandl116aa622007-08-15 14:28:22 +00001503
Georg Brandl6ba000c2009-09-17 22:17:38 +00001504 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl116aa622007-08-15 14:28:22 +00001505
Georg Brandl6ba000c2009-09-17 22:17:38 +00001506 parser.set_defaults(mode="advanced")
1507 parser.add_option("--advanced", action="store_const",
1508 dest="mode", const="advanced")
1509 parser.add_option("--novice", action="store_const",
1510 dest="mode", const="novice")
Georg Brandl116aa622007-08-15 14:28:22 +00001511
Georg Brandl116aa622007-08-15 14:28:22 +00001512
1513.. _optparse-option-callbacks:
1514
1515Option Callbacks
1516----------------
1517
1518When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1519needs, you have two choices: extend :mod:`optparse` or define a callback option.
1520Extending :mod:`optparse` is more general, but overkill for a lot of simple
1521cases. Quite often a simple callback is all you need.
1522
1523There are two steps to defining a callback option:
1524
Georg Brandl6ba000c2009-09-17 22:17:38 +00001525* define the option itself using the ``"callback"`` action
Georg Brandl116aa622007-08-15 14:28:22 +00001526
1527* write the callback; this is a function (or method) that takes at least four
1528 arguments, as described below
1529
1530
1531.. _optparse-defining-callback-option:
1532
1533Defining a callback option
1534^^^^^^^^^^^^^^^^^^^^^^^^^^
1535
1536As always, the easiest way to define a callback option is by using the
Georg Brandl6ba000c2009-09-17 22:17:38 +00001537:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1538only option attribute you must specify is ``callback``, the function to call::
Georg Brandl116aa622007-08-15 14:28:22 +00001539
1540 parser.add_option("-c", action="callback", callback=my_callback)
1541
1542``callback`` is a function (or other callable object), so you must have already
1543defined ``my_callback()`` when you create this callback option. In this simple
Éric Araujo3efdf062010-12-16 03:16:29 +00001544case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
Georg Brandl116aa622007-08-15 14:28:22 +00001545which usually means that the option takes no arguments---the mere presence of
Éric Araujo3efdf062010-12-16 03:16:29 +00001546``-c`` on the command-line is all it needs to know. In some
Georg Brandl116aa622007-08-15 14:28:22 +00001547circumstances, though, you might want your callback to consume an arbitrary
1548number of command-line arguments. This is where writing callbacks gets tricky;
1549it's covered later in this section.
1550
1551:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandl6ba000c2009-09-17 22:17:38 +00001552will only pass additional arguments if you specify them via
1553:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1554minimal callback function signature is::
Georg Brandl116aa622007-08-15 14:28:22 +00001555
1556 def my_callback(option, opt, value, parser):
1557
1558The four arguments to a callback are described below.
1559
1560There are several other option attributes that you can supply when you define a
1561callback option:
1562
Georg Brandl6ba000c2009-09-17 22:17:38 +00001563:attr:`~Option.type`
1564 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1565 instructs :mod:`optparse` to consume one argument and convert it to
1566 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1567 though, :mod:`optparse` passes it to your callback function.
Georg Brandl116aa622007-08-15 14:28:22 +00001568
Georg Brandl6ba000c2009-09-17 22:17:38 +00001569:attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001570 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandl6ba000c2009-09-17 22:17:38 +00001571 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1572 :attr:`~Option.type`. It then passes a tuple of converted values to your
1573 callback.
Georg Brandl116aa622007-08-15 14:28:22 +00001574
Georg Brandl6ba000c2009-09-17 22:17:38 +00001575:attr:`~Option.callback_args`
Georg Brandl116aa622007-08-15 14:28:22 +00001576 a tuple of extra positional arguments to pass to the callback
1577
Georg Brandl6ba000c2009-09-17 22:17:38 +00001578:attr:`~Option.callback_kwargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001579 a dictionary of extra keyword arguments to pass to the callback
1580
1581
1582.. _optparse-how-callbacks-called:
1583
1584How callbacks are called
1585^^^^^^^^^^^^^^^^^^^^^^^^
1586
1587All callbacks are called as follows::
1588
1589 func(option, opt_str, value, parser, *args, **kwargs)
1590
1591where
1592
1593``option``
1594 is the Option instance that's calling the callback
1595
1596``opt_str``
1597 is the option string seen on the command-line that's triggering the callback.
Georg Brandl6ba000c2009-09-17 22:17:38 +00001598 (If an abbreviated long option was used, ``opt_str`` will be the full,
Éric Araujo3efdf062010-12-16 03:16:29 +00001599 canonical option string---e.g. if the user puts ``--foo`` on the
1600 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
Georg Brandl6ba000c2009-09-17 22:17:38 +00001601 ``"--foobar"``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001602
1603``value``
1604 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandl6ba000c2009-09-17 22:17:38 +00001605 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1606 the type implied by the option's type. If :attr:`~Option.type` for this option is
1607 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001608 > 1, ``value`` will be a tuple of values of the appropriate type.
1609
1610``parser``
Georg Brandl6ba000c2009-09-17 22:17:38 +00001611 is the OptionParser instance driving the whole thing, mainly useful because
1612 you can access some other interesting data through its instance attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001613
1614 ``parser.largs``
Georg Brandl6ba000c2009-09-17 22:17:38 +00001615 the current list of leftover arguments, ie. arguments that have been
1616 consumed but are neither options nor option arguments. Feel free to modify
1617 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1618 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001619
1620 ``parser.rargs``
Georg Brandl6ba000c2009-09-17 22:17:38 +00001621 the current list of remaining arguments, ie. with ``opt_str`` and
1622 ``value`` (if applicable) removed, and only the arguments following them
1623 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1624 arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001625
1626 ``parser.values``
1627 the object where option values are by default stored (an instance of
Georg Brandl6ba000c2009-09-17 22:17:38 +00001628 optparse.OptionValues). This lets callbacks use the same mechanism as the
1629 rest of :mod:`optparse` for storing option values; you don't need to mess
1630 around with globals or closures. You can also access or modify the
1631 value(s) of any options already encountered on the command-line.
Georg Brandl116aa622007-08-15 14:28:22 +00001632
1633``args``
Georg Brandl6ba000c2009-09-17 22:17:38 +00001634 is a tuple of arbitrary positional arguments supplied via the
1635 :attr:`~Option.callback_args` option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001636
1637``kwargs``
Georg Brandl6ba000c2009-09-17 22:17:38 +00001638 is a dictionary of arbitrary keyword arguments supplied via
1639 :attr:`~Option.callback_kwargs`.
Georg Brandl116aa622007-08-15 14:28:22 +00001640
1641
1642.. _optparse-raising-errors-in-callback:
1643
1644Raising errors in a callback
1645^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1646
Georg Brandl6ba000c2009-09-17 22:17:38 +00001647The callback function should raise :exc:`OptionValueError` if there are any
1648problems with the option or its argument(s). :mod:`optparse` catches this and
1649terminates the program, printing the error message you supply to stderr. Your
1650message should be clear, concise, accurate, and mention the option at fault.
1651Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl116aa622007-08-15 14:28:22 +00001652
1653
1654.. _optparse-callback-example-1:
1655
1656Callback example 1: trivial callback
1657^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1658
1659Here's an example of a callback option that takes no arguments, and simply
1660records that the option was seen::
1661
1662 def record_foo_seen(option, opt_str, value, parser):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001663 parser.values.saw_foo = True
Georg Brandl116aa622007-08-15 14:28:22 +00001664
1665 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1666
Georg Brandl6ba000c2009-09-17 22:17:38 +00001667Of course, you could do that with the ``"store_true"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001668
1669
1670.. _optparse-callback-example-2:
1671
1672Callback example 2: check option order
1673^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1674
Éric Araujo3efdf062010-12-16 03:16:29 +00001675Here's a slightly more interesting example: record the fact that ``-a`` is
1676seen, but blow up if it comes after ``-b`` in the command-line. ::
Georg Brandl116aa622007-08-15 14:28:22 +00001677
1678 def check_order(option, opt_str, value, parser):
1679 if parser.values.b:
1680 raise OptionValueError("can't use -a after -b")
1681 parser.values.a = 1
1682 [...]
1683 parser.add_option("-a", action="callback", callback=check_order)
1684 parser.add_option("-b", action="store_true", dest="b")
1685
1686
1687.. _optparse-callback-example-3:
1688
1689Callback example 3: check option order (generalized)
1690^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1691
1692If you want to re-use this callback for several similar options (set a flag, but
Éric Araujo3efdf062010-12-16 03:16:29 +00001693blow up if ``-b`` has already been seen), it needs a bit of work: the error
Georg Brandl116aa622007-08-15 14:28:22 +00001694message and the flag that it sets must be generalized. ::
1695
1696 def check_order(option, opt_str, value, parser):
1697 if parser.values.b:
1698 raise OptionValueError("can't use %s after -b" % opt_str)
1699 setattr(parser.values, option.dest, 1)
1700 [...]
1701 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1702 parser.add_option("-b", action="store_true", dest="b")
1703 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1704
1705
1706.. _optparse-callback-example-4:
1707
1708Callback example 4: check arbitrary condition
1709^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1710
1711Of course, you could put any condition in there---you're not limited to checking
1712the values of already-defined options. For example, if you have options that
1713should not be called when the moon is full, all you have to do is this::
1714
1715 def check_moon(option, opt_str, value, parser):
1716 if is_moon_full():
1717 raise OptionValueError("%s option invalid when moon is full"
1718 % opt_str)
1719 setattr(parser.values, option.dest, 1)
1720 [...]
1721 parser.add_option("--foo",
1722 action="callback", callback=check_moon, dest="foo")
1723
1724(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1725
1726
1727.. _optparse-callback-example-5:
1728
1729Callback example 5: fixed arguments
1730^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1731
1732Things get slightly more interesting when you define callback options that take
1733a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandl6ba000c2009-09-17 22:17:38 +00001734is similar to defining a ``"store"`` or ``"append"`` option: if you define
1735:attr:`~Option.type`, then the option takes one argument that must be
1736convertible to that type; if you further define :attr:`~Option.nargs`, then the
1737option takes :attr:`~Option.nargs` arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001738
Georg Brandl6ba000c2009-09-17 22:17:38 +00001739Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl116aa622007-08-15 14:28:22 +00001740
1741 def store_value(option, opt_str, value, parser):
1742 setattr(parser.values, option.dest, value)
1743 [...]
1744 parser.add_option("--foo",
1745 action="callback", callback=store_value,
1746 type="int", nargs=3, dest="foo")
1747
1748Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1749them to integers for you; all you have to do is store them. (Or whatever;
1750obviously you don't need a callback for this example.)
1751
1752
1753.. _optparse-callback-example-6:
1754
1755Callback example 6: variable arguments
1756^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1757
1758Things get hairy when you want an option to take a variable number of arguments.
1759For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1760built-in capabilities for it. And you have to deal with certain intricacies of
1761conventional Unix command-line parsing that :mod:`optparse` normally handles for
1762you. In particular, callbacks should implement the conventional rules for bare
Éric Araujo3efdf062010-12-16 03:16:29 +00001763``--`` and ``-`` arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001764
Éric Araujo3efdf062010-12-16 03:16:29 +00001765* either ``--`` or ``-`` can be option arguments
Georg Brandl116aa622007-08-15 14:28:22 +00001766
Éric Araujo3efdf062010-12-16 03:16:29 +00001767* bare ``--`` (if not the argument to some option): halt command-line
1768 processing and discard the ``--``
Georg Brandl116aa622007-08-15 14:28:22 +00001769
Éric Araujo3efdf062010-12-16 03:16:29 +00001770* bare ``-`` (if not the argument to some option): halt command-line
1771 processing but keep the ``-`` (append it to ``parser.largs``)
Georg Brandl116aa622007-08-15 14:28:22 +00001772
1773If you want an option that takes a variable number of arguments, there are
1774several subtle, tricky issues to worry about. The exact implementation you
1775choose will be based on which trade-offs you're willing to make for your
1776application (which is why :mod:`optparse` doesn't support this sort of thing
1777directly).
1778
1779Nevertheless, here's a stab at a callback for an option with variable
1780arguments::
1781
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001782 def vararg_callback(option, opt_str, value, parser):
1783 assert value is None
1784 value = []
Georg Brandl116aa622007-08-15 14:28:22 +00001785
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001786 def floatable(str):
1787 try:
1788 float(str)
1789 return True
1790 except ValueError:
1791 return False
Georg Brandl116aa622007-08-15 14:28:22 +00001792
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001793 for arg in parser.rargs:
1794 # stop on --foo like options
1795 if arg[:2] == "--" and len(arg) > 2:
1796 break
1797 # stop on -a, but not on -3 or -3.0
1798 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1799 break
1800 value.append(arg)
1801
1802 del parser.rargs[:len(value)]
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001803 setattr(parser.values, option.dest, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001804
1805 [...]
Benjamin Petersonae5360b2008-09-08 23:05:23 +00001806 parser.add_option("-c", "--callback", dest="vararg_attr",
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001807 action="callback", callback=vararg_callback)
Georg Brandl116aa622007-08-15 14:28:22 +00001808
Georg Brandl116aa622007-08-15 14:28:22 +00001809
1810.. _optparse-extending-optparse:
1811
1812Extending :mod:`optparse`
1813-------------------------
1814
1815Since the two major controlling factors in how :mod:`optparse` interprets
1816command-line options are the action and type of each option, the most likely
1817direction of extension is to add new actions and new types.
1818
1819
1820.. _optparse-adding-new-types:
1821
1822Adding new types
1823^^^^^^^^^^^^^^^^
1824
1825To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandl6ba000c2009-09-17 22:17:38 +00001826:class:`Option` class. This class has a couple of attributes that define
1827:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl116aa622007-08-15 14:28:22 +00001828
Georg Brandl6ba000c2009-09-17 22:17:38 +00001829.. attribute:: Option.TYPES
Georg Brandl116aa622007-08-15 14:28:22 +00001830
Georg Brandl6ba000c2009-09-17 22:17:38 +00001831 A tuple of type names; in your subclass, simply define a new tuple
1832 :attr:`TYPES` that builds on the standard one.
Georg Brandl116aa622007-08-15 14:28:22 +00001833
Georg Brandl6ba000c2009-09-17 22:17:38 +00001834.. attribute:: Option.TYPE_CHECKER
Georg Brandl116aa622007-08-15 14:28:22 +00001835
Georg Brandl6ba000c2009-09-17 22:17:38 +00001836 A dictionary mapping type names to type-checking functions. A type-checking
1837 function has the following signature::
Georg Brandl116aa622007-08-15 14:28:22 +00001838
Georg Brandl6ba000c2009-09-17 22:17:38 +00001839 def check_mytype(option, opt, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001840
Georg Brandl6ba000c2009-09-17 22:17:38 +00001841 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
Éric Araujo3efdf062010-12-16 03:16:29 +00001842 (e.g., ``-f``), and ``value`` is the string from the command line that must
Georg Brandl6ba000c2009-09-17 22:17:38 +00001843 be checked and converted to your desired type. ``check_mytype()`` should
1844 return an object of the hypothetical type ``mytype``. The value returned by
1845 a type-checking function will wind up in the OptionValues instance returned
1846 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1847 ``value`` parameter.
1848
1849 Your type-checking function should raise :exc:`OptionValueError` if it
1850 encounters any problems. :exc:`OptionValueError` takes a single string
1851 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1852 method, which in turn prepends the program name and the string ``"error:"``
1853 and prints everything to stderr before terminating the process.
1854
1855Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl116aa622007-08-15 14:28:22 +00001856parse Python-style complex numbers on the command line. (This is even sillier
1857than it used to be, because :mod:`optparse` 1.3 added built-in support for
1858complex numbers, but never mind.)
1859
1860First, the necessary imports::
1861
1862 from copy import copy
1863 from optparse import Option, OptionValueError
1864
1865You need to define your type-checker first, since it's referred to later (in the
Georg Brandl6ba000c2009-09-17 22:17:38 +00001866:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl116aa622007-08-15 14:28:22 +00001867
1868 def check_complex(option, opt, value):
1869 try:
1870 return complex(value)
1871 except ValueError:
1872 raise OptionValueError(
1873 "option %s: invalid complex value: %r" % (opt, value))
1874
1875Finally, the Option subclass::
1876
1877 class MyOption (Option):
1878 TYPES = Option.TYPES + ("complex",)
1879 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1880 TYPE_CHECKER["complex"] = check_complex
1881
1882(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandl6ba000c2009-09-17 22:17:38 +00001883up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1884Option class. This being Python, nothing stops you from doing that except good
1885manners and common sense.)
Georg Brandl116aa622007-08-15 14:28:22 +00001886
1887That's it! Now you can write a script that uses the new option type just like
1888any other :mod:`optparse`\ -based script, except you have to instruct your
1889OptionParser to use MyOption instead of Option::
1890
1891 parser = OptionParser(option_class=MyOption)
1892 parser.add_option("-c", type="complex")
1893
1894Alternately, you can build your own option list and pass it to OptionParser; if
1895you don't use :meth:`add_option` in the above way, you don't need to tell
1896OptionParser which option class to use::
1897
1898 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1899 parser = OptionParser(option_list=option_list)
1900
1901
1902.. _optparse-adding-new-actions:
1903
1904Adding new actions
1905^^^^^^^^^^^^^^^^^^
1906
1907Adding new actions is a bit trickier, because you have to understand that
1908:mod:`optparse` has a couple of classifications for actions:
1909
1910"store" actions
1911 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandl6ba000c2009-09-17 22:17:38 +00001912 current OptionValues instance; these options require a :attr:`~Option.dest`
1913 attribute to be supplied to the Option constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001914
1915"typed" actions
Georg Brandl6ba000c2009-09-17 22:17:38 +00001916 actions that take a value from the command line and expect it to be of a
1917 certain type; or rather, a string that can be converted to a certain type.
1918 These options require a :attr:`~Option.type` attribute to the Option
1919 constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001920
Georg Brandl6ba000c2009-09-17 22:17:38 +00001921These are overlapping sets: some default "store" actions are ``"store"``,
1922``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1923actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001924
1925When you add an action, you need to categorize it by listing it in at least one
1926of the following class attributes of Option (all are lists of strings):
1927
Georg Brandl6ba000c2009-09-17 22:17:38 +00001928.. attribute:: Option.ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001929
Georg Brandl6ba000c2009-09-17 22:17:38 +00001930 All actions must be listed in ACTIONS.
Georg Brandl116aa622007-08-15 14:28:22 +00001931
Georg Brandl6ba000c2009-09-17 22:17:38 +00001932.. attribute:: Option.STORE_ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001933
Georg Brandl6ba000c2009-09-17 22:17:38 +00001934 "store" actions are additionally listed here.
1935
1936.. attribute:: Option.TYPED_ACTIONS
1937
1938 "typed" actions are additionally listed here.
1939
1940.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1941
1942 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl116aa622007-08-15 14:28:22 +00001943 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandl6ba000c2009-09-17 22:17:38 +00001944 assigns the default type, ``"string"``, to options with no explicit type
1945 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001946
1947In order to actually implement your new action, you must override Option's
1948:meth:`take_action` method and add a case that recognizes your action.
1949
Georg Brandl6ba000c2009-09-17 22:17:38 +00001950For example, let's add an ``"extend"`` action. This is similar to the standard
1951``"append"`` action, but instead of taking a single value from the command-line
1952and appending it to an existing list, ``"extend"`` will take multiple values in
1953a single comma-delimited string, and extend an existing list with them. That
Éric Araujo3efdf062010-12-16 03:16:29 +00001954is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
Georg Brandl6ba000c2009-09-17 22:17:38 +00001955line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001956
1957 --names=foo,bar --names blah --names ding,dong
1958
1959would result in a list ::
1960
1961 ["foo", "bar", "blah", "ding", "dong"]
1962
1963Again we define a subclass of Option::
1964
Ezio Melottide2cef52010-01-03 09:08:34 +00001965 class MyOption(Option):
Georg Brandl116aa622007-08-15 14:28:22 +00001966
1967 ACTIONS = Option.ACTIONS + ("extend",)
1968 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1969 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1970 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1971
1972 def take_action(self, action, dest, opt, value, values, parser):
1973 if action == "extend":
1974 lvalue = value.split(",")
1975 values.ensure_value(dest, []).extend(lvalue)
1976 else:
1977 Option.take_action(
1978 self, action, dest, opt, value, values, parser)
1979
1980Features of note:
1981
Georg Brandl6ba000c2009-09-17 22:17:38 +00001982* ``"extend"`` both expects a value on the command-line and stores that value
1983 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1984 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001985
Georg Brandl6ba000c2009-09-17 22:17:38 +00001986* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1987 ``"extend"`` actions, we put the ``"extend"`` action in
1988 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001989
1990* :meth:`MyOption.take_action` implements just this one new action, and passes
1991 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandl6ba000c2009-09-17 22:17:38 +00001992 actions.
Georg Brandl116aa622007-08-15 14:28:22 +00001993
Georg Brandl6ba000c2009-09-17 22:17:38 +00001994* ``values`` is an instance of the optparse_parser.Values class, which provides
1995 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1996 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001997
1998 values.ensure_value(attr, value)
1999
2000 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandl6ba000c2009-09-17 22:17:38 +00002001 ensure_value() first sets it to ``value``, and then returns 'value. This is
2002 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
2003 of which accumulate data in a variable and expect that variable to be of a
2004 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl116aa622007-08-15 14:28:22 +00002005 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandl6ba000c2009-09-17 22:17:38 +00002006 about setting a default value for the option destinations in question; they
2007 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl116aa622007-08-15 14:28:22 +00002008 getting it right when it's needed.