blob: d0783e7707f95d5720fee20e1b3e3693a533cfaa [file] [log] [blame]
Steven Betharde9330e72010-03-02 08:38:09 +00001:mod:`optparse` --- Parser for command line options
2===================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00003
4.. module:: optparse
Steven Betharde9330e72010-03-02 08:38:09 +00005 :synopsis: Command-line option parsing library.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00006 :deprecated:
Éric Araujo29a0b572011-08-19 02:14:03 +02007.. moduleauthor:: Greg Ward <gward@python.net>
8.. sectionauthor:: Greg Ward <gward@python.net>
9
10.. versionadded:: 2.3
Georg Brandl8ec7f652007-08-15 14:28:01 +000011
Steven Bethard74bd9cf2010-05-24 02:38:00 +000012.. deprecated:: 2.7
13 The :mod:`optparse` module is deprecated and will not be developed further;
14 development will continue with the :mod:`argparse` module.
15
Éric Araujo29a0b572011-08-19 02:14:03 +020016**Source code:** :source:`Lib/optparse.py`
Georg Brandl8ec7f652007-08-15 14:28:01 +000017
Éric Araujo29a0b572011-08-19 02:14:03 +020018--------------
Georg Brandl8ec7f652007-08-15 14:28:01 +000019
Georg Brandlb926ebb2009-09-17 17:14:04 +000020:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
21command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
22more declarative style of command-line parsing: you create an instance of
23:class:`OptionParser`, populate it with options, and parse the command
24line. :mod:`optparse` allows users to specify options in the conventional
25GNU/POSIX syntax, and additionally generates usage and help messages for you.
Georg Brandl8ec7f652007-08-15 14:28:01 +000026
Georg Brandlb926ebb2009-09-17 17:14:04 +000027Here's an example of using :mod:`optparse` in a simple script::
Georg Brandl8ec7f652007-08-15 14:28:01 +000028
29 from optparse import OptionParser
30 [...]
31 parser = OptionParser()
32 parser.add_option("-f", "--file", dest="filename",
33 help="write report to FILE", metavar="FILE")
34 parser.add_option("-q", "--quiet",
35 action="store_false", dest="verbose", default=True,
36 help="don't print status messages to stdout")
37
38 (options, args) = parser.parse_args()
39
40With these few lines of code, users of your script can now do the "usual thing"
41on the command-line, for example::
42
43 <yourscript> --file=outfile -q
44
Georg Brandlb926ebb2009-09-17 17:14:04 +000045As it parses the command line, :mod:`optparse` sets attributes of the
46``options`` object returned by :meth:`parse_args` based on user-supplied
47command-line values. When :meth:`parse_args` returns from parsing this command
48line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
49``False``. :mod:`optparse` supports both long and short options, allows short
Georg Brandl8ec7f652007-08-15 14:28:01 +000050options to be merged together, and allows options to be associated with their
51arguments in a variety of ways. Thus, the following command lines are all
52equivalent to the above example::
53
54 <yourscript> -f outfile --quiet
55 <yourscript> --quiet --file outfile
56 <yourscript> -q -foutfile
57 <yourscript> -qfoutfile
58
59Additionally, users can run one of ::
60
61 <yourscript> -h
62 <yourscript> --help
63
Ezio Melotti5129ed32010-01-03 09:01:27 +000064and :mod:`optparse` will print out a brief summary of your script's options:
65
66.. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +000067
Georg Brandl28046022011-02-25 11:01:04 +000068 Usage: <yourscript> [options]
Georg Brandl8ec7f652007-08-15 14:28:01 +000069
Georg Brandl28046022011-02-25 11:01:04 +000070 Options:
Georg Brandl8ec7f652007-08-15 14:28:01 +000071 -h, --help show this help message and exit
72 -f FILE, --file=FILE write report to FILE
73 -q, --quiet don't print status messages to stdout
74
75where the value of *yourscript* is determined at runtime (normally from
76``sys.argv[0]``).
77
Georg Brandl8ec7f652007-08-15 14:28:01 +000078
79.. _optparse-background:
80
81Background
82----------
83
84:mod:`optparse` was explicitly designed to encourage the creation of programs
85with straightforward, conventional command-line interfaces. To that end, it
86supports only the most common command-line syntax and semantics conventionally
87used under Unix. If you are unfamiliar with these conventions, read this
88section to acquaint yourself with them.
89
90
91.. _optparse-terminology:
92
93Terminology
94^^^^^^^^^^^
95
96argument
Georg Brandlb926ebb2009-09-17 17:14:04 +000097 a string entered on the command-line, and passed by the shell to ``execl()``
98 or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
99 (``sys.argv[0]`` is the name of the program being executed). Unix shells
100 also use the term "word".
Georg Brandl8ec7f652007-08-15 14:28:01 +0000101
102 It is occasionally desirable to substitute an argument list other than
103 ``sys.argv[1:]``, so you should read "argument" as "an element of
104 ``sys.argv[1:]``, or of some other list provided as a substitute for
105 ``sys.argv[1:]``".
106
Andrew M. Kuchling810f8072008-09-06 13:04:02 +0000107option
Georg Brandlb926ebb2009-09-17 17:14:04 +0000108 an argument used to supply extra information to guide or customize the
109 execution of a program. There are many different syntaxes for options; the
110 traditional Unix syntax is a hyphen ("-") followed by a single letter,
Éric Araujoa8132ec2010-12-16 03:53:53 +0000111 e.g. ``-x`` or ``-F``. Also, traditional Unix syntax allows multiple
112 options to be merged into a single argument, e.g. ``-x -F`` is equivalent
113 to ``-xF``. The GNU project introduced ``--`` followed by a series of
114 hyphen-separated words, e.g. ``--file`` or ``--dry-run``. These are the
Georg Brandlb926ebb2009-09-17 17:14:04 +0000115 only two option syntaxes provided by :mod:`optparse`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000116
117 Some other option syntaxes that the world has seen include:
118
Éric Araujoa8132ec2010-12-16 03:53:53 +0000119 * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
Georg Brandl8ec7f652007-08-15 14:28:01 +0000120 as multiple options merged into a single argument)
121
Éric Araujoa8132ec2010-12-16 03:53:53 +0000122 * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
Georg Brandl8ec7f652007-08-15 14:28:01 +0000123 equivalent to the previous syntax, but they aren't usually seen in the same
124 program)
125
126 * a plus sign followed by a single letter, or a few letters, or a word, e.g.
Éric Araujoa8132ec2010-12-16 03:53:53 +0000127 ``+f``, ``+rgb``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000128
Éric Araujoa8132ec2010-12-16 03:53:53 +0000129 * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``,
130 ``/file``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000131
Georg Brandlb926ebb2009-09-17 17:14:04 +0000132 These option syntaxes are not supported by :mod:`optparse`, and they never
133 will be. This is deliberate: the first three are non-standard on any
134 environment, and the last only makes sense if you're exclusively targeting
135 VMS, MS-DOS, and/or Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000136
137option argument
Georg Brandlb926ebb2009-09-17 17:14:04 +0000138 an argument that follows an option, is closely associated with that option,
139 and is consumed from the argument list when that option is. With
140 :mod:`optparse`, option arguments may either be in a separate argument from
Ezio Melotti5129ed32010-01-03 09:01:27 +0000141 their option:
142
143 .. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +0000144
145 -f foo
146 --file foo
147
Ezio Melotti5129ed32010-01-03 09:01:27 +0000148 or included in the same argument:
149
150 .. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151
152 -ffoo
153 --file=foo
154
Georg Brandlb926ebb2009-09-17 17:14:04 +0000155 Typically, a given option either takes an argument or it doesn't. Lots of
156 people want an "optional option arguments" feature, meaning that some options
157 will take an argument if they see it, and won't if they don't. This is
Éric Araujoa8132ec2010-12-16 03:53:53 +0000158 somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
159 an optional argument and ``-b`` is another option entirely, how do we
160 interpret ``-ab``? Because of this ambiguity, :mod:`optparse` does not
Georg Brandlb926ebb2009-09-17 17:14:04 +0000161 support this feature.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000162
163positional argument
164 something leftover in the argument list after options have been parsed, i.e.
Georg Brandlb926ebb2009-09-17 17:14:04 +0000165 after options and their arguments have been parsed and removed from the
166 argument list.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000167
168required option
169 an option that must be supplied on the command-line; note that the phrase
170 "required option" is self-contradictory in English. :mod:`optparse` doesn't
Georg Brandlb926ebb2009-09-17 17:14:04 +0000171 prevent you from implementing required options, but doesn't give you much
Georg Brandl66d8d692009-12-28 08:48:24 +0000172 help at it either.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000173
174For example, consider this hypothetical command-line::
175
176 prog -v --report /tmp/report.txt foo bar
177
Éric Araujoa8132ec2010-12-16 03:53:53 +0000178``-v`` and ``--report`` are both options. Assuming that ``--report``
179takes one argument, ``/tmp/report.txt`` is an option argument. ``foo`` and
180``bar`` are positional arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000181
182
183.. _optparse-what-options-for:
184
185What are options for?
186^^^^^^^^^^^^^^^^^^^^^
187
188Options are used to provide extra information to tune or customize the execution
189of a program. In case it wasn't clear, options are usually *optional*. A
190program should be able to run just fine with no options whatsoever. (Pick a
191random program from the Unix or GNU toolsets. Can it run without any options at
192all and still make sense? The main exceptions are ``find``, ``tar``, and
193``dd``\ ---all of which are mutant oddballs that have been rightly criticized
194for their non-standard syntax and confusing interfaces.)
195
196Lots of people want their programs to have "required options". Think about it.
197If it's required, then it's *not optional*! If there is a piece of information
198that your program absolutely requires in order to run successfully, that's what
199positional arguments are for.
200
201As an example of good command-line interface design, consider the humble ``cp``
202utility, for copying files. It doesn't make much sense to try to copy files
203without supplying a destination and at least one source. Hence, ``cp`` fails if
204you run it with no arguments. However, it has a flexible, useful syntax that
205does not require any options at all::
206
207 cp SOURCE DEST
208 cp SOURCE ... DEST-DIR
209
210You can get pretty far with just that. Most ``cp`` implementations provide a
211bunch of options to tweak exactly how the files are copied: you can preserve
212mode and modification time, avoid following symlinks, ask before clobbering
213existing files, etc. But none of this distracts from the core mission of
214``cp``, which is to copy either one file to another, or several files to another
215directory.
216
217
218.. _optparse-what-positional-arguments-for:
219
220What are positional arguments for?
221^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
222
223Positional arguments are for those pieces of information that your program
224absolutely, positively requires to run.
225
226A good user interface should have as few absolute requirements as possible. If
227your program requires 17 distinct pieces of information in order to run
228successfully, it doesn't much matter *how* you get that information from the
229user---most people will give up and walk away before they successfully run the
230program. This applies whether the user interface is a command-line, a
231configuration file, or a GUI: if you make that many demands on your users, most
232of them will simply give up.
233
234In short, try to minimize the amount of information that users are absolutely
235required to supply---use sensible defaults whenever possible. Of course, you
236also want to make your programs reasonably flexible. That's what options are
237for. Again, it doesn't matter if they are entries in a config file, widgets in
238the "Preferences" dialog of a GUI, or command-line options---the more options
239you implement, the more flexible your program is, and the more complicated its
240implementation becomes. Too much flexibility has drawbacks as well, of course;
241too many options can overwhelm users and make your code much harder to maintain.
242
Georg Brandl8ec7f652007-08-15 14:28:01 +0000243
244.. _optparse-tutorial:
245
246Tutorial
247--------
248
249While :mod:`optparse` is quite flexible and powerful, it's also straightforward
250to use in most cases. This section covers the code patterns that are common to
251any :mod:`optparse`\ -based program.
252
253First, you need to import the OptionParser class; then, early in the main
254program, create an OptionParser instance::
255
256 from optparse import OptionParser
257 [...]
258 parser = OptionParser()
259
260Then you can start defining options. The basic syntax is::
261
262 parser.add_option(opt_str, ...,
263 attr=value, ...)
264
Éric Araujoa8132ec2010-12-16 03:53:53 +0000265Each option has one or more option strings, such as ``-f`` or ``--file``,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266and several option attributes that tell :mod:`optparse` what to expect and what
267to do when it encounters that option on the command line.
268
269Typically, each option will have one short option string and one long option
270string, e.g.::
271
272 parser.add_option("-f", "--file", ...)
273
274You're free to define as many short option strings and as many long option
275strings as you like (including zero), as long as there is at least one option
276string overall.
277
278The option strings passed to :meth:`add_option` are effectively labels for the
279option defined by that call. For brevity, we will frequently refer to
280*encountering an option* on the command line; in reality, :mod:`optparse`
281encounters *option strings* and looks up options from them.
282
283Once all of your options are defined, instruct :mod:`optparse` to parse your
284program's command line::
285
286 (options, args) = parser.parse_args()
287
288(If you like, you can pass a custom argument list to :meth:`parse_args`, but
289that's rarely necessary: by default it uses ``sys.argv[1:]``.)
290
291:meth:`parse_args` returns two values:
292
293* ``options``, an object containing values for all of your options---e.g. if
Éric Araujoa8132ec2010-12-16 03:53:53 +0000294 ``--file`` takes a single string argument, then ``options.file`` will be the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000295 filename supplied by the user, or ``None`` if the user did not supply that
296 option
297
298* ``args``, the list of positional arguments leftover after parsing options
299
300This tutorial section only covers the four most important option attributes:
Georg Brandlb926ebb2009-09-17 17:14:04 +0000301:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
302(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
303most fundamental.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000304
305
306.. _optparse-understanding-option-actions:
307
308Understanding option actions
309^^^^^^^^^^^^^^^^^^^^^^^^^^^^
310
311Actions tell :mod:`optparse` what to do when it encounters an option on the
312command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
313adding new actions is an advanced topic covered in section
Georg Brandlb926ebb2009-09-17 17:14:04 +0000314:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
315a value in some variable---for example, take a string from the command line and
316store it in an attribute of ``options``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000317
318If you don't specify an option action, :mod:`optparse` defaults to ``store``.
319
320
321.. _optparse-store-action:
322
323The store action
324^^^^^^^^^^^^^^^^
325
326The most common option action is ``store``, which tells :mod:`optparse` to take
327the next argument (or the remainder of the current argument), ensure that it is
328of the correct type, and store it to your chosen destination.
329
330For example::
331
332 parser.add_option("-f", "--file",
333 action="store", type="string", dest="filename")
334
335Now let's make up a fake command line and ask :mod:`optparse` to parse it::
336
337 args = ["-f", "foo.txt"]
338 (options, args) = parser.parse_args(args)
339
Éric Araujoa8132ec2010-12-16 03:53:53 +0000340When :mod:`optparse` sees the option string ``-f``, it consumes the next
341argument, ``foo.txt``, and stores it in ``options.filename``. So, after this
Georg Brandl8ec7f652007-08-15 14:28:01 +0000342call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
343
344Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
345Here's an option that expects an integer argument::
346
347 parser.add_option("-n", type="int", dest="num")
348
349Note that this option has no long option string, which is perfectly acceptable.
350Also, there's no explicit action, since the default is ``store``.
351
352Let's parse another fake command-line. This time, we'll jam the option argument
Éric Araujoa8132ec2010-12-16 03:53:53 +0000353right up against the option: since ``-n42`` (one argument) is equivalent to
354``-n 42`` (two arguments), the code ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000355
356 (options, args) = parser.parse_args(["-n42"])
357 print options.num
358
Éric Araujoa8132ec2010-12-16 03:53:53 +0000359will print ``42``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000360
361If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
362the fact that the default action is ``store``, that means our first example can
363be a lot shorter::
364
365 parser.add_option("-f", "--file", dest="filename")
366
367If you don't supply a destination, :mod:`optparse` figures out a sensible
368default from the option strings: if the first long option string is
Éric Araujoa8132ec2010-12-16 03:53:53 +0000369``--foo-bar``, then the default destination is ``foo_bar``. If there are no
Georg Brandl8ec7f652007-08-15 14:28:01 +0000370long option strings, :mod:`optparse` looks at the first short option string: the
Éric Araujoa8132ec2010-12-16 03:53:53 +0000371default destination for ``-f`` is ``f``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000372
373:mod:`optparse` also includes built-in ``long`` and ``complex`` types. Adding
374types is covered in section :ref:`optparse-extending-optparse`.
375
376
377.. _optparse-handling-boolean-options:
378
379Handling boolean (flag) options
380^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
381
382Flag options---set a variable to true or false when a particular option is seen
383---are quite common. :mod:`optparse` supports them with two separate actions,
384``store_true`` and ``store_false``. For example, you might have a ``verbose``
Éric Araujoa8132ec2010-12-16 03:53:53 +0000385flag that is turned on with ``-v`` and off with ``-q``::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000386
387 parser.add_option("-v", action="store_true", dest="verbose")
388 parser.add_option("-q", action="store_false", dest="verbose")
389
390Here we have two different options with the same destination, which is perfectly
391OK. (It just means you have to be a bit careful when setting default values---
392see below.)
393
Éric Araujoa8132ec2010-12-16 03:53:53 +0000394When :mod:`optparse` encounters ``-v`` on the command line, it sets
395``options.verbose`` to ``True``; when it encounters ``-q``,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000396``options.verbose`` is set to ``False``.
397
398
399.. _optparse-other-actions:
400
401Other actions
402^^^^^^^^^^^^^
403
404Some other actions supported by :mod:`optparse` are:
405
Georg Brandlb926ebb2009-09-17 17:14:04 +0000406``"store_const"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000407 store a constant value
408
Georg Brandlb926ebb2009-09-17 17:14:04 +0000409``"append"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000410 append this option's argument to a list
411
Georg Brandlb926ebb2009-09-17 17:14:04 +0000412``"count"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000413 increment a counter by one
414
Georg Brandlb926ebb2009-09-17 17:14:04 +0000415``"callback"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000416 call a specified function
417
418These are covered in section :ref:`optparse-reference-guide`, Reference Guide
419and section :ref:`optparse-option-callbacks`.
420
421
422.. _optparse-default-values:
423
424Default values
425^^^^^^^^^^^^^^
426
427All of the above examples involve setting some variable (the "destination") when
428certain command-line options are seen. What happens if those options are never
429seen? Since we didn't supply any defaults, they are all set to ``None``. This
430is usually fine, but sometimes you want more control. :mod:`optparse` lets you
431supply a default value for each destination, which is assigned before the
432command line is parsed.
433
434First, consider the verbose/quiet example. If we want :mod:`optparse` to set
Éric Araujoa8132ec2010-12-16 03:53:53 +0000435``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000436
437 parser.add_option("-v", action="store_true", dest="verbose", default=True)
438 parser.add_option("-q", action="store_false", dest="verbose")
439
440Since default values apply to the *destination* rather than to any particular
441option, and these two options happen to have the same destination, this is
442exactly equivalent::
443
444 parser.add_option("-v", action="store_true", dest="verbose")
445 parser.add_option("-q", action="store_false", dest="verbose", default=True)
446
447Consider this::
448
449 parser.add_option("-v", action="store_true", dest="verbose", default=False)
450 parser.add_option("-q", action="store_false", dest="verbose", default=True)
451
452Again, the default value for ``verbose`` will be ``True``: the last default
453value supplied for any particular destination is the one that counts.
454
455A clearer way to specify default values is the :meth:`set_defaults` method of
456OptionParser, which you can call at any time before calling :meth:`parse_args`::
457
458 parser.set_defaults(verbose=True)
459 parser.add_option(...)
460 (options, args) = parser.parse_args()
461
462As before, the last value specified for a given option destination is the one
463that counts. For clarity, try to use one method or the other of setting default
464values, not both.
465
466
467.. _optparse-generating-help:
468
469Generating help
470^^^^^^^^^^^^^^^
471
472:mod:`optparse`'s ability to generate help and usage text automatically is
473useful for creating user-friendly command-line interfaces. All you have to do
Georg Brandlb926ebb2009-09-17 17:14:04 +0000474is supply a :attr:`~Option.help` value for each option, and optionally a short
475usage message for your whole program. Here's an OptionParser populated with
Georg Brandl8ec7f652007-08-15 14:28:01 +0000476user-friendly (documented) options::
477
478 usage = "usage: %prog [options] arg1 arg2"
479 parser = OptionParser(usage=usage)
480 parser.add_option("-v", "--verbose",
481 action="store_true", dest="verbose", default=True,
482 help="make lots of noise [default]")
483 parser.add_option("-q", "--quiet",
Andrew M. Kuchling810f8072008-09-06 13:04:02 +0000484 action="store_false", dest="verbose",
Georg Brandl8ec7f652007-08-15 14:28:01 +0000485 help="be vewwy quiet (I'm hunting wabbits)")
486 parser.add_option("-f", "--filename",
Georg Brandld7226ff2009-09-16 13:06:22 +0000487 metavar="FILE", help="write output to FILE")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000488 parser.add_option("-m", "--mode",
489 default="intermediate",
490 help="interaction mode: novice, intermediate, "
491 "or expert [default: %default]")
492
Éric Araujoa8132ec2010-12-16 03:53:53 +0000493If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000494command-line, or if you just call :meth:`parser.print_help`, it prints the
Ezio Melotti5129ed32010-01-03 09:01:27 +0000495following to standard output:
496
497.. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +0000498
Georg Brandl28046022011-02-25 11:01:04 +0000499 Usage: <yourscript> [options] arg1 arg2
Georg Brandl8ec7f652007-08-15 14:28:01 +0000500
Georg Brandl28046022011-02-25 11:01:04 +0000501 Options:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502 -h, --help show this help message and exit
503 -v, --verbose make lots of noise [default]
504 -q, --quiet be vewwy quiet (I'm hunting wabbits)
505 -f FILE, --filename=FILE
506 write output to FILE
507 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
508 expert [default: intermediate]
509
510(If the help output is triggered by a help option, :mod:`optparse` exits after
511printing the help text.)
512
513There's a lot going on here to help :mod:`optparse` generate the best possible
514help message:
515
516* the script defines its own usage message::
517
518 usage = "usage: %prog [options] arg1 arg2"
519
Éric Araujoa8132ec2010-12-16 03:53:53 +0000520 :mod:`optparse` expands ``%prog`` in the usage string to the name of the
Georg Brandlb926ebb2009-09-17 17:14:04 +0000521 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
522 is then printed before the detailed option help.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000523
524 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandl28046022011-02-25 11:01:04 +0000525 default: ``"Usage: %prog [options]"``, which is fine if your script doesn't
Georg Brandlb926ebb2009-09-17 17:14:04 +0000526 take any positional arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000527
528* every option defines a help string, and doesn't worry about line-wrapping---
529 :mod:`optparse` takes care of wrapping lines and making the help output look
530 good.
531
532* options that take a value indicate this fact in their automatically-generated
533 help message, e.g. for the "mode" option::
534
535 -m MODE, --mode=MODE
536
537 Here, "MODE" is called the meta-variable: it stands for the argument that the
Éric Araujoa8132ec2010-12-16 03:53:53 +0000538 user is expected to supply to ``-m``/``--mode``. By default,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000539 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandlb926ebb2009-09-17 17:14:04 +0000540 that for the meta-variable. Sometimes, that's not what you want---for
Éric Araujoa8132ec2010-12-16 03:53:53 +0000541 example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
Georg Brandlb926ebb2009-09-17 17:14:04 +0000542 resulting in this automatically-generated option description::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543
544 -f FILE, --filename=FILE
545
Georg Brandlb926ebb2009-09-17 17:14:04 +0000546 This is important for more than just saving space, though: the manually
Éric Araujoa8132ec2010-12-16 03:53:53 +0000547 written help text uses the meta-variable ``FILE`` to clue the user in that
548 there's a connection between the semi-formal syntax ``-f FILE`` and the informal
Georg Brandlb926ebb2009-09-17 17:14:04 +0000549 semantic description "write output to FILE". This is a simple but effective
550 way to make your help text a lot clearer and more useful for end users.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000551
Georg Brandl799b3722008-03-25 08:39:10 +0000552.. versionadded:: 2.4
553 Options that have a default value can include ``%default`` in the help
554 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
555 default value. If an option has no default value (or the default value is
556 ``None``), ``%default`` expands to ``none``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000557
Georg Brandl28046022011-02-25 11:01:04 +0000558Grouping Options
559++++++++++++++++
560
Georg Brandlb926ebb2009-09-17 17:14:04 +0000561When dealing with many options, it is convenient to group these options for
562better help output. An :class:`OptionParser` can contain several option groups,
563each of which can contain several options.
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000564
Georg Brandl28046022011-02-25 11:01:04 +0000565An option group is obtained using the class :class:`OptionGroup`:
566
567.. class:: OptionGroup(parser, title, description=None)
568
569 where
570
571 * parser is the :class:`OptionParser` instance the group will be insterted in
572 to
573 * title is the group title
574 * description, optional, is a long description of the group
575
576:class:`OptionGroup` inherits from :class:`OptionContainer` (like
577:class:`OptionParser`) and so the :meth:`add_option` method can be used to add
578an option to the group.
579
580Once all the options are declared, using the :class:`OptionParser` method
581:meth:`add_option_group` the group is added to the previously defined parser.
582
583Continuing with the parser defined in the previous section, adding an
584:class:`OptionGroup` to a parser is easy::
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000585
586 group = OptionGroup(parser, "Dangerous Options",
Georg Brandl7044b112009-01-03 21:04:55 +0000587 "Caution: use these options at your own risk. "
588 "It is believed that some of them bite.")
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000589 group.add_option("-g", action="store_true", help="Group option.")
590 parser.add_option_group(group)
591
Ezio Melotti5129ed32010-01-03 09:01:27 +0000592This would result in the following help output:
593
594.. code-block:: text
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000595
Georg Brandl28046022011-02-25 11:01:04 +0000596 Usage: <yourscript> [options] arg1 arg2
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000597
Georg Brandl28046022011-02-25 11:01:04 +0000598 Options:
599 -h, --help show this help message and exit
600 -v, --verbose make lots of noise [default]
601 -q, --quiet be vewwy quiet (I'm hunting wabbits)
602 -f FILE, --filename=FILE
603 write output to FILE
604 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
605 expert [default: intermediate]
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000606
Georg Brandl28046022011-02-25 11:01:04 +0000607 Dangerous Options:
608 Caution: use these options at your own risk. It is believed that some
609 of them bite.
610
611 -g Group option.
612
Eli Bendersky9efddb62011-11-16 06:01:14 +0200613A bit more complete example might involve using more than one group: still
614extending the previous example::
Georg Brandl28046022011-02-25 11:01:04 +0000615
616 group = OptionGroup(parser, "Dangerous Options",
617 "Caution: use these options at your own risk. "
618 "It is believed that some of them bite.")
619 group.add_option("-g", action="store_true", help="Group option.")
620 parser.add_option_group(group)
621
622 group = OptionGroup(parser, "Debug Options")
623 group.add_option("-d", "--debug", action="store_true",
624 help="Print debug information")
625 group.add_option("-s", "--sql", action="store_true",
626 help="Print all SQL statements executed")
627 group.add_option("-e", action="store_true", help="Print every action done")
628 parser.add_option_group(group)
629
630that results in the following output:
631
632.. code-block:: text
633
634 Usage: <yourscript> [options] arg1 arg2
635
636 Options:
637 -h, --help show this help message and exit
638 -v, --verbose make lots of noise [default]
639 -q, --quiet be vewwy quiet (I'm hunting wabbits)
640 -f FILE, --filename=FILE
641 write output to FILE
642 -m MODE, --mode=MODE interaction mode: novice, intermediate, or expert
643 [default: intermediate]
644
645 Dangerous Options:
646 Caution: use these options at your own risk. It is believed that some
647 of them bite.
648
649 -g Group option.
650
651 Debug Options:
652 -d, --debug Print debug information
653 -s, --sql Print all SQL statements executed
654 -e Print every action done
655
656Another interesting method, in particular when working programmatically with
657option groups is:
658
659.. method:: OptionParser.get_option_group(opt_str)
660
Eli Benderskydedb5022011-07-30 11:12:45 +0300661 Return the :class:`OptionGroup` to which the short or long option
662 string *opt_str* (e.g. ``'-o'`` or ``'--option'``) belongs. If
663 there's no such :class:`OptionGroup`, return ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000664
665.. _optparse-printing-version-string:
666
667Printing a version string
668^^^^^^^^^^^^^^^^^^^^^^^^^
669
670Similar to the brief usage string, :mod:`optparse` can also print a version
671string for your program. You have to supply the string as the ``version``
672argument to OptionParser::
673
674 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
675
Éric Araujoa8132ec2010-12-16 03:53:53 +0000676``%prog`` is expanded just like it is in ``usage``. Apart from that,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000677``version`` can contain anything you like. When you supply it, :mod:`optparse`
Éric Araujoa8132ec2010-12-16 03:53:53 +0000678automatically adds a ``--version`` option to your parser. If it encounters
Georg Brandl8ec7f652007-08-15 14:28:01 +0000679this option on the command line, it expands your ``version`` string (by
Éric Araujoa8132ec2010-12-16 03:53:53 +0000680replacing ``%prog``), prints it to stdout, and exits.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000681
682For example, if your script is called ``/usr/bin/foo``::
683
684 $ /usr/bin/foo --version
685 foo 1.0
686
Ezio Melottib9c3ed42010-01-04 21:43:02 +0000687The following two methods can be used to print and get the ``version`` string:
688
689.. method:: OptionParser.print_version(file=None)
690
691 Print the version message for the current program (``self.version``) to
692 *file* (default stdout). As with :meth:`print_usage`, any occurrence
Éric Araujoa8132ec2010-12-16 03:53:53 +0000693 of ``%prog`` in ``self.version`` is replaced with the name of the current
Ezio Melottib9c3ed42010-01-04 21:43:02 +0000694 program. Does nothing if ``self.version`` is empty or undefined.
695
696.. method:: OptionParser.get_version()
697
698 Same as :meth:`print_version` but returns the version string instead of
699 printing it.
700
Georg Brandl8ec7f652007-08-15 14:28:01 +0000701
702.. _optparse-how-optparse-handles-errors:
703
704How :mod:`optparse` handles errors
705^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
706
707There are two broad classes of errors that :mod:`optparse` has to worry about:
708programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandlb926ebb2009-09-17 17:14:04 +0000709calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
710option attributes, missing option attributes, etc. These are dealt with in the
711usual way: raise an exception (either :exc:`optparse.OptionError` or
712:exc:`TypeError`) and let the program crash.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000713
714Handling user errors is much more important, since they are guaranteed to happen
715no matter how stable your code is. :mod:`optparse` can automatically detect
Éric Araujoa8132ec2010-12-16 03:53:53 +0000716some user errors, such as bad option arguments (passing ``-n 4x`` where
717``-n`` takes an integer argument), missing arguments (``-n`` at the end
718of the command line, where ``-n`` takes an argument of any type). Also,
Georg Brandlb926ebb2009-09-17 17:14:04 +0000719you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl8ec7f652007-08-15 14:28:01 +0000720condition::
721
722 (options, args) = parser.parse_args()
723 [...]
724 if options.a and options.b:
725 parser.error("options -a and -b are mutually exclusive")
726
727In either case, :mod:`optparse` handles the error the same way: it prints the
728program's usage message and an error message to standard error and exits with
729error status 2.
730
Éric Araujoa8132ec2010-12-16 03:53:53 +0000731Consider the first example above, where the user passes ``4x`` to an option
Georg Brandl8ec7f652007-08-15 14:28:01 +0000732that takes an integer::
733
734 $ /usr/bin/foo -n 4x
Georg Brandl28046022011-02-25 11:01:04 +0000735 Usage: foo [options]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000736
737 foo: error: option -n: invalid integer value: '4x'
738
739Or, where the user fails to pass a value at all::
740
741 $ /usr/bin/foo -n
Georg Brandl28046022011-02-25 11:01:04 +0000742 Usage: foo [options]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000743
744 foo: error: -n option requires an argument
745
746:mod:`optparse`\ -generated error messages take care always to mention the
747option involved in the error; be sure to do the same when calling
Georg Brandlb926ebb2009-09-17 17:14:04 +0000748:func:`OptionParser.error` from your application code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000749
Georg Brandl60c0be32008-06-13 13:26:54 +0000750If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Georg Brandl0c9eb432009-06-30 16:35:11 +0000751you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
752and/or :meth:`~OptionParser.error` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000753
754
755.. _optparse-putting-it-all-together:
756
757Putting it all together
758^^^^^^^^^^^^^^^^^^^^^^^
759
760Here's what :mod:`optparse`\ -based scripts usually look like::
761
762 from optparse import OptionParser
763 [...]
764 def main():
765 usage = "usage: %prog [options] arg"
766 parser = OptionParser(usage)
767 parser.add_option("-f", "--file", dest="filename",
768 help="read data from FILENAME")
769 parser.add_option("-v", "--verbose",
770 action="store_true", dest="verbose")
771 parser.add_option("-q", "--quiet",
772 action="store_false", dest="verbose")
773 [...]
774 (options, args) = parser.parse_args()
775 if len(args) != 1:
776 parser.error("incorrect number of arguments")
777 if options.verbose:
778 print "reading %s..." % options.filename
779 [...]
780
781 if __name__ == "__main__":
782 main()
783
Georg Brandl8ec7f652007-08-15 14:28:01 +0000784
785.. _optparse-reference-guide:
786
787Reference Guide
788---------------
789
790
791.. _optparse-creating-parser:
792
793Creating the parser
794^^^^^^^^^^^^^^^^^^^
795
Georg Brandlb926ebb2009-09-17 17:14:04 +0000796The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000797
Georg Brandlb926ebb2009-09-17 17:14:04 +0000798.. class:: OptionParser(...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000799
Georg Brandlb926ebb2009-09-17 17:14:04 +0000800 The OptionParser constructor has no required arguments, but a number of
801 optional keyword arguments. You should always pass them as keyword
802 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000803
804 ``usage`` (default: ``"%prog [options]"``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000805 The usage summary to print when your program is run incorrectly or with a
806 help option. When :mod:`optparse` prints the usage string, it expands
807 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
808 passed that keyword argument). To suppress a usage message, pass the
809 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000810
811 ``option_list`` (default: ``[]``)
812 A list of Option objects to populate the parser with. The options in
Georg Brandlb926ebb2009-09-17 17:14:04 +0000813 ``option_list`` are added after any options in ``standard_option_list`` (a
814 class attribute that may be set by OptionParser subclasses), but before
815 any version or help options. Deprecated; use :meth:`add_option` after
816 creating the parser instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000817
818 ``option_class`` (default: optparse.Option)
819 Class to use when adding options to the parser in :meth:`add_option`.
820
821 ``version`` (default: ``None``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000822 A version string to print when the user supplies a version option. If you
823 supply a true value for ``version``, :mod:`optparse` automatically adds a
Éric Araujoa8132ec2010-12-16 03:53:53 +0000824 version option with the single option string ``--version``. The
825 substring ``%prog`` is expanded the same as for ``usage``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000826
827 ``conflict_handler`` (default: ``"error"``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000828 Specifies what to do when options with conflicting option strings are
829 added to the parser; see section
830 :ref:`optparse-conflicts-between-options`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000831
832 ``description`` (default: ``None``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000833 A paragraph of text giving a brief overview of your program.
834 :mod:`optparse` reformats this paragraph to fit the current terminal width
835 and prints it when the user requests help (after ``usage``, but before the
836 list of options).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000837
Georg Brandlb926ebb2009-09-17 17:14:04 +0000838 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
839 An instance of optparse.HelpFormatter that will be used for printing help
840 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000841 IndentedHelpFormatter and TitledHelpFormatter.
842
843 ``add_help_option`` (default: ``True``)
Éric Araujoa8132ec2010-12-16 03:53:53 +0000844 If true, :mod:`optparse` will add a help option (with option strings ``-h``
845 and ``--help``) to the parser.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000846
847 ``prog``
Éric Araujoa8132ec2010-12-16 03:53:53 +0000848 The string to use when expanding ``%prog`` in ``usage`` and ``version``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000849 instead of ``os.path.basename(sys.argv[0])``.
850
Senthil Kumaran67b4e182010-03-23 08:46:31 +0000851 ``epilog`` (default: ``None``)
852 A paragraph of help text to print after the option help.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000853
854.. _optparse-populating-parser:
855
856Populating the parser
857^^^^^^^^^^^^^^^^^^^^^
858
859There are several ways to populate the parser with options. The preferred way
Georg Brandlb926ebb2009-09-17 17:14:04 +0000860is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl8ec7f652007-08-15 14:28:01 +0000861:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
862
863* pass it an Option instance (as returned by :func:`make_option`)
864
865* pass it any combination of positional and keyword arguments that are
Georg Brandlb926ebb2009-09-17 17:14:04 +0000866 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
867 will create the Option instance for you
Georg Brandl8ec7f652007-08-15 14:28:01 +0000868
869The other alternative is to pass a list of pre-constructed Option instances to
870the OptionParser constructor, as in::
871
872 option_list = [
873 make_option("-f", "--filename",
874 action="store", type="string", dest="filename"),
875 make_option("-q", "--quiet",
876 action="store_false", dest="verbose"),
877 ]
878 parser = OptionParser(option_list=option_list)
879
880(:func:`make_option` is a factory function for creating Option instances;
881currently it is an alias for the Option constructor. A future version of
882:mod:`optparse` may split Option into several classes, and :func:`make_option`
883will pick the right class to instantiate. Do not instantiate Option directly.)
884
885
886.. _optparse-defining-options:
887
888Defining options
889^^^^^^^^^^^^^^^^
890
891Each Option instance represents a set of synonymous command-line option strings,
Éric Araujoa8132ec2010-12-16 03:53:53 +0000892e.g. ``-f`` and ``--file``. You can specify any number of short or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000893long option strings, but you must specify at least one overall option string.
894
Georg Brandlb926ebb2009-09-17 17:14:04 +0000895The canonical way to create an :class:`Option` instance is with the
896:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000897
Georg Brandlb926ebb2009-09-17 17:14:04 +0000898.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000899
Georg Brandlb926ebb2009-09-17 17:14:04 +0000900 To define an option with only a short option string::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000901
Georg Brandlb926ebb2009-09-17 17:14:04 +0000902 parser.add_option("-f", attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000903
Georg Brandlb926ebb2009-09-17 17:14:04 +0000904 And to define an option with only a long option string::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000905
Georg Brandlb926ebb2009-09-17 17:14:04 +0000906 parser.add_option("--foo", attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000907
Georg Brandlb926ebb2009-09-17 17:14:04 +0000908 The keyword arguments define attributes of the new Option object. The most
909 important option attribute is :attr:`~Option.action`, and it largely
910 determines which other attributes are relevant or required. If you pass
911 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
912 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000913
Georg Brandlb926ebb2009-09-17 17:14:04 +0000914 An option's *action* determines what :mod:`optparse` does when it encounters
915 this option on the command-line. The standard option actions hard-coded into
916 :mod:`optparse` are:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000917
Georg Brandlb926ebb2009-09-17 17:14:04 +0000918 ``"store"``
919 store this option's argument (default)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000920
Georg Brandlb926ebb2009-09-17 17:14:04 +0000921 ``"store_const"``
922 store a constant value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000923
Georg Brandlb926ebb2009-09-17 17:14:04 +0000924 ``"store_true"``
925 store a true value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000926
Georg Brandlb926ebb2009-09-17 17:14:04 +0000927 ``"store_false"``
928 store a false value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000929
Georg Brandlb926ebb2009-09-17 17:14:04 +0000930 ``"append"``
931 append this option's argument to a list
Georg Brandl8ec7f652007-08-15 14:28:01 +0000932
Georg Brandlb926ebb2009-09-17 17:14:04 +0000933 ``"append_const"``
934 append a constant value to a list
Georg Brandl8ec7f652007-08-15 14:28:01 +0000935
Georg Brandlb926ebb2009-09-17 17:14:04 +0000936 ``"count"``
937 increment a counter by one
Georg Brandl8ec7f652007-08-15 14:28:01 +0000938
Georg Brandlb926ebb2009-09-17 17:14:04 +0000939 ``"callback"``
940 call a specified function
Georg Brandl8ec7f652007-08-15 14:28:01 +0000941
Georg Brandlb926ebb2009-09-17 17:14:04 +0000942 ``"help"``
943 print a usage message including all options and the documentation for them
Georg Brandl8ec7f652007-08-15 14:28:01 +0000944
Georg Brandlb926ebb2009-09-17 17:14:04 +0000945 (If you don't supply an action, the default is ``"store"``. For this action,
946 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
947 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000948
949As you can see, most actions involve storing or updating a value somewhere.
950:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandlb926ebb2009-09-17 17:14:04 +0000951``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl8ec7f652007-08-15 14:28:01 +0000952arguments (and various other values) are stored as attributes of this object,
Georg Brandlb926ebb2009-09-17 17:14:04 +0000953according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000954
Georg Brandlb926ebb2009-09-17 17:14:04 +0000955For example, when you call ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000956
957 parser.parse_args()
958
959one of the first things :mod:`optparse` does is create the ``options`` object::
960
961 options = Values()
962
Georg Brandlb926ebb2009-09-17 17:14:04 +0000963If one of the options in this parser is defined with ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000964
965 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
966
967and the command-line being parsed includes any of the following::
968
969 -ffoo
970 -f foo
971 --file=foo
972 --file foo
973
Georg Brandlb926ebb2009-09-17 17:14:04 +0000974then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000975
976 options.filename = "foo"
977
Georg Brandlb926ebb2009-09-17 17:14:04 +0000978The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
979as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
980one that makes sense for *all* options.
981
982
983.. _optparse-option-attributes:
984
985Option attributes
986^^^^^^^^^^^^^^^^^
987
988The following option attributes may be passed as keyword arguments to
989:meth:`OptionParser.add_option`. If you pass an option attribute that is not
990relevant to a particular option, or fail to pass a required option attribute,
991:mod:`optparse` raises :exc:`OptionError`.
992
993.. attribute:: Option.action
994
995 (default: ``"store"``)
996
997 Determines :mod:`optparse`'s behaviour when this option is seen on the
998 command line; the available options are documented :ref:`here
999 <optparse-standard-option-actions>`.
1000
1001.. attribute:: Option.type
1002
1003 (default: ``"string"``)
1004
1005 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
1006 the available option types are documented :ref:`here
1007 <optparse-standard-option-types>`.
1008
1009.. attribute:: Option.dest
1010
1011 (default: derived from option strings)
1012
1013 If the option's action implies writing or modifying a value somewhere, this
1014 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
1015 attribute of the ``options`` object that :mod:`optparse` builds as it parses
1016 the command line.
1017
1018.. attribute:: Option.default
1019
1020 The value to use for this option's destination if the option is not seen on
1021 the command line. See also :meth:`OptionParser.set_defaults`.
1022
1023.. attribute:: Option.nargs
1024
1025 (default: 1)
1026
1027 How many arguments of type :attr:`~Option.type` should be consumed when this
1028 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
1029 :attr:`~Option.dest`.
1030
1031.. attribute:: Option.const
1032
1033 For actions that store a constant value, the constant value to store.
1034
1035.. attribute:: Option.choices
1036
1037 For options of type ``"choice"``, the list of strings the user may choose
1038 from.
1039
1040.. attribute:: Option.callback
1041
1042 For options with action ``"callback"``, the callable to call when this option
1043 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1044 arguments passed to the callable.
1045
1046.. attribute:: Option.callback_args
1047 Option.callback_kwargs
1048
1049 Additional positional and keyword arguments to pass to ``callback`` after the
1050 four standard callback arguments.
1051
1052.. attribute:: Option.help
1053
1054 Help text to print for this option when listing all available options after
Éric Araujoa8132ec2010-12-16 03:53:53 +00001055 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
Georg Brandlb926ebb2009-09-17 17:14:04 +00001056 no help text is supplied, the option will be listed without help text. To
1057 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
1058
1059.. attribute:: Option.metavar
1060
1061 (default: derived from option strings)
1062
1063 Stand-in for the option argument(s) to use when printing help text. See
1064 section :ref:`optparse-tutorial` for an example.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001065
1066
1067.. _optparse-standard-option-actions:
1068
1069Standard option actions
1070^^^^^^^^^^^^^^^^^^^^^^^
1071
1072The various option actions all have slightly different requirements and effects.
1073Most actions have several relevant option attributes which you may specify to
1074guide :mod:`optparse`'s behaviour; a few have required attributes, which you
1075must specify for any option using that action.
1076
Georg Brandlb926ebb2009-09-17 17:14:04 +00001077* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1078 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001079
1080 The option must be followed by an argument, which is converted to a value
Georg Brandlb926ebb2009-09-17 17:14:04 +00001081 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1082 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1083 command line; all will be converted according to :attr:`~Option.type` and
1084 stored to :attr:`~Option.dest` as a tuple. See the
1085 :ref:`optparse-standard-option-types` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001086
Georg Brandlb926ebb2009-09-17 17:14:04 +00001087 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1088 defaults to ``"choice"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001089
Georg Brandlb926ebb2009-09-17 17:14:04 +00001090 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001091
Georg Brandlb926ebb2009-09-17 17:14:04 +00001092 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
Éric Araujoa8132ec2010-12-16 03:53:53 +00001093 from the first long option string (e.g., ``--foo-bar`` implies
Georg Brandlb926ebb2009-09-17 17:14:04 +00001094 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
Éric Araujoa8132ec2010-12-16 03:53:53 +00001095 destination from the first short option string (e.g., ``-f`` implies ``f``).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001096
1097 Example::
1098
1099 parser.add_option("-f")
1100 parser.add_option("-p", type="float", nargs=3, dest="point")
1101
Georg Brandlb926ebb2009-09-17 17:14:04 +00001102 As it parses the command line ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001103
1104 -f foo.txt -p 1 -3.5 4 -fbar.txt
1105
Georg Brandlb926ebb2009-09-17 17:14:04 +00001106 :mod:`optparse` will set ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001107
1108 options.f = "foo.txt"
1109 options.point = (1.0, -3.5, 4.0)
1110 options.f = "bar.txt"
1111
Georg Brandlb926ebb2009-09-17 17:14:04 +00001112* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1113 :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001114
Georg Brandlb926ebb2009-09-17 17:14:04 +00001115 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001116
1117 Example::
1118
1119 parser.add_option("-q", "--quiet",
1120 action="store_const", const=0, dest="verbose")
1121 parser.add_option("-v", "--verbose",
1122 action="store_const", const=1, dest="verbose")
1123 parser.add_option("--noisy",
1124 action="store_const", const=2, dest="verbose")
1125
Éric Araujoa8132ec2010-12-16 03:53:53 +00001126 If ``--noisy`` is seen, :mod:`optparse` will set ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001127
1128 options.verbose = 2
1129
Georg Brandlb926ebb2009-09-17 17:14:04 +00001130* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001131
Georg Brandlb926ebb2009-09-17 17:14:04 +00001132 A special case of ``"store_const"`` that stores a true value to
1133 :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001134
Georg Brandlb926ebb2009-09-17 17:14:04 +00001135* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001136
Georg Brandlb926ebb2009-09-17 17:14:04 +00001137 Like ``"store_true"``, but stores a false value.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001138
1139 Example::
1140
1141 parser.add_option("--clobber", action="store_true", dest="clobber")
1142 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1143
Georg Brandlb926ebb2009-09-17 17:14:04 +00001144* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1145 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001146
1147 The option must be followed by an argument, which is appended to the list in
Georg Brandlb926ebb2009-09-17 17:14:04 +00001148 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1149 supplied, an empty list is automatically created when :mod:`optparse` first
1150 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1151 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1152 is appended to :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001153
Georg Brandlb926ebb2009-09-17 17:14:04 +00001154 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1155 for the ``"store"`` action.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001156
1157 Example::
1158
1159 parser.add_option("-t", "--tracks", action="append", type="int")
1160
Éric Araujoa8132ec2010-12-16 03:53:53 +00001161 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
Georg Brandl8ec7f652007-08-15 14:28:01 +00001162 of::
1163
1164 options.tracks = []
1165 options.tracks.append(int("3"))
1166
Éric Araujoa8132ec2010-12-16 03:53:53 +00001167 If, a little later on, ``--tracks=4`` is seen, it does::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001168
1169 options.tracks.append(int("4"))
1170
Georg Brandlb926ebb2009-09-17 17:14:04 +00001171* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1172 :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001173
Georg Brandlb926ebb2009-09-17 17:14:04 +00001174 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1175 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1176 ``None``, and an empty list is automatically created the first time the option
1177 is encountered.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001178
Georg Brandlb926ebb2009-09-17 17:14:04 +00001179* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001180
Georg Brandlb926ebb2009-09-17 17:14:04 +00001181 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1182 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1183 first time.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001184
1185 Example::
1186
1187 parser.add_option("-v", action="count", dest="verbosity")
1188
Éric Araujoa8132ec2010-12-16 03:53:53 +00001189 The first time ``-v`` is seen on the command line, :mod:`optparse` does the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001190 equivalent of::
1191
1192 options.verbosity = 0
1193 options.verbosity += 1
1194
Éric Araujoa8132ec2010-12-16 03:53:53 +00001195 Every subsequent occurrence of ``-v`` results in ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001196
1197 options.verbosity += 1
1198
Georg Brandlb926ebb2009-09-17 17:14:04 +00001199* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1200 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1201 :attr:`~Option.callback_kwargs`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001202
Georg Brandlb926ebb2009-09-17 17:14:04 +00001203 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001204
1205 func(option, opt_str, value, parser, *args, **kwargs)
1206
1207 See section :ref:`optparse-option-callbacks` for more detail.
1208
Georg Brandlb926ebb2009-09-17 17:14:04 +00001209* ``"help"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001210
Georg Brandlb926ebb2009-09-17 17:14:04 +00001211 Prints a complete help message for all the options in the current option
1212 parser. The help message is constructed from the ``usage`` string passed to
1213 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1214 option.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001215
Georg Brandlb926ebb2009-09-17 17:14:04 +00001216 If no :attr:`~Option.help` string is supplied for an option, it will still be
1217 listed in the help message. To omit an option entirely, use the special value
1218 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001219
Georg Brandlb926ebb2009-09-17 17:14:04 +00001220 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1221 OptionParsers, so you do not normally need to create one.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001222
1223 Example::
1224
1225 from optparse import OptionParser, SUPPRESS_HELP
1226
Georg Brandl718b2212009-09-16 13:11:06 +00001227 # usually, a help option is added automatically, but that can
1228 # be suppressed using the add_help_option argument
1229 parser = OptionParser(add_help_option=False)
1230
Georg Brandld7226ff2009-09-16 13:06:22 +00001231 parser.add_option("-h", "--help", action="help")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001232 parser.add_option("-v", action="store_true", dest="verbose",
1233 help="Be moderately verbose")
1234 parser.add_option("--file", dest="filename",
Georg Brandld7226ff2009-09-16 13:06:22 +00001235 help="Input file to read data from")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001236 parser.add_option("--secret", help=SUPPRESS_HELP)
1237
Éric Araujoa8132ec2010-12-16 03:53:53 +00001238 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
Georg Brandlb926ebb2009-09-17 17:14:04 +00001239 it will print something like the following help message to stdout (assuming
Ezio Melotti5129ed32010-01-03 09:01:27 +00001240 ``sys.argv[0]`` is ``"foo.py"``):
1241
1242 .. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +00001243
Georg Brandl28046022011-02-25 11:01:04 +00001244 Usage: foo.py [options]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001245
Georg Brandl28046022011-02-25 11:01:04 +00001246 Options:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001247 -h, --help Show this help message and exit
1248 -v Be moderately verbose
1249 --file=FILENAME Input file to read data from
1250
1251 After printing the help message, :mod:`optparse` terminates your process with
1252 ``sys.exit(0)``.
1253
Georg Brandlb926ebb2009-09-17 17:14:04 +00001254* ``"version"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001255
Georg Brandlb926ebb2009-09-17 17:14:04 +00001256 Prints the version number supplied to the OptionParser to stdout and exits.
1257 The version number is actually formatted and printed by the
1258 ``print_version()`` method of OptionParser. Generally only relevant if the
1259 ``version`` argument is supplied to the OptionParser constructor. As with
1260 :attr:`~Option.help` options, you will rarely create ``version`` options,
1261 since :mod:`optparse` automatically adds them when needed.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001262
1263
1264.. _optparse-standard-option-types:
1265
1266Standard option types
1267^^^^^^^^^^^^^^^^^^^^^
1268
Georg Brandlb926ebb2009-09-17 17:14:04 +00001269:mod:`optparse` has six built-in option types: ``"string"``, ``"int"``,
1270``"long"``, ``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1271option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001272
1273Arguments to string options are not checked or converted in any way: the text on
1274the command line is stored in the destination (or passed to the callback) as-is.
1275
Georg Brandlb926ebb2009-09-17 17:14:04 +00001276Integer arguments (type ``"int"`` or ``"long"``) are parsed as follows:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001277
1278* if the number starts with ``0x``, it is parsed as a hexadecimal number
1279
1280* if the number starts with ``0``, it is parsed as an octal number
1281
Georg Brandl97ca5832007-09-24 17:55:47 +00001282* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl8ec7f652007-08-15 14:28:01 +00001283
1284* otherwise, the number is parsed as a decimal number
1285
1286
Georg Brandlb926ebb2009-09-17 17:14:04 +00001287The conversion is done by calling either :func:`int` or :func:`long` with the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001288appropriate base (2, 8, 10, or 16). If this fails, so will :mod:`optparse`,
1289although with a more useful error message.
1290
Georg Brandlb926ebb2009-09-17 17:14:04 +00001291``"float"`` and ``"complex"`` option arguments are converted directly with
1292:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001293
Georg Brandlb926ebb2009-09-17 17:14:04 +00001294``"choice"`` options are a subtype of ``"string"`` options. The
Georg Brandl35e7a8f2010-10-06 10:41:31 +00001295:attr:`~Option.choices` option attribute (a sequence of strings) defines the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001296set of allowed option arguments. :func:`optparse.check_choice` compares
1297user-supplied option arguments against this master list and raises
1298:exc:`OptionValueError` if an invalid string is given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001299
1300
1301.. _optparse-parsing-arguments:
1302
1303Parsing arguments
1304^^^^^^^^^^^^^^^^^
1305
1306The whole point of creating and populating an OptionParser is to call its
1307:meth:`parse_args` method::
1308
1309 (options, args) = parser.parse_args(args=None, values=None)
1310
1311where the input parameters are
1312
1313``args``
1314 the list of arguments to process (default: ``sys.argv[1:]``)
1315
1316``values``
Georg Brandl0347c712010-08-01 19:02:09 +00001317 a :class:`optparse.Values` object to store option arguments in (default: a
1318 new instance of :class:`Values`) -- if you give an existing object, the
1319 option defaults will not be initialized on it
Georg Brandl8ec7f652007-08-15 14:28:01 +00001320
1321and the return values are
1322
1323``options``
Georg Brandl8514b852009-09-01 08:06:03 +00001324 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl8ec7f652007-08-15 14:28:01 +00001325 instance created by :mod:`optparse`
1326
1327``args``
1328 the leftover positional arguments after all options have been processed
1329
1330The most common usage is to supply neither keyword argument. If you supply
Georg Brandlb926ebb2009-09-17 17:14:04 +00001331``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl8ec7f652007-08-15 14:28:01 +00001332for every option argument stored to an option destination) and returned by
1333:meth:`parse_args`.
1334
1335If :meth:`parse_args` encounters any errors in the argument list, it calls the
1336OptionParser's :meth:`error` method with an appropriate end-user error message.
1337This ultimately terminates your process with an exit status of 2 (the
1338traditional Unix exit status for command-line errors).
1339
1340
1341.. _optparse-querying-manipulating-option-parser:
1342
1343Querying and manipulating your option parser
1344^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1345
Georg Brandlb926ebb2009-09-17 17:14:04 +00001346The default behavior of the option parser can be customized slightly, and you
1347can also poke around your option parser and see what's there. OptionParser
1348provides several methods to help you out:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001349
Georg Brandlb926ebb2009-09-17 17:14:04 +00001350.. method:: OptionParser.disable_interspersed_args()
Georg Brandl7842a412009-09-17 16:26:06 +00001351
Éric Araujoa8132ec2010-12-16 03:53:53 +00001352 Set parsing to stop on the first non-option. For example, if ``-a`` and
1353 ``-b`` are both simple options that take no arguments, :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00001354 normally accepts this syntax::
Georg Brandl7842a412009-09-17 16:26:06 +00001355
Georg Brandlb926ebb2009-09-17 17:14:04 +00001356 prog -a arg1 -b arg2
Georg Brandl7842a412009-09-17 16:26:06 +00001357
Georg Brandlb926ebb2009-09-17 17:14:04 +00001358 and treats it as equivalent to ::
Georg Brandl7842a412009-09-17 16:26:06 +00001359
Georg Brandlb926ebb2009-09-17 17:14:04 +00001360 prog -a -b arg1 arg2
Georg Brandl7842a412009-09-17 16:26:06 +00001361
Georg Brandlb926ebb2009-09-17 17:14:04 +00001362 To disable this feature, call :meth:`disable_interspersed_args`. This
1363 restores traditional Unix syntax, where option parsing stops with the first
1364 non-option argument.
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001365
Georg Brandlb926ebb2009-09-17 17:14:04 +00001366 Use this if you have a command processor which runs another command which has
1367 options of its own and you want to make sure these options don't get
1368 confused. For example, each command might have a different set of options.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001369
Georg Brandlb926ebb2009-09-17 17:14:04 +00001370.. method:: OptionParser.enable_interspersed_args()
1371
1372 Set parsing to not stop on the first non-option, allowing interspersing
1373 switches with command arguments. This is the default behavior.
1374
1375.. method:: OptionParser.get_option(opt_str)
1376
1377 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl8ec7f652007-08-15 14:28:01 +00001378 no options have that option string.
1379
Georg Brandlb926ebb2009-09-17 17:14:04 +00001380.. method:: OptionParser.has_option(opt_str)
1381
1382 Return true if the OptionParser has an option with option string *opt_str*
Éric Araujoa8132ec2010-12-16 03:53:53 +00001383 (e.g., ``-q`` or ``--verbose``).
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001384
Georg Brandlb926ebb2009-09-17 17:14:04 +00001385.. method:: OptionParser.remove_option(opt_str)
1386
1387 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1388 option is removed. If that option provided any other option strings, all of
1389 those option strings become invalid. If *opt_str* does not occur in any
1390 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001391
1392
1393.. _optparse-conflicts-between-options:
1394
1395Conflicts between options
1396^^^^^^^^^^^^^^^^^^^^^^^^^
1397
1398If you're not careful, it's easy to define options with conflicting option
1399strings::
1400
1401 parser.add_option("-n", "--dry-run", ...)
1402 [...]
1403 parser.add_option("-n", "--noisy", ...)
1404
1405(This is particularly true if you've defined your own OptionParser subclass with
1406some standard options.)
1407
1408Every time you add an option, :mod:`optparse` checks for conflicts with existing
1409options. If it finds any, it invokes the current conflict-handling mechanism.
1410You can set the conflict-handling mechanism either in the constructor::
1411
1412 parser = OptionParser(..., conflict_handler=handler)
1413
1414or with a separate call::
1415
1416 parser.set_conflict_handler(handler)
1417
1418The available conflict handlers are:
1419
Georg Brandlb926ebb2009-09-17 17:14:04 +00001420 ``"error"`` (default)
1421 assume option conflicts are a programming error and raise
1422 :exc:`OptionConflictError`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001423
Georg Brandlb926ebb2009-09-17 17:14:04 +00001424 ``"resolve"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001425 resolve option conflicts intelligently (see below)
1426
1427
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001428As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl8ec7f652007-08-15 14:28:01 +00001429intelligently and add conflicting options to it::
1430
1431 parser = OptionParser(conflict_handler="resolve")
1432 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1433 parser.add_option("-n", "--noisy", ..., help="be noisy")
1434
1435At this point, :mod:`optparse` detects that a previously-added option is already
Éric Araujoa8132ec2010-12-16 03:53:53 +00001436using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1437it resolves the situation by removing ``-n`` from the earlier option's list of
1438option strings. Now ``--dry-run`` is the only way for the user to activate
Georg Brandl8ec7f652007-08-15 14:28:01 +00001439that option. If the user asks for help, the help message will reflect that::
1440
Georg Brandl28046022011-02-25 11:01:04 +00001441 Options:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001442 --dry-run do no harm
1443 [...]
1444 -n, --noisy be noisy
1445
1446It's possible to whittle away the option strings for a previously-added option
1447until there are none left, and the user has no way of invoking that option from
1448the command-line. In that case, :mod:`optparse` removes that option completely,
1449so it doesn't show up in help text or anywhere else. Carrying on with our
1450existing OptionParser::
1451
1452 parser.add_option("--dry-run", ..., help="new dry-run option")
1453
Éric Araujoa8132ec2010-12-16 03:53:53 +00001454At this point, the original ``-n``/``--dry-run`` option is no longer
Georg Brandl8ec7f652007-08-15 14:28:01 +00001455accessible, so :mod:`optparse` removes it, leaving this help text::
1456
Georg Brandl28046022011-02-25 11:01:04 +00001457 Options:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001458 [...]
1459 -n, --noisy be noisy
1460 --dry-run new dry-run option
1461
1462
1463.. _optparse-cleanup:
1464
1465Cleanup
1466^^^^^^^
1467
1468OptionParser instances have several cyclic references. This should not be a
1469problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandlb926ebb2009-09-17 17:14:04 +00001470references explicitly by calling :meth:`~OptionParser.destroy` on your
1471OptionParser once you are done with it. This is particularly useful in
1472long-running applications where large object graphs are reachable from your
1473OptionParser.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001474
1475
1476.. _optparse-other-methods:
1477
1478Other methods
1479^^^^^^^^^^^^^
1480
1481OptionParser supports several other public methods:
1482
Georg Brandlb926ebb2009-09-17 17:14:04 +00001483.. method:: OptionParser.set_usage(usage)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001484
Georg Brandlb926ebb2009-09-17 17:14:04 +00001485 Set the usage string according to the rules described above for the ``usage``
1486 constructor keyword argument. Passing ``None`` sets the default usage
1487 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001488
Ezio Melottib9c3ed42010-01-04 21:43:02 +00001489.. method:: OptionParser.print_usage(file=None)
1490
1491 Print the usage message for the current program (``self.usage``) to *file*
Éric Araujoa8132ec2010-12-16 03:53:53 +00001492 (default stdout). Any occurrence of the string ``%prog`` in ``self.usage``
Ezio Melottib9c3ed42010-01-04 21:43:02 +00001493 is replaced with the name of the current program. Does nothing if
1494 ``self.usage`` is empty or not defined.
1495
1496.. method:: OptionParser.get_usage()
1497
1498 Same as :meth:`print_usage` but returns the usage string instead of
1499 printing it.
1500
Georg Brandlb926ebb2009-09-17 17:14:04 +00001501.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001502
Georg Brandlb926ebb2009-09-17 17:14:04 +00001503 Set default values for several option destinations at once. Using
1504 :meth:`set_defaults` is the preferred way to set default values for options,
1505 since multiple options can share the same destination. For example, if
1506 several "mode" options all set the same destination, any one of them can set
1507 the default, and the last one wins::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001508
Georg Brandlb926ebb2009-09-17 17:14:04 +00001509 parser.add_option("--advanced", action="store_const",
1510 dest="mode", const="advanced",
1511 default="novice") # overridden below
1512 parser.add_option("--novice", action="store_const",
1513 dest="mode", const="novice",
1514 default="advanced") # overrides above setting
Georg Brandl8ec7f652007-08-15 14:28:01 +00001515
Georg Brandlb926ebb2009-09-17 17:14:04 +00001516 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001517
Georg Brandlb926ebb2009-09-17 17:14:04 +00001518 parser.set_defaults(mode="advanced")
1519 parser.add_option("--advanced", action="store_const",
1520 dest="mode", const="advanced")
1521 parser.add_option("--novice", action="store_const",
1522 dest="mode", const="novice")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001523
Georg Brandl8ec7f652007-08-15 14:28:01 +00001524
1525.. _optparse-option-callbacks:
1526
1527Option Callbacks
1528----------------
1529
1530When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1531needs, you have two choices: extend :mod:`optparse` or define a callback option.
1532Extending :mod:`optparse` is more general, but overkill for a lot of simple
1533cases. Quite often a simple callback is all you need.
1534
1535There are two steps to defining a callback option:
1536
Georg Brandlb926ebb2009-09-17 17:14:04 +00001537* define the option itself using the ``"callback"`` action
Georg Brandl8ec7f652007-08-15 14:28:01 +00001538
1539* write the callback; this is a function (or method) that takes at least four
1540 arguments, as described below
1541
1542
1543.. _optparse-defining-callback-option:
1544
1545Defining a callback option
1546^^^^^^^^^^^^^^^^^^^^^^^^^^
1547
1548As always, the easiest way to define a callback option is by using the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001549:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1550only option attribute you must specify is ``callback``, the function to call::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001551
1552 parser.add_option("-c", action="callback", callback=my_callback)
1553
1554``callback`` is a function (or other callable object), so you must have already
1555defined ``my_callback()`` when you create this callback option. In this simple
Éric Araujoa8132ec2010-12-16 03:53:53 +00001556case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001557which usually means that the option takes no arguments---the mere presence of
Éric Araujoa8132ec2010-12-16 03:53:53 +00001558``-c`` on the command-line is all it needs to know. In some
Georg Brandl8ec7f652007-08-15 14:28:01 +00001559circumstances, though, you might want your callback to consume an arbitrary
1560number of command-line arguments. This is where writing callbacks gets tricky;
1561it's covered later in this section.
1562
1563:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandlb926ebb2009-09-17 17:14:04 +00001564will only pass additional arguments if you specify them via
1565:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1566minimal callback function signature is::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001567
1568 def my_callback(option, opt, value, parser):
1569
1570The four arguments to a callback are described below.
1571
1572There are several other option attributes that you can supply when you define a
1573callback option:
1574
Georg Brandlb926ebb2009-09-17 17:14:04 +00001575:attr:`~Option.type`
1576 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1577 instructs :mod:`optparse` to consume one argument and convert it to
1578 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1579 though, :mod:`optparse` passes it to your callback function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001580
Georg Brandlb926ebb2009-09-17 17:14:04 +00001581:attr:`~Option.nargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001582 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandlb926ebb2009-09-17 17:14:04 +00001583 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1584 :attr:`~Option.type`. It then passes a tuple of converted values to your
1585 callback.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001586
Georg Brandlb926ebb2009-09-17 17:14:04 +00001587:attr:`~Option.callback_args`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001588 a tuple of extra positional arguments to pass to the callback
1589
Georg Brandlb926ebb2009-09-17 17:14:04 +00001590:attr:`~Option.callback_kwargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001591 a dictionary of extra keyword arguments to pass to the callback
1592
1593
1594.. _optparse-how-callbacks-called:
1595
1596How callbacks are called
1597^^^^^^^^^^^^^^^^^^^^^^^^
1598
1599All callbacks are called as follows::
1600
1601 func(option, opt_str, value, parser, *args, **kwargs)
1602
1603where
1604
1605``option``
1606 is the Option instance that's calling the callback
1607
1608``opt_str``
1609 is the option string seen on the command-line that's triggering the callback.
Georg Brandlb926ebb2009-09-17 17:14:04 +00001610 (If an abbreviated long option was used, ``opt_str`` will be the full,
Éric Araujoa8132ec2010-12-16 03:53:53 +00001611 canonical option string---e.g. if the user puts ``--foo`` on the
1612 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
Georg Brandlb926ebb2009-09-17 17:14:04 +00001613 ``"--foobar"``.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001614
1615``value``
1616 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandlb926ebb2009-09-17 17:14:04 +00001617 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1618 the type implied by the option's type. If :attr:`~Option.type` for this option is
1619 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001620 > 1, ``value`` will be a tuple of values of the appropriate type.
1621
1622``parser``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001623 is the OptionParser instance driving the whole thing, mainly useful because
1624 you can access some other interesting data through its instance attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001625
1626 ``parser.largs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001627 the current list of leftover arguments, ie. arguments that have been
1628 consumed but are neither options nor option arguments. Feel free to modify
1629 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1630 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001631
1632 ``parser.rargs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001633 the current list of remaining arguments, ie. with ``opt_str`` and
1634 ``value`` (if applicable) removed, and only the arguments following them
1635 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1636 arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001637
1638 ``parser.values``
1639 the object where option values are by default stored (an instance of
Georg Brandlb926ebb2009-09-17 17:14:04 +00001640 optparse.OptionValues). This lets callbacks use the same mechanism as the
1641 rest of :mod:`optparse` for storing option values; you don't need to mess
1642 around with globals or closures. You can also access or modify the
1643 value(s) of any options already encountered on the command-line.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001644
1645``args``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001646 is a tuple of arbitrary positional arguments supplied via the
1647 :attr:`~Option.callback_args` option attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001648
1649``kwargs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001650 is a dictionary of arbitrary keyword arguments supplied via
1651 :attr:`~Option.callback_kwargs`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001652
1653
1654.. _optparse-raising-errors-in-callback:
1655
1656Raising errors in a callback
1657^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1658
Georg Brandlb926ebb2009-09-17 17:14:04 +00001659The callback function should raise :exc:`OptionValueError` if there are any
1660problems with the option or its argument(s). :mod:`optparse` catches this and
1661terminates the program, printing the error message you supply to stderr. Your
1662message should be clear, concise, accurate, and mention the option at fault.
1663Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001664
1665
1666.. _optparse-callback-example-1:
1667
1668Callback example 1: trivial callback
1669^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1670
1671Here's an example of a callback option that takes no arguments, and simply
1672records that the option was seen::
1673
1674 def record_foo_seen(option, opt_str, value, parser):
Georg Brandl253a29f2009-02-05 11:33:21 +00001675 parser.values.saw_foo = True
Georg Brandl8ec7f652007-08-15 14:28:01 +00001676
1677 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1678
Georg Brandlb926ebb2009-09-17 17:14:04 +00001679Of course, you could do that with the ``"store_true"`` action.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001680
1681
1682.. _optparse-callback-example-2:
1683
1684Callback example 2: check option order
1685^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1686
Éric Araujoa8132ec2010-12-16 03:53:53 +00001687Here's a slightly more interesting example: record the fact that ``-a`` is
1688seen, but blow up if it comes after ``-b`` in the command-line. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001689
1690 def check_order(option, opt_str, value, parser):
1691 if parser.values.b:
1692 raise OptionValueError("can't use -a after -b")
1693 parser.values.a = 1
1694 [...]
1695 parser.add_option("-a", action="callback", callback=check_order)
1696 parser.add_option("-b", action="store_true", dest="b")
1697
1698
1699.. _optparse-callback-example-3:
1700
1701Callback example 3: check option order (generalized)
1702^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1703
1704If you want to re-use this callback for several similar options (set a flag, but
Éric Araujoa8132ec2010-12-16 03:53:53 +00001705blow up if ``-b`` has already been seen), it needs a bit of work: the error
Georg Brandl8ec7f652007-08-15 14:28:01 +00001706message and the flag that it sets must be generalized. ::
1707
1708 def check_order(option, opt_str, value, parser):
1709 if parser.values.b:
1710 raise OptionValueError("can't use %s after -b" % opt_str)
1711 setattr(parser.values, option.dest, 1)
1712 [...]
1713 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1714 parser.add_option("-b", action="store_true", dest="b")
1715 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1716
1717
1718.. _optparse-callback-example-4:
1719
1720Callback example 4: check arbitrary condition
1721^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1722
1723Of course, you could put any condition in there---you're not limited to checking
1724the values of already-defined options. For example, if you have options that
1725should not be called when the moon is full, all you have to do is this::
1726
1727 def check_moon(option, opt_str, value, parser):
1728 if is_moon_full():
1729 raise OptionValueError("%s option invalid when moon is full"
1730 % opt_str)
1731 setattr(parser.values, option.dest, 1)
1732 [...]
1733 parser.add_option("--foo",
1734 action="callback", callback=check_moon, dest="foo")
1735
1736(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1737
1738
1739.. _optparse-callback-example-5:
1740
1741Callback example 5: fixed arguments
1742^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1743
1744Things get slightly more interesting when you define callback options that take
1745a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandlb926ebb2009-09-17 17:14:04 +00001746is similar to defining a ``"store"`` or ``"append"`` option: if you define
1747:attr:`~Option.type`, then the option takes one argument that must be
1748convertible to that type; if you further define :attr:`~Option.nargs`, then the
1749option takes :attr:`~Option.nargs` arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001750
Georg Brandlb926ebb2009-09-17 17:14:04 +00001751Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001752
1753 def store_value(option, opt_str, value, parser):
1754 setattr(parser.values, option.dest, value)
1755 [...]
1756 parser.add_option("--foo",
1757 action="callback", callback=store_value,
1758 type="int", nargs=3, dest="foo")
1759
1760Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1761them to integers for you; all you have to do is store them. (Or whatever;
1762obviously you don't need a callback for this example.)
1763
1764
1765.. _optparse-callback-example-6:
1766
1767Callback example 6: variable arguments
1768^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1769
1770Things get hairy when you want an option to take a variable number of arguments.
1771For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1772built-in capabilities for it. And you have to deal with certain intricacies of
1773conventional Unix command-line parsing that :mod:`optparse` normally handles for
1774you. In particular, callbacks should implement the conventional rules for bare
Éric Araujoa8132ec2010-12-16 03:53:53 +00001775``--`` and ``-`` arguments:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001776
Éric Araujoa8132ec2010-12-16 03:53:53 +00001777* either ``--`` or ``-`` can be option arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +00001778
Éric Araujoa8132ec2010-12-16 03:53:53 +00001779* bare ``--`` (if not the argument to some option): halt command-line
1780 processing and discard the ``--``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001781
Éric Araujoa8132ec2010-12-16 03:53:53 +00001782* bare ``-`` (if not the argument to some option): halt command-line
1783 processing but keep the ``-`` (append it to ``parser.largs``)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001784
1785If you want an option that takes a variable number of arguments, there are
1786several subtle, tricky issues to worry about. The exact implementation you
1787choose will be based on which trade-offs you're willing to make for your
1788application (which is why :mod:`optparse` doesn't support this sort of thing
1789directly).
1790
1791Nevertheless, here's a stab at a callback for an option with variable
1792arguments::
1793
Georg Brandl60b2e382008-12-15 09:07:39 +00001794 def vararg_callback(option, opt_str, value, parser):
1795 assert value is None
1796 value = []
Georg Brandl8ec7f652007-08-15 14:28:01 +00001797
Georg Brandl60b2e382008-12-15 09:07:39 +00001798 def floatable(str):
1799 try:
1800 float(str)
1801 return True
1802 except ValueError:
1803 return False
Georg Brandl8ec7f652007-08-15 14:28:01 +00001804
Georg Brandl60b2e382008-12-15 09:07:39 +00001805 for arg in parser.rargs:
1806 # stop on --foo like options
1807 if arg[:2] == "--" and len(arg) > 2:
1808 break
1809 # stop on -a, but not on -3 or -3.0
1810 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1811 break
1812 value.append(arg)
1813
1814 del parser.rargs[:len(value)]
Georg Brandl174fbe72009-02-05 10:30:57 +00001815 setattr(parser.values, option.dest, value)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001816
1817 [...]
Andrew M. Kuchling810f8072008-09-06 13:04:02 +00001818 parser.add_option("-c", "--callback", dest="vararg_attr",
Benjamin Petersonc8590942008-04-23 20:38:06 +00001819 action="callback", callback=vararg_callback)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001820
Georg Brandl8ec7f652007-08-15 14:28:01 +00001821
1822.. _optparse-extending-optparse:
1823
1824Extending :mod:`optparse`
1825-------------------------
1826
1827Since the two major controlling factors in how :mod:`optparse` interprets
1828command-line options are the action and type of each option, the most likely
1829direction of extension is to add new actions and new types.
1830
1831
1832.. _optparse-adding-new-types:
1833
1834Adding new types
1835^^^^^^^^^^^^^^^^
1836
1837To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandlb926ebb2009-09-17 17:14:04 +00001838:class:`Option` class. This class has a couple of attributes that define
1839:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001840
Georg Brandlb926ebb2009-09-17 17:14:04 +00001841.. attribute:: Option.TYPES
Georg Brandl8ec7f652007-08-15 14:28:01 +00001842
Georg Brandlb926ebb2009-09-17 17:14:04 +00001843 A tuple of type names; in your subclass, simply define a new tuple
1844 :attr:`TYPES` that builds on the standard one.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001845
Georg Brandlb926ebb2009-09-17 17:14:04 +00001846.. attribute:: Option.TYPE_CHECKER
Georg Brandl8ec7f652007-08-15 14:28:01 +00001847
Georg Brandlb926ebb2009-09-17 17:14:04 +00001848 A dictionary mapping type names to type-checking functions. A type-checking
1849 function has the following signature::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001850
Georg Brandlb926ebb2009-09-17 17:14:04 +00001851 def check_mytype(option, opt, value)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001852
Georg Brandlb926ebb2009-09-17 17:14:04 +00001853 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
Éric Araujoa8132ec2010-12-16 03:53:53 +00001854 (e.g., ``-f``), and ``value`` is the string from the command line that must
Georg Brandlb926ebb2009-09-17 17:14:04 +00001855 be checked and converted to your desired type. ``check_mytype()`` should
1856 return an object of the hypothetical type ``mytype``. The value returned by
1857 a type-checking function will wind up in the OptionValues instance returned
1858 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1859 ``value`` parameter.
1860
1861 Your type-checking function should raise :exc:`OptionValueError` if it
1862 encounters any problems. :exc:`OptionValueError` takes a single string
1863 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1864 method, which in turn prepends the program name and the string ``"error:"``
1865 and prints everything to stderr before terminating the process.
1866
1867Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl8ec7f652007-08-15 14:28:01 +00001868parse Python-style complex numbers on the command line. (This is even sillier
1869than it used to be, because :mod:`optparse` 1.3 added built-in support for
1870complex numbers, but never mind.)
1871
1872First, the necessary imports::
1873
1874 from copy import copy
1875 from optparse import Option, OptionValueError
1876
1877You need to define your type-checker first, since it's referred to later (in the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001878:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001879
1880 def check_complex(option, opt, value):
1881 try:
1882 return complex(value)
1883 except ValueError:
1884 raise OptionValueError(
1885 "option %s: invalid complex value: %r" % (opt, value))
1886
1887Finally, the Option subclass::
1888
1889 class MyOption (Option):
1890 TYPES = Option.TYPES + ("complex",)
1891 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1892 TYPE_CHECKER["complex"] = check_complex
1893
1894(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandlb926ebb2009-09-17 17:14:04 +00001895up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1896Option class. This being Python, nothing stops you from doing that except good
1897manners and common sense.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001898
1899That's it! Now you can write a script that uses the new option type just like
1900any other :mod:`optparse`\ -based script, except you have to instruct your
1901OptionParser to use MyOption instead of Option::
1902
1903 parser = OptionParser(option_class=MyOption)
1904 parser.add_option("-c", type="complex")
1905
1906Alternately, you can build your own option list and pass it to OptionParser; if
1907you don't use :meth:`add_option` in the above way, you don't need to tell
1908OptionParser which option class to use::
1909
1910 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1911 parser = OptionParser(option_list=option_list)
1912
1913
1914.. _optparse-adding-new-actions:
1915
1916Adding new actions
1917^^^^^^^^^^^^^^^^^^
1918
1919Adding new actions is a bit trickier, because you have to understand that
1920:mod:`optparse` has a couple of classifications for actions:
1921
1922"store" actions
1923 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001924 current OptionValues instance; these options require a :attr:`~Option.dest`
1925 attribute to be supplied to the Option constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001926
1927"typed" actions
Georg Brandlb926ebb2009-09-17 17:14:04 +00001928 actions that take a value from the command line and expect it to be of a
1929 certain type; or rather, a string that can be converted to a certain type.
1930 These options require a :attr:`~Option.type` attribute to the Option
1931 constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001932
Georg Brandlb926ebb2009-09-17 17:14:04 +00001933These are overlapping sets: some default "store" actions are ``"store"``,
1934``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1935actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001936
1937When you add an action, you need to categorize it by listing it in at least one
1938of the following class attributes of Option (all are lists of strings):
1939
Georg Brandlb926ebb2009-09-17 17:14:04 +00001940.. attribute:: Option.ACTIONS
Georg Brandl8ec7f652007-08-15 14:28:01 +00001941
Georg Brandlb926ebb2009-09-17 17:14:04 +00001942 All actions must be listed in ACTIONS.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001943
Georg Brandlb926ebb2009-09-17 17:14:04 +00001944.. attribute:: Option.STORE_ACTIONS
Georg Brandl8ec7f652007-08-15 14:28:01 +00001945
Georg Brandlb926ebb2009-09-17 17:14:04 +00001946 "store" actions are additionally listed here.
1947
1948.. attribute:: Option.TYPED_ACTIONS
1949
1950 "typed" actions are additionally listed here.
1951
1952.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1953
1954 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl8ec7f652007-08-15 14:28:01 +00001955 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00001956 assigns the default type, ``"string"``, to options with no explicit type
1957 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001958
1959In order to actually implement your new action, you must override Option's
1960:meth:`take_action` method and add a case that recognizes your action.
1961
Georg Brandlb926ebb2009-09-17 17:14:04 +00001962For example, let's add an ``"extend"`` action. This is similar to the standard
1963``"append"`` action, but instead of taking a single value from the command-line
1964and appending it to an existing list, ``"extend"`` will take multiple values in
1965a single comma-delimited string, and extend an existing list with them. That
Éric Araujoa8132ec2010-12-16 03:53:53 +00001966is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
Georg Brandlb926ebb2009-09-17 17:14:04 +00001967line ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001968
1969 --names=foo,bar --names blah --names ding,dong
1970
1971would result in a list ::
1972
1973 ["foo", "bar", "blah", "ding", "dong"]
1974
1975Again we define a subclass of Option::
1976
Ezio Melotti5129ed32010-01-03 09:01:27 +00001977 class MyOption(Option):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001978
1979 ACTIONS = Option.ACTIONS + ("extend",)
1980 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1981 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1982 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1983
1984 def take_action(self, action, dest, opt, value, values, parser):
1985 if action == "extend":
1986 lvalue = value.split(",")
1987 values.ensure_value(dest, []).extend(lvalue)
1988 else:
1989 Option.take_action(
1990 self, action, dest, opt, value, values, parser)
1991
1992Features of note:
1993
Georg Brandlb926ebb2009-09-17 17:14:04 +00001994* ``"extend"`` both expects a value on the command-line and stores that value
1995 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1996 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001997
Georg Brandlb926ebb2009-09-17 17:14:04 +00001998* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1999 ``"extend"`` actions, we put the ``"extend"`` action in
2000 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002001
2002* :meth:`MyOption.take_action` implements just this one new action, and passes
2003 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00002004 actions.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002005
Georg Brandlb926ebb2009-09-17 17:14:04 +00002006* ``values`` is an instance of the optparse_parser.Values class, which provides
2007 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
2008 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00002009
2010 values.ensure_value(attr, value)
2011
2012 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandlb926ebb2009-09-17 17:14:04 +00002013 ensure_value() first sets it to ``value``, and then returns 'value. This is
2014 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
2015 of which accumulate data in a variable and expect that variable to be of a
2016 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl8ec7f652007-08-15 14:28:01 +00002017 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandlb926ebb2009-09-17 17:14:04 +00002018 about setting a default value for the option destinations in question; they
2019 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl8ec7f652007-08-15 14:28:01 +00002020 getting it right when it's needed.