blob: 9a4ba4e6ed2fa07759be4d9dcd2810b90d66fc8a [file] [log] [blame]
Steven Bethard6d265692010-03-02 09:22:57 +00001:mod:`optparse` --- Parser for command line options
2===================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: optparse
Steven Bethard6d265692010-03-02 09:22:57 +00005 :synopsis: Command-line option parsing library.
Steven Bethard59710962010-05-24 03:21:08 +00006 :deprecated:
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007
Georg Brandl116aa622007-08-15 14:28:22 +00008.. moduleauthor:: Greg Ward <gward@python.net>
Georg Brandl116aa622007-08-15 14:28:22 +00009.. sectionauthor:: Greg Ward <gward@python.net>
10
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040011**Source code:** :source:`Lib/optparse.py`
12
Éric Araujo19f9b712011-08-19 00:49:18 +020013.. deprecated:: 3.2
Georg Brandldf48b972014-03-24 09:06:18 +010014 The :mod:`optparse` module is deprecated and will not be developed further;
15 development will continue with the :mod:`argparse` module.
Éric Araujo19f9b712011-08-19 00:49:18 +020016
Raymond Hettinger469271d2011-01-27 20:38:46 +000017--------------
18
Georg Brandl15a515f2009-09-17 22:11:49 +000019:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
20command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
21more declarative style of command-line parsing: you create an instance of
22:class:`OptionParser`, populate it with options, and parse the command
23line. :mod:`optparse` allows users to specify options in the conventional
24GNU/POSIX syntax, and additionally generates usage and help messages for you.
Georg Brandl116aa622007-08-15 14:28:22 +000025
Georg Brandl15a515f2009-09-17 22:11:49 +000026Here's an example of using :mod:`optparse` in a simple script::
Georg Brandl116aa622007-08-15 14:28:22 +000027
28 from optparse import OptionParser
Serhiy Storchakadba90392016-05-10 12:01:23 +030029 ...
Georg Brandl116aa622007-08-15 14:28:22 +000030 parser = OptionParser()
31 parser.add_option("-f", "--file", dest="filename",
32 help="write report to FILE", metavar="FILE")
33 parser.add_option("-q", "--quiet",
34 action="store_false", dest="verbose", default=True,
35 help="don't print status messages to stdout")
36
37 (options, args) = parser.parse_args()
38
39With these few lines of code, users of your script can now do the "usual thing"
40on the command-line, for example::
41
42 <yourscript> --file=outfile -q
43
Georg Brandl15a515f2009-09-17 22:11:49 +000044As it parses the command line, :mod:`optparse` sets attributes of the
45``options`` object returned by :meth:`parse_args` based on user-supplied
46command-line values. When :meth:`parse_args` returns from parsing this command
47line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
48``False``. :mod:`optparse` supports both long and short options, allows short
Georg Brandl116aa622007-08-15 14:28:22 +000049options to be merged together, and allows options to be associated with their
50arguments in a variety of ways. Thus, the following command lines are all
51equivalent to the above example::
52
53 <yourscript> -f outfile --quiet
54 <yourscript> --quiet --file outfile
55 <yourscript> -q -foutfile
56 <yourscript> -qfoutfile
57
58Additionally, users can run one of ::
59
60 <yourscript> -h
61 <yourscript> --help
62
Ezio Melotti383ae952010-01-03 09:06:02 +000063and :mod:`optparse` will print out a brief summary of your script's options:
64
65.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +000066
Georg Brandl121ff822011-01-02 14:23:43 +000067 Usage: <yourscript> [options]
Georg Brandl116aa622007-08-15 14:28:22 +000068
Georg Brandl121ff822011-01-02 14:23:43 +000069 Options:
Georg Brandl116aa622007-08-15 14:28:22 +000070 -h, --help show this help message and exit
71 -f FILE, --file=FILE write report to FILE
72 -q, --quiet don't print status messages to stdout
73
74where the value of *yourscript* is determined at runtime (normally from
75``sys.argv[0]``).
76
Georg Brandl116aa622007-08-15 14:28:22 +000077
78.. _optparse-background:
79
80Background
81----------
82
83:mod:`optparse` was explicitly designed to encourage the creation of programs
84with straightforward, conventional command-line interfaces. To that end, it
85supports only the most common command-line syntax and semantics conventionally
86used under Unix. If you are unfamiliar with these conventions, read this
87section to acquaint yourself with them.
88
89
90.. _optparse-terminology:
91
92Terminology
93^^^^^^^^^^^
94
95argument
Georg Brandl15a515f2009-09-17 22:11:49 +000096 a string entered on the command-line, and passed by the shell to ``execl()``
97 or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
98 (``sys.argv[0]`` is the name of the program being executed). Unix shells
99 also use the term "word".
Georg Brandl116aa622007-08-15 14:28:22 +0000100
101 It is occasionally desirable to substitute an argument list other than
102 ``sys.argv[1:]``, so you should read "argument" as "an element of
103 ``sys.argv[1:]``, or of some other list provided as a substitute for
104 ``sys.argv[1:]``".
105
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000106option
Georg Brandl15a515f2009-09-17 22:11:49 +0000107 an argument used to supply extra information to guide or customize the
108 execution of a program. There are many different syntaxes for options; the
109 traditional Unix syntax is a hyphen ("-") followed by a single letter,
Éric Araujo713d3032010-11-18 16:38:46 +0000110 e.g. ``-x`` or ``-F``. Also, traditional Unix syntax allows multiple
111 options to be merged into a single argument, e.g. ``-x -F`` is equivalent
112 to ``-xF``. The GNU project introduced ``--`` followed by a series of
113 hyphen-separated words, e.g. ``--file`` or ``--dry-run``. These are the
Georg Brandl15a515f2009-09-17 22:11:49 +0000114 only two option syntaxes provided by :mod:`optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116 Some other option syntaxes that the world has seen include:
117
Éric Araujo713d3032010-11-18 16:38:46 +0000118 * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
Georg Brandl116aa622007-08-15 14:28:22 +0000119 as multiple options merged into a single argument)
120
Éric Araujo713d3032010-11-18 16:38:46 +0000121 * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
Georg Brandl116aa622007-08-15 14:28:22 +0000122 equivalent to the previous syntax, but they aren't usually seen in the same
123 program)
124
125 * a plus sign followed by a single letter, or a few letters, or a word, e.g.
Éric Araujo713d3032010-11-18 16:38:46 +0000126 ``+f``, ``+rgb``
Georg Brandl116aa622007-08-15 14:28:22 +0000127
Éric Araujo713d3032010-11-18 16:38:46 +0000128 * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``,
129 ``/file``
Georg Brandl116aa622007-08-15 14:28:22 +0000130
Georg Brandl15a515f2009-09-17 22:11:49 +0000131 These option syntaxes are not supported by :mod:`optparse`, and they never
132 will be. This is deliberate: the first three are non-standard on any
133 environment, and the last only makes sense if you're exclusively targeting
134 VMS, MS-DOS, and/or Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000135
136option argument
Georg Brandl15a515f2009-09-17 22:11:49 +0000137 an argument that follows an option, is closely associated with that option,
138 and is consumed from the argument list when that option is. With
139 :mod:`optparse`, option arguments may either be in a separate argument from
Ezio Melotti383ae952010-01-03 09:06:02 +0000140 their option:
141
142 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144 -f foo
145 --file foo
146
Ezio Melotti383ae952010-01-03 09:06:02 +0000147 or included in the same argument:
148
149 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000150
151 -ffoo
152 --file=foo
153
Georg Brandl15a515f2009-09-17 22:11:49 +0000154 Typically, a given option either takes an argument or it doesn't. Lots of
155 people want an "optional option arguments" feature, meaning that some options
156 will take an argument if they see it, and won't if they don't. This is
Éric Araujo713d3032010-11-18 16:38:46 +0000157 somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
158 an optional argument and ``-b`` is another option entirely, how do we
159 interpret ``-ab``? Because of this ambiguity, :mod:`optparse` does not
Georg Brandl15a515f2009-09-17 22:11:49 +0000160 support this feature.
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162positional argument
163 something leftover in the argument list after options have been parsed, i.e.
Georg Brandl15a515f2009-09-17 22:11:49 +0000164 after options and their arguments have been parsed and removed from the
165 argument list.
Georg Brandl116aa622007-08-15 14:28:22 +0000166
167required option
168 an option that must be supplied on the command-line; note that the phrase
169 "required option" is self-contradictory in English. :mod:`optparse` doesn't
Georg Brandl15a515f2009-09-17 22:11:49 +0000170 prevent you from implementing required options, but doesn't give you much
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000171 help at it either.
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173For example, consider this hypothetical command-line::
174
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +0100175 prog -v --report report.txt foo bar
Georg Brandl116aa622007-08-15 14:28:22 +0000176
Éric Araujo713d3032010-11-18 16:38:46 +0000177``-v`` and ``--report`` are both options. Assuming that ``--report``
Petri Lehtinen9f74c6c2013-02-23 19:26:56 +0100178takes one argument, ``report.txt`` is an option argument. ``foo`` and
Éric Araujo713d3032010-11-18 16:38:46 +0000179``bar`` are positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181
182.. _optparse-what-options-for:
183
184What are options for?
185^^^^^^^^^^^^^^^^^^^^^
186
187Options are used to provide extra information to tune or customize the execution
188of a program. In case it wasn't clear, options are usually *optional*. A
189program should be able to run just fine with no options whatsoever. (Pick a
190random program from the Unix or GNU toolsets. Can it run without any options at
191all and still make sense? The main exceptions are ``find``, ``tar``, and
192``dd``\ ---all of which are mutant oddballs that have been rightly criticized
193for their non-standard syntax and confusing interfaces.)
194
195Lots of people want their programs to have "required options". Think about it.
196If it's required, then it's *not optional*! If there is a piece of information
197that your program absolutely requires in order to run successfully, that's what
198positional arguments are for.
199
200As an example of good command-line interface design, consider the humble ``cp``
201utility, for copying files. It doesn't make much sense to try to copy files
202without supplying a destination and at least one source. Hence, ``cp`` fails if
203you run it with no arguments. However, it has a flexible, useful syntax that
204does not require any options at all::
205
206 cp SOURCE DEST
207 cp SOURCE ... DEST-DIR
208
209You can get pretty far with just that. Most ``cp`` implementations provide a
210bunch of options to tweak exactly how the files are copied: you can preserve
211mode and modification time, avoid following symlinks, ask before clobbering
212existing files, etc. But none of this distracts from the core mission of
213``cp``, which is to copy either one file to another, or several files to another
214directory.
215
216
217.. _optparse-what-positional-arguments-for:
218
219What are positional arguments for?
220^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
221
222Positional arguments are for those pieces of information that your program
223absolutely, positively requires to run.
224
225A good user interface should have as few absolute requirements as possible. If
226your program requires 17 distinct pieces of information in order to run
227successfully, it doesn't much matter *how* you get that information from the
228user---most people will give up and walk away before they successfully run the
229program. This applies whether the user interface is a command-line, a
230configuration file, or a GUI: if you make that many demands on your users, most
231of them will simply give up.
232
233In short, try to minimize the amount of information that users are absolutely
234required to supply---use sensible defaults whenever possible. Of course, you
235also want to make your programs reasonably flexible. That's what options are
236for. Again, it doesn't matter if they are entries in a config file, widgets in
237the "Preferences" dialog of a GUI, or command-line options---the more options
238you implement, the more flexible your program is, and the more complicated its
239implementation becomes. Too much flexibility has drawbacks as well, of course;
240too many options can overwhelm users and make your code much harder to maintain.
241
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243.. _optparse-tutorial:
244
245Tutorial
246--------
247
248While :mod:`optparse` is quite flexible and powerful, it's also straightforward
249to use in most cases. This section covers the code patterns that are common to
250any :mod:`optparse`\ -based program.
251
252First, you need to import the OptionParser class; then, early in the main
253program, create an OptionParser instance::
254
255 from optparse import OptionParser
Serhiy Storchakadba90392016-05-10 12:01:23 +0300256 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000257 parser = OptionParser()
258
259Then you can start defining options. The basic syntax is::
260
261 parser.add_option(opt_str, ...,
262 attr=value, ...)
263
Éric Araujo713d3032010-11-18 16:38:46 +0000264Each option has one or more option strings, such as ``-f`` or ``--file``,
Georg Brandl116aa622007-08-15 14:28:22 +0000265and several option attributes that tell :mod:`optparse` what to expect and what
266to do when it encounters that option on the command line.
267
268Typically, each option will have one short option string and one long option
269string, e.g.::
270
271 parser.add_option("-f", "--file", ...)
272
273You're free to define as many short option strings and as many long option
274strings as you like (including zero), as long as there is at least one option
275string overall.
276
Ezio Melottie0add762012-09-14 06:32:35 +0300277The option strings passed to :meth:`OptionParser.add_option` are effectively
278labels for the
Georg Brandl116aa622007-08-15 14:28:22 +0000279option 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 Araujo713d3032010-11-18 16:38:46 +0000294 ``--file`` takes a single string argument, then ``options.file`` will be the
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandl15a515f2009-09-17 22:11:49 +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 Brandl116aa622007-08-15 14:28:22 +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 Brandl15a515f2009-09-17 22:11:49 +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 Brandl116aa622007-08-15 14:28:22 +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 Araujo713d3032010-11-18 16:38:46 +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 Brandl116aa622007-08-15 14:28:22 +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 Araujo713d3032010-11-18 16:38:46 +0000353right up against the option: since ``-n42`` (one argument) is equivalent to
354``-n 42`` (two arguments), the code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356 (options, args) = parser.parse_args(["-n42"])
Georg Brandl6911e3c2007-09-04 07:15:32 +0000357 print(options.num)
Georg Brandl116aa622007-08-15 14:28:22 +0000358
Éric Araujo713d3032010-11-18 16:38:46 +0000359will print ``42``.
Georg Brandl116aa622007-08-15 14:28:22 +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 Araujo713d3032010-11-18 16:38:46 +0000369``--foo-bar``, then the default destination is ``foo_bar``. If there are no
Georg Brandl116aa622007-08-15 14:28:22 +0000370long option strings, :mod:`optparse` looks at the first short option string: the
Éric Araujo713d3032010-11-18 16:38:46 +0000371default destination for ``-f`` is ``f``.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
Georg Brandl5c106642007-11-29 17:41:05 +0000373:mod:`optparse` also includes the built-in ``complex`` type. Adding
Georg Brandl116aa622007-08-15 14:28:22 +0000374types 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 Araujo713d3032010-11-18 16:38:46 +0000385flag that is turned on with ``-v`` and off with ``-q``::
Georg Brandl116aa622007-08-15 14:28:22 +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 Araujo713d3032010-11-18 16:38:46 +0000394When :mod:`optparse` encounters ``-v`` on the command line, it sets
395``options.verbose`` to ``True``; when it encounters ``-q``,
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandl15a515f2009-09-17 22:11:49 +0000406``"store_const"``
Georg Brandl116aa622007-08-15 14:28:22 +0000407 store a constant value
408
Georg Brandl15a515f2009-09-17 22:11:49 +0000409``"append"``
Georg Brandl116aa622007-08-15 14:28:22 +0000410 append this option's argument to a list
411
Georg Brandl15a515f2009-09-17 22:11:49 +0000412``"count"``
Georg Brandl116aa622007-08-15 14:28:22 +0000413 increment a counter by one
414
Georg Brandl15a515f2009-09-17 22:11:49 +0000415``"callback"``
Georg Brandl116aa622007-08-15 14:28:22 +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 Araujo713d3032010-11-18 16:38:46 +0000435``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandl15a515f2009-09-17 22:11:49 +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 Brandl116aa622007-08-15 14:28:22 +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",
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000484 action="store_false", dest="verbose",
Georg Brandl116aa622007-08-15 14:28:22 +0000485 help="be vewwy quiet (I'm hunting wabbits)")
486 parser.add_option("-f", "--filename",
Georg Brandlee8783d2009-09-16 16:00:31 +0000487 metavar="FILE", help="write output to FILE")
Georg Brandl116aa622007-08-15 14:28:22 +0000488 parser.add_option("-m", "--mode",
489 default="intermediate",
490 help="interaction mode: novice, intermediate, "
491 "or expert [default: %default]")
492
Éric Araujo713d3032010-11-18 16:38:46 +0000493If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
Georg Brandl116aa622007-08-15 14:28:22 +0000494command-line, or if you just call :meth:`parser.print_help`, it prints the
Ezio Melotti383ae952010-01-03 09:06:02 +0000495following to standard output:
496
497.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000498
Georg Brandl121ff822011-01-02 14:23:43 +0000499 Usage: <yourscript> [options] arg1 arg2
Georg Brandl116aa622007-08-15 14:28:22 +0000500
Georg Brandl121ff822011-01-02 14:23:43 +0000501 Options:
Georg Brandl116aa622007-08-15 14:28:22 +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 Araujo713d3032010-11-18 16:38:46 +0000520 :mod:`optparse` expands ``%prog`` in the usage string to the name of the
Georg Brandl15a515f2009-09-17 22:11:49 +0000521 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
522 is then printed before the detailed option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandl121ff822011-01-02 14:23:43 +0000525 default: ``"Usage: %prog [options]"``, which is fine if your script doesn't
Georg Brandl15a515f2009-09-17 22:11:49 +0000526 take any positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +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 Araujo713d3032010-11-18 16:38:46 +0000538 user is expected to supply to ``-m``/``--mode``. By default,
Georg Brandl116aa622007-08-15 14:28:22 +0000539 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandl15a515f2009-09-17 22:11:49 +0000540 that for the meta-variable. Sometimes, that's not what you want---for
Éric Araujo713d3032010-11-18 16:38:46 +0000541 example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
Georg Brandl15a515f2009-09-17 22:11:49 +0000542 resulting in this automatically-generated option description::
Georg Brandl116aa622007-08-15 14:28:22 +0000543
544 -f FILE, --filename=FILE
545
Georg Brandl15a515f2009-09-17 22:11:49 +0000546 This is important for more than just saving space, though: the manually
Éric Araujo713d3032010-11-18 16:38:46 +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 Brandl15a515f2009-09-17 22:11:49 +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 Brandl116aa622007-08-15 14:28:22 +0000551
552* options that have a default value can include ``%default`` in the help
553 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
554 default value. If an option has no default value (or the default value is
555 ``None``), ``%default`` expands to ``none``.
556
Georg Brandl121ff822011-01-02 14:23:43 +0000557Grouping Options
558++++++++++++++++
559
Georg Brandl15a515f2009-09-17 22:11:49 +0000560When dealing with many options, it is convenient to group these options for
561better help output. An :class:`OptionParser` can contain several option groups,
562each of which can contain several options.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000563
Georg Brandl121ff822011-01-02 14:23:43 +0000564An option group is obtained using the class :class:`OptionGroup`:
565
566.. class:: OptionGroup(parser, title, description=None)
567
568 where
569
570 * parser is the :class:`OptionParser` instance the group will be insterted in
571 to
572 * title is the group title
573 * description, optional, is a long description of the group
574
575:class:`OptionGroup` inherits from :class:`OptionContainer` (like
576:class:`OptionParser`) and so the :meth:`add_option` method can be used to add
577an option to the group.
578
579Once all the options are declared, using the :class:`OptionParser` method
580:meth:`add_option_group` the group is added to the previously defined parser.
581
582Continuing with the parser defined in the previous section, adding an
583:class:`OptionGroup` to a parser is easy::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000584
585 group = OptionGroup(parser, "Dangerous Options",
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000586 "Caution: use these options at your own risk. "
587 "It is believed that some of them bite.")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000588 group.add_option("-g", action="store_true", help="Group option.")
589 parser.add_option_group(group)
590
Ezio Melotti383ae952010-01-03 09:06:02 +0000591This would result in the following help output:
592
593.. code-block:: text
Christian Heimesfdab48e2008-01-20 09:06:41 +0000594
Georg Brandl121ff822011-01-02 14:23:43 +0000595 Usage: <yourscript> [options] arg1 arg2
Christian Heimesfdab48e2008-01-20 09:06:41 +0000596
Georg Brandl121ff822011-01-02 14:23:43 +0000597 Options:
598 -h, --help show this help message and exit
599 -v, --verbose make lots of noise [default]
600 -q, --quiet be vewwy quiet (I'm hunting wabbits)
601 -f FILE, --filename=FILE
602 write output to FILE
603 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
604 expert [default: intermediate]
Christian Heimesfdab48e2008-01-20 09:06:41 +0000605
Georg Brandl121ff822011-01-02 14:23:43 +0000606 Dangerous Options:
607 Caution: use these options at your own risk. It is believed that some
608 of them bite.
609
610 -g Group option.
611
Eli Benderskyeeae1492011-11-16 06:02:21 +0200612A bit more complete example might involve using more than one group: still
613extending the previous example::
Georg Brandl121ff822011-01-02 14:23:43 +0000614
615 group = OptionGroup(parser, "Dangerous Options",
616 "Caution: use these options at your own risk. "
617 "It is believed that some of them bite.")
618 group.add_option("-g", action="store_true", help="Group option.")
619 parser.add_option_group(group)
620
621 group = OptionGroup(parser, "Debug Options")
622 group.add_option("-d", "--debug", action="store_true",
623 help="Print debug information")
624 group.add_option("-s", "--sql", action="store_true",
625 help="Print all SQL statements executed")
626 group.add_option("-e", action="store_true", help="Print every action done")
627 parser.add_option_group(group)
628
629that results in the following output:
630
631.. code-block:: text
632
633 Usage: <yourscript> [options] arg1 arg2
634
635 Options:
636 -h, --help show this help message and exit
637 -v, --verbose make lots of noise [default]
638 -q, --quiet be vewwy quiet (I'm hunting wabbits)
639 -f FILE, --filename=FILE
640 write output to FILE
641 -m MODE, --mode=MODE interaction mode: novice, intermediate, or expert
642 [default: intermediate]
643
644 Dangerous Options:
645 Caution: use these options at your own risk. It is believed that some
646 of them bite.
647
648 -g Group option.
649
650 Debug Options:
651 -d, --debug Print debug information
652 -s, --sql Print all SQL statements executed
653 -e Print every action done
654
655Another interesting method, in particular when working programmatically with
656option groups is:
657
658.. method:: OptionParser.get_option_group(opt_str)
659
Eli Benderskye2503582011-07-30 11:14:32 +0300660 Return the :class:`OptionGroup` to which the short or long option
661 string *opt_str* (e.g. ``'-o'`` or ``'--option'``) belongs. If
662 there's no such :class:`OptionGroup`, return ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000663
664.. _optparse-printing-version-string:
665
666Printing a version string
667^^^^^^^^^^^^^^^^^^^^^^^^^
668
669Similar to the brief usage string, :mod:`optparse` can also print a version
670string for your program. You have to supply the string as the ``version``
671argument to OptionParser::
672
673 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
674
Éric Araujo713d3032010-11-18 16:38:46 +0000675``%prog`` is expanded just like it is in ``usage``. Apart from that,
Georg Brandl116aa622007-08-15 14:28:22 +0000676``version`` can contain anything you like. When you supply it, :mod:`optparse`
Éric Araujo713d3032010-11-18 16:38:46 +0000677automatically adds a ``--version`` option to your parser. If it encounters
Georg Brandl116aa622007-08-15 14:28:22 +0000678this option on the command line, it expands your ``version`` string (by
Éric Araujo713d3032010-11-18 16:38:46 +0000679replacing ``%prog``), prints it to stdout, and exits.
Georg Brandl116aa622007-08-15 14:28:22 +0000680
681For example, if your script is called ``/usr/bin/foo``::
682
683 $ /usr/bin/foo --version
684 foo 1.0
685
Ezio Melotti1ce43192010-01-04 21:53:17 +0000686The following two methods can be used to print and get the ``version`` string:
687
688.. method:: OptionParser.print_version(file=None)
689
690 Print the version message for the current program (``self.version``) to
691 *file* (default stdout). As with :meth:`print_usage`, any occurrence
Éric Araujo713d3032010-11-18 16:38:46 +0000692 of ``%prog`` in ``self.version`` is replaced with the name of the current
Ezio Melotti1ce43192010-01-04 21:53:17 +0000693 program. Does nothing if ``self.version`` is empty or undefined.
694
695.. method:: OptionParser.get_version()
696
697 Same as :meth:`print_version` but returns the version string instead of
698 printing it.
699
Georg Brandl116aa622007-08-15 14:28:22 +0000700
701.. _optparse-how-optparse-handles-errors:
702
703How :mod:`optparse` handles errors
704^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
705
706There are two broad classes of errors that :mod:`optparse` has to worry about:
707programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandl15a515f2009-09-17 22:11:49 +0000708calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
709option attributes, missing option attributes, etc. These are dealt with in the
710usual way: raise an exception (either :exc:`optparse.OptionError` or
711:exc:`TypeError`) and let the program crash.
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713Handling user errors is much more important, since they are guaranteed to happen
714no matter how stable your code is. :mod:`optparse` can automatically detect
Éric Araujo713d3032010-11-18 16:38:46 +0000715some user errors, such as bad option arguments (passing ``-n 4x`` where
716``-n`` takes an integer argument), missing arguments (``-n`` at the end
717of the command line, where ``-n`` takes an argument of any type). Also,
Georg Brandl15a515f2009-09-17 22:11:49 +0000718you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl116aa622007-08-15 14:28:22 +0000719condition::
720
721 (options, args) = parser.parse_args()
Serhiy Storchakadba90392016-05-10 12:01:23 +0300722 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000723 if options.a and options.b:
724 parser.error("options -a and -b are mutually exclusive")
725
726In either case, :mod:`optparse` handles the error the same way: it prints the
727program's usage message and an error message to standard error and exits with
728error status 2.
729
Éric Araujo713d3032010-11-18 16:38:46 +0000730Consider the first example above, where the user passes ``4x`` to an option
Georg Brandl116aa622007-08-15 14:28:22 +0000731that takes an integer::
732
733 $ /usr/bin/foo -n 4x
Georg Brandl121ff822011-01-02 14:23:43 +0000734 Usage: foo [options]
Georg Brandl116aa622007-08-15 14:28:22 +0000735
736 foo: error: option -n: invalid integer value: '4x'
737
738Or, where the user fails to pass a value at all::
739
740 $ /usr/bin/foo -n
Georg Brandl121ff822011-01-02 14:23:43 +0000741 Usage: foo [options]
Georg Brandl116aa622007-08-15 14:28:22 +0000742
743 foo: error: -n option requires an argument
744
745:mod:`optparse`\ -generated error messages take care always to mention the
746option involved in the error; be sure to do the same when calling
Georg Brandl15a515f2009-09-17 22:11:49 +0000747:func:`OptionParser.error` from your application code.
Georg Brandl116aa622007-08-15 14:28:22 +0000748
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000749If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000750you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
751and/or :meth:`~OptionParser.error` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000752
753
754.. _optparse-putting-it-all-together:
755
756Putting it all together
757^^^^^^^^^^^^^^^^^^^^^^^
758
759Here's what :mod:`optparse`\ -based scripts usually look like::
760
761 from optparse import OptionParser
Serhiy Storchakadba90392016-05-10 12:01:23 +0300762 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000763 def main():
764 usage = "usage: %prog [options] arg"
765 parser = OptionParser(usage)
766 parser.add_option("-f", "--file", dest="filename",
767 help="read data from FILENAME")
768 parser.add_option("-v", "--verbose",
769 action="store_true", dest="verbose")
770 parser.add_option("-q", "--quiet",
771 action="store_false", dest="verbose")
Serhiy Storchakadba90392016-05-10 12:01:23 +0300772 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000773 (options, args) = parser.parse_args()
774 if len(args) != 1:
775 parser.error("incorrect number of arguments")
776 if options.verbose:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000777 print("reading %s..." % options.filename)
Serhiy Storchakadba90392016-05-10 12:01:23 +0300778 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000779
780 if __name__ == "__main__":
781 main()
782
Georg Brandl116aa622007-08-15 14:28:22 +0000783
784.. _optparse-reference-guide:
785
786Reference Guide
787---------------
788
789
790.. _optparse-creating-parser:
791
792Creating the parser
793^^^^^^^^^^^^^^^^^^^
794
Georg Brandl15a515f2009-09-17 22:11:49 +0000795The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000796
Georg Brandl15a515f2009-09-17 22:11:49 +0000797.. class:: OptionParser(...)
Georg Brandl116aa622007-08-15 14:28:22 +0000798
Georg Brandl15a515f2009-09-17 22:11:49 +0000799 The OptionParser constructor has no required arguments, but a number of
800 optional keyword arguments. You should always pass them as keyword
801 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl116aa622007-08-15 14:28:22 +0000802
803 ``usage`` (default: ``"%prog [options]"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000804 The usage summary to print when your program is run incorrectly or with a
805 help option. When :mod:`optparse` prints the usage string, it expands
806 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
807 passed that keyword argument). To suppress a usage message, pass the
808 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl116aa622007-08-15 14:28:22 +0000809
810 ``option_list`` (default: ``[]``)
811 A list of Option objects to populate the parser with. The options in
Georg Brandl15a515f2009-09-17 22:11:49 +0000812 ``option_list`` are added after any options in ``standard_option_list`` (a
813 class attribute that may be set by OptionParser subclasses), but before
814 any version or help options. Deprecated; use :meth:`add_option` after
815 creating the parser instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000816
817 ``option_class`` (default: optparse.Option)
818 Class to use when adding options to the parser in :meth:`add_option`.
819
820 ``version`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000821 A version string to print when the user supplies a version option. If you
822 supply a true value for ``version``, :mod:`optparse` automatically adds a
Éric Araujo713d3032010-11-18 16:38:46 +0000823 version option with the single option string ``--version``. The
824 substring ``%prog`` is expanded the same as for ``usage``.
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826 ``conflict_handler`` (default: ``"error"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000827 Specifies what to do when options with conflicting option strings are
828 added to the parser; see section
829 :ref:`optparse-conflicts-between-options`.
Georg Brandl116aa622007-08-15 14:28:22 +0000830
831 ``description`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000832 A paragraph of text giving a brief overview of your program.
833 :mod:`optparse` reformats this paragraph to fit the current terminal width
834 and prints it when the user requests help (after ``usage``, but before the
835 list of options).
Georg Brandl116aa622007-08-15 14:28:22 +0000836
Georg Brandl15a515f2009-09-17 22:11:49 +0000837 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
838 An instance of optparse.HelpFormatter that will be used for printing help
839 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl116aa622007-08-15 14:28:22 +0000840 IndentedHelpFormatter and TitledHelpFormatter.
841
842 ``add_help_option`` (default: ``True``)
Éric Araujo713d3032010-11-18 16:38:46 +0000843 If true, :mod:`optparse` will add a help option (with option strings ``-h``
844 and ``--help``) to the parser.
Georg Brandl116aa622007-08-15 14:28:22 +0000845
846 ``prog``
Éric Araujo713d3032010-11-18 16:38:46 +0000847 The string to use when expanding ``%prog`` in ``usage`` and ``version``
Georg Brandl116aa622007-08-15 14:28:22 +0000848 instead of ``os.path.basename(sys.argv[0])``.
849
Senthil Kumaran5b58f5e2010-03-23 11:00:53 +0000850 ``epilog`` (default: ``None``)
851 A paragraph of help text to print after the option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000852
853.. _optparse-populating-parser:
854
855Populating the parser
856^^^^^^^^^^^^^^^^^^^^^
857
858There are several ways to populate the parser with options. The preferred way
Georg Brandl15a515f2009-09-17 22:11:49 +0000859is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl116aa622007-08-15 14:28:22 +0000860:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
861
862* pass it an Option instance (as returned by :func:`make_option`)
863
864* pass it any combination of positional and keyword arguments that are
Georg Brandl15a515f2009-09-17 22:11:49 +0000865 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
866 will create the Option instance for you
Georg Brandl116aa622007-08-15 14:28:22 +0000867
868The other alternative is to pass a list of pre-constructed Option instances to
869the OptionParser constructor, as in::
870
871 option_list = [
872 make_option("-f", "--filename",
873 action="store", type="string", dest="filename"),
874 make_option("-q", "--quiet",
875 action="store_false", dest="verbose"),
876 ]
877 parser = OptionParser(option_list=option_list)
878
879(:func:`make_option` is a factory function for creating Option instances;
880currently it is an alias for the Option constructor. A future version of
881:mod:`optparse` may split Option into several classes, and :func:`make_option`
882will pick the right class to instantiate. Do not instantiate Option directly.)
883
884
885.. _optparse-defining-options:
886
887Defining options
888^^^^^^^^^^^^^^^^
889
890Each Option instance represents a set of synonymous command-line option strings,
Éric Araujo713d3032010-11-18 16:38:46 +0000891e.g. ``-f`` and ``--file``. You can specify any number of short or
Georg Brandl116aa622007-08-15 14:28:22 +0000892long option strings, but you must specify at least one overall option string.
893
Georg Brandl15a515f2009-09-17 22:11:49 +0000894The canonical way to create an :class:`Option` instance is with the
895:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl116aa622007-08-15 14:28:22 +0000896
Ezio Melottie0add762012-09-14 06:32:35 +0300897.. method:: OptionParser.add_option(option)
898 OptionParser.add_option(*opt_str, attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000899
Georg Brandl15a515f2009-09-17 22:11:49 +0000900 To define an option with only a short option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000901
Georg Brandl15a515f2009-09-17 22:11:49 +0000902 parser.add_option("-f", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000903
Georg Brandl15a515f2009-09-17 22:11:49 +0000904 And to define an option with only a long option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000905
Georg Brandl15a515f2009-09-17 22:11:49 +0000906 parser.add_option("--foo", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000907
Georg Brandl15a515f2009-09-17 22:11:49 +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 Brandl116aa622007-08-15 14:28:22 +0000913
Georg Brandl15a515f2009-09-17 22:11:49 +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 Brandl116aa622007-08-15 14:28:22 +0000917
Georg Brandl15a515f2009-09-17 22:11:49 +0000918 ``"store"``
919 store this option's argument (default)
Georg Brandl116aa622007-08-15 14:28:22 +0000920
Georg Brandl15a515f2009-09-17 22:11:49 +0000921 ``"store_const"``
922 store a constant value
Georg Brandl116aa622007-08-15 14:28:22 +0000923
Georg Brandl15a515f2009-09-17 22:11:49 +0000924 ``"store_true"``
925 store a true value
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Georg Brandl15a515f2009-09-17 22:11:49 +0000927 ``"store_false"``
928 store a false value
Georg Brandl116aa622007-08-15 14:28:22 +0000929
Georg Brandl15a515f2009-09-17 22:11:49 +0000930 ``"append"``
931 append this option's argument to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000932
Georg Brandl15a515f2009-09-17 22:11:49 +0000933 ``"append_const"``
934 append a constant value to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000935
Georg Brandl15a515f2009-09-17 22:11:49 +0000936 ``"count"``
937 increment a counter by one
Georg Brandl116aa622007-08-15 14:28:22 +0000938
Georg Brandl15a515f2009-09-17 22:11:49 +0000939 ``"callback"``
940 call a specified function
Georg Brandl116aa622007-08-15 14:28:22 +0000941
Georg Brandl15a515f2009-09-17 22:11:49 +0000942 ``"help"``
943 print a usage message including all options and the documentation for them
Georg Brandl116aa622007-08-15 14:28:22 +0000944
Georg Brandl15a515f2009-09-17 22:11:49 +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 Brandl116aa622007-08-15 14:28:22 +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 Brandl15a515f2009-09-17 22:11:49 +0000951``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl116aa622007-08-15 14:28:22 +0000952arguments (and various other values) are stored as attributes of this object,
Georg Brandl15a515f2009-09-17 22:11:49 +0000953according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
Georg Brandl15a515f2009-09-17 22:11:49 +0000955For example, when you call ::
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandl15a515f2009-09-17 22:11:49 +0000963If one of the options in this parser is defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandl15a515f2009-09-17 22:11:49 +0000974then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl116aa622007-08-15 14:28:22 +0000975
976 options.filename = "foo"
977
Georg Brandl15a515f2009-09-17 22:11:49 +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 Araujo713d3032010-11-18 16:38:46 +00001055 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
Georg Brandl15a515f2009-09-17 22:11:49 +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 Brandl116aa622007-08-15 14:28:22 +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 Brandl15a515f2009-09-17 22:11:49 +00001077* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1078 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001079
1080 The option must be followed by an argument, which is converted to a value
Georg Brandl15a515f2009-09-17 22:11:49 +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 Brandl116aa622007-08-15 14:28:22 +00001086
Georg Brandl15a515f2009-09-17 22:11:49 +00001087 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1088 defaults to ``"choice"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001089
Georg Brandl15a515f2009-09-17 22:11:49 +00001090 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001091
Georg Brandl15a515f2009-09-17 22:11:49 +00001092 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
Éric Araujo713d3032010-11-18 16:38:46 +00001093 from the first long option string (e.g., ``--foo-bar`` implies
Georg Brandl15a515f2009-09-17 22:11:49 +00001094 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
Éric Araujo713d3032010-11-18 16:38:46 +00001095 destination from the first short option string (e.g., ``-f`` implies ``f``).
Georg Brandl116aa622007-08-15 14:28:22 +00001096
1097 Example::
1098
1099 parser.add_option("-f")
1100 parser.add_option("-p", type="float", nargs=3, dest="point")
1101
Georg Brandl15a515f2009-09-17 22:11:49 +00001102 As it parses the command line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001103
1104 -f foo.txt -p 1 -3.5 4 -fbar.txt
1105
Georg Brandl15a515f2009-09-17 22:11:49 +00001106 :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +00001107
1108 options.f = "foo.txt"
1109 options.point = (1.0, -3.5, 4.0)
1110 options.f = "bar.txt"
1111
Georg Brandl15a515f2009-09-17 22:11:49 +00001112* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1113 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001114
Georg Brandl15a515f2009-09-17 22:11:49 +00001115 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +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 Araujo713d3032010-11-18 16:38:46 +00001126 If ``--noisy`` is seen, :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +00001127
1128 options.verbose = 2
1129
Georg Brandl15a515f2009-09-17 22:11:49 +00001130* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001131
Georg Brandl15a515f2009-09-17 22:11:49 +00001132 A special case of ``"store_const"`` that stores a true value to
1133 :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001134
Georg Brandl15a515f2009-09-17 22:11:49 +00001135* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001136
Georg Brandl15a515f2009-09-17 22:11:49 +00001137 Like ``"store_true"``, but stores a false value.
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandl15a515f2009-09-17 22:11:49 +00001144* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1145 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001146
1147 The option must be followed by an argument, which is appended to the list in
Georg Brandl15a515f2009-09-17 22:11:49 +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 Brandl116aa622007-08-15 14:28:22 +00001153
Georg Brandl15a515f2009-09-17 22:11:49 +00001154 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1155 for the ``"store"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001156
1157 Example::
1158
1159 parser.add_option("-t", "--tracks", action="append", type="int")
1160
Éric Araujo713d3032010-11-18 16:38:46 +00001161 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
Georg Brandl116aa622007-08-15 14:28:22 +00001162 of::
1163
1164 options.tracks = []
1165 options.tracks.append(int("3"))
1166
Éric Araujo713d3032010-11-18 16:38:46 +00001167 If, a little later on, ``--tracks=4`` is seen, it does::
Georg Brandl116aa622007-08-15 14:28:22 +00001168
1169 options.tracks.append(int("4"))
1170
R David Murray14d66a92012-09-08 16:45:35 -04001171 The ``append`` action calls the ``append`` method on the current value of the
1172 option. This means that any default value specified must have an ``append``
1173 method. It also means that if the default value is non-empty, the default
1174 elements will be present in the parsed value for the option, with any values
1175 from the command line appended after those default values::
1176
1177 >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
1178 >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
1179 >>> opts.files
1180 ['~/.mypkg/defaults', 'overrides.mypkg']
1181
Georg Brandl15a515f2009-09-17 22:11:49 +00001182* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1183 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001184
Georg Brandl15a515f2009-09-17 22:11:49 +00001185 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1186 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1187 ``None``, and an empty list is automatically created the first time the option
1188 is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +00001189
Georg Brandl15a515f2009-09-17 22:11:49 +00001190* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001191
Georg Brandl15a515f2009-09-17 22:11:49 +00001192 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1193 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1194 first time.
Georg Brandl116aa622007-08-15 14:28:22 +00001195
1196 Example::
1197
1198 parser.add_option("-v", action="count", dest="verbosity")
1199
Éric Araujo713d3032010-11-18 16:38:46 +00001200 The first time ``-v`` is seen on the command line, :mod:`optparse` does the
Georg Brandl116aa622007-08-15 14:28:22 +00001201 equivalent of::
1202
1203 options.verbosity = 0
1204 options.verbosity += 1
1205
Éric Araujo713d3032010-11-18 16:38:46 +00001206 Every subsequent occurrence of ``-v`` results in ::
Georg Brandl116aa622007-08-15 14:28:22 +00001207
1208 options.verbosity += 1
1209
Georg Brandl15a515f2009-09-17 22:11:49 +00001210* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1211 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1212 :attr:`~Option.callback_kwargs`]
Georg Brandl116aa622007-08-15 14:28:22 +00001213
Georg Brandl15a515f2009-09-17 22:11:49 +00001214 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001215
1216 func(option, opt_str, value, parser, *args, **kwargs)
1217
1218 See section :ref:`optparse-option-callbacks` for more detail.
1219
Georg Brandl15a515f2009-09-17 22:11:49 +00001220* ``"help"``
Georg Brandl116aa622007-08-15 14:28:22 +00001221
Georg Brandl15a515f2009-09-17 22:11:49 +00001222 Prints a complete help message for all the options in the current option
1223 parser. The help message is constructed from the ``usage`` string passed to
1224 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1225 option.
Georg Brandl116aa622007-08-15 14:28:22 +00001226
Georg Brandl15a515f2009-09-17 22:11:49 +00001227 If no :attr:`~Option.help` string is supplied for an option, it will still be
1228 listed in the help message. To omit an option entirely, use the special value
1229 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl116aa622007-08-15 14:28:22 +00001230
Georg Brandl15a515f2009-09-17 22:11:49 +00001231 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1232 OptionParsers, so you do not normally need to create one.
Georg Brandl116aa622007-08-15 14:28:22 +00001233
1234 Example::
1235
1236 from optparse import OptionParser, SUPPRESS_HELP
1237
Georg Brandlee8783d2009-09-16 16:00:31 +00001238 # usually, a help option is added automatically, but that can
1239 # be suppressed using the add_help_option argument
1240 parser = OptionParser(add_help_option=False)
1241
1242 parser.add_option("-h", "--help", action="help")
Georg Brandl116aa622007-08-15 14:28:22 +00001243 parser.add_option("-v", action="store_true", dest="verbose",
1244 help="Be moderately verbose")
1245 parser.add_option("--file", dest="filename",
Georg Brandlee8783d2009-09-16 16:00:31 +00001246 help="Input file to read data from")
Georg Brandl116aa622007-08-15 14:28:22 +00001247 parser.add_option("--secret", help=SUPPRESS_HELP)
1248
Éric Araujo713d3032010-11-18 16:38:46 +00001249 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
Georg Brandl15a515f2009-09-17 22:11:49 +00001250 it will print something like the following help message to stdout (assuming
Ezio Melotti383ae952010-01-03 09:06:02 +00001251 ``sys.argv[0]`` is ``"foo.py"``):
1252
1253 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +00001254
Georg Brandl121ff822011-01-02 14:23:43 +00001255 Usage: foo.py [options]
Georg Brandl116aa622007-08-15 14:28:22 +00001256
Georg Brandl121ff822011-01-02 14:23:43 +00001257 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001258 -h, --help Show this help message and exit
1259 -v Be moderately verbose
1260 --file=FILENAME Input file to read data from
1261
1262 After printing the help message, :mod:`optparse` terminates your process with
1263 ``sys.exit(0)``.
1264
Georg Brandl15a515f2009-09-17 22:11:49 +00001265* ``"version"``
Georg Brandl116aa622007-08-15 14:28:22 +00001266
Georg Brandl15a515f2009-09-17 22:11:49 +00001267 Prints the version number supplied to the OptionParser to stdout and exits.
1268 The version number is actually formatted and printed by the
1269 ``print_version()`` method of OptionParser. Generally only relevant if the
1270 ``version`` argument is supplied to the OptionParser constructor. As with
1271 :attr:`~Option.help` options, you will rarely create ``version`` options,
1272 since :mod:`optparse` automatically adds them when needed.
Georg Brandl116aa622007-08-15 14:28:22 +00001273
1274
1275.. _optparse-standard-option-types:
1276
1277Standard option types
1278^^^^^^^^^^^^^^^^^^^^^
1279
Georg Brandl15a515f2009-09-17 22:11:49 +00001280:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1281``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1282option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +00001283
1284Arguments to string options are not checked or converted in any way: the text on
1285the command line is stored in the destination (or passed to the callback) as-is.
1286
Georg Brandl15a515f2009-09-17 22:11:49 +00001287Integer arguments (type ``"int"``) are parsed as follows:
Georg Brandl116aa622007-08-15 14:28:22 +00001288
1289* if the number starts with ``0x``, it is parsed as a hexadecimal number
1290
1291* if the number starts with ``0``, it is parsed as an octal number
1292
Georg Brandl9afde1c2007-11-01 20:32:30 +00001293* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl116aa622007-08-15 14:28:22 +00001294
1295* otherwise, the number is parsed as a decimal number
1296
1297
Georg Brandl15a515f2009-09-17 22:11:49 +00001298The conversion is done by calling :func:`int` with the appropriate base (2, 8,
129910, or 16). If this fails, so will :mod:`optparse`, although with a more useful
Georg Brandl5c106642007-11-29 17:41:05 +00001300error message.
Georg Brandl116aa622007-08-15 14:28:22 +00001301
Georg Brandl15a515f2009-09-17 22:11:49 +00001302``"float"`` and ``"complex"`` option arguments are converted directly with
1303:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl116aa622007-08-15 14:28:22 +00001304
Georg Brandl15a515f2009-09-17 22:11:49 +00001305``"choice"`` options are a subtype of ``"string"`` options. The
Georg Brandl682d7e02010-10-06 10:26:05 +00001306:attr:`~Option.choices` option attribute (a sequence of strings) defines the
Georg Brandl15a515f2009-09-17 22:11:49 +00001307set of allowed option arguments. :func:`optparse.check_choice` compares
1308user-supplied option arguments against this master list and raises
1309:exc:`OptionValueError` if an invalid string is given.
Georg Brandl116aa622007-08-15 14:28:22 +00001310
1311
1312.. _optparse-parsing-arguments:
1313
1314Parsing arguments
1315^^^^^^^^^^^^^^^^^
1316
1317The whole point of creating and populating an OptionParser is to call its
1318:meth:`parse_args` method::
1319
1320 (options, args) = parser.parse_args(args=None, values=None)
1321
1322where the input parameters are
1323
1324``args``
1325 the list of arguments to process (default: ``sys.argv[1:]``)
1326
1327``values``
Martin Panter7462b6492015-11-02 03:37:02 +00001328 an :class:`optparse.Values` object to store option arguments in (default: a
Georg Brandl09410122010-08-01 06:53:28 +00001329 new instance of :class:`Values`) -- if you give an existing object, the
1330 option defaults will not be initialized on it
Georg Brandl116aa622007-08-15 14:28:22 +00001331
1332and the return values are
1333
1334``options``
Georg Brandla6053b42009-09-01 08:11:14 +00001335 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl116aa622007-08-15 14:28:22 +00001336 instance created by :mod:`optparse`
1337
1338``args``
1339 the leftover positional arguments after all options have been processed
1340
1341The most common usage is to supply neither keyword argument. If you supply
Georg Brandl15a515f2009-09-17 22:11:49 +00001342``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl116aa622007-08-15 14:28:22 +00001343for every option argument stored to an option destination) and returned by
1344:meth:`parse_args`.
1345
1346If :meth:`parse_args` encounters any errors in the argument list, it calls the
1347OptionParser's :meth:`error` method with an appropriate end-user error message.
1348This ultimately terminates your process with an exit status of 2 (the
1349traditional Unix exit status for command-line errors).
1350
1351
1352.. _optparse-querying-manipulating-option-parser:
1353
1354Querying and manipulating your option parser
1355^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1356
Georg Brandl15a515f2009-09-17 22:11:49 +00001357The default behavior of the option parser can be customized slightly, and you
1358can also poke around your option parser and see what's there. OptionParser
1359provides several methods to help you out:
Georg Brandl116aa622007-08-15 14:28:22 +00001360
Georg Brandl15a515f2009-09-17 22:11:49 +00001361.. method:: OptionParser.disable_interspersed_args()
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001362
Éric Araujo713d3032010-11-18 16:38:46 +00001363 Set parsing to stop on the first non-option. For example, if ``-a`` and
1364 ``-b`` are both simple options that take no arguments, :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001365 normally accepts this syntax::
Georg Brandl116aa622007-08-15 14:28:22 +00001366
Georg Brandl15a515f2009-09-17 22:11:49 +00001367 prog -a arg1 -b arg2
1368
1369 and treats it as equivalent to ::
1370
1371 prog -a -b arg1 arg2
1372
1373 To disable this feature, call :meth:`disable_interspersed_args`. This
1374 restores traditional Unix syntax, where option parsing stops with the first
1375 non-option argument.
1376
1377 Use this if you have a command processor which runs another command which has
1378 options of its own and you want to make sure these options don't get
1379 confused. For example, each command might have a different set of options.
1380
1381.. method:: OptionParser.enable_interspersed_args()
1382
1383 Set parsing to not stop on the first non-option, allowing interspersing
1384 switches with command arguments. This is the default behavior.
1385
1386.. method:: OptionParser.get_option(opt_str)
1387
1388 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl116aa622007-08-15 14:28:22 +00001389 no options have that option string.
1390
Georg Brandl15a515f2009-09-17 22:11:49 +00001391.. method:: OptionParser.has_option(opt_str)
1392
1393 Return true if the OptionParser has an option with option string *opt_str*
Éric Araujo713d3032010-11-18 16:38:46 +00001394 (e.g., ``-q`` or ``--verbose``).
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001395
Georg Brandl15a515f2009-09-17 22:11:49 +00001396.. method:: OptionParser.remove_option(opt_str)
1397
1398 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1399 option is removed. If that option provided any other option strings, all of
1400 those option strings become invalid. If *opt_str* does not occur in any
1401 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001402
1403
1404.. _optparse-conflicts-between-options:
1405
1406Conflicts between options
1407^^^^^^^^^^^^^^^^^^^^^^^^^
1408
1409If you're not careful, it's easy to define options with conflicting option
1410strings::
1411
1412 parser.add_option("-n", "--dry-run", ...)
Serhiy Storchakadba90392016-05-10 12:01:23 +03001413 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001414 parser.add_option("-n", "--noisy", ...)
1415
1416(This is particularly true if you've defined your own OptionParser subclass with
1417some standard options.)
1418
1419Every time you add an option, :mod:`optparse` checks for conflicts with existing
1420options. If it finds any, it invokes the current conflict-handling mechanism.
1421You can set the conflict-handling mechanism either in the constructor::
1422
1423 parser = OptionParser(..., conflict_handler=handler)
1424
1425or with a separate call::
1426
1427 parser.set_conflict_handler(handler)
1428
1429The available conflict handlers are:
1430
Georg Brandl15a515f2009-09-17 22:11:49 +00001431 ``"error"`` (default)
1432 assume option conflicts are a programming error and raise
1433 :exc:`OptionConflictError`
Georg Brandl116aa622007-08-15 14:28:22 +00001434
Georg Brandl15a515f2009-09-17 22:11:49 +00001435 ``"resolve"``
Georg Brandl116aa622007-08-15 14:28:22 +00001436 resolve option conflicts intelligently (see below)
1437
1438
Benjamin Petersone5384b02008-10-04 22:00:42 +00001439As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl116aa622007-08-15 14:28:22 +00001440intelligently and add conflicting options to it::
1441
1442 parser = OptionParser(conflict_handler="resolve")
1443 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1444 parser.add_option("-n", "--noisy", ..., help="be noisy")
1445
1446At this point, :mod:`optparse` detects that a previously-added option is already
Éric Araujo713d3032010-11-18 16:38:46 +00001447using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1448it resolves the situation by removing ``-n`` from the earlier option's list of
1449option strings. Now ``--dry-run`` is the only way for the user to activate
Georg Brandl116aa622007-08-15 14:28:22 +00001450that option. If the user asks for help, the help message will reflect that::
1451
Georg Brandl121ff822011-01-02 14:23:43 +00001452 Options:
Georg Brandl116aa622007-08-15 14:28:22 +00001453 --dry-run do no harm
Serhiy Storchakadba90392016-05-10 12:01:23 +03001454 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001455 -n, --noisy be noisy
1456
1457It's possible to whittle away the option strings for a previously-added option
1458until there are none left, and the user has no way of invoking that option from
1459the command-line. In that case, :mod:`optparse` removes that option completely,
1460so it doesn't show up in help text or anywhere else. Carrying on with our
1461existing OptionParser::
1462
1463 parser.add_option("--dry-run", ..., help="new dry-run option")
1464
Éric Araujo713d3032010-11-18 16:38:46 +00001465At this point, the original ``-n``/``--dry-run`` option is no longer
Georg Brandl116aa622007-08-15 14:28:22 +00001466accessible, so :mod:`optparse` removes it, leaving this help text::
1467
Georg Brandl121ff822011-01-02 14:23:43 +00001468 Options:
Serhiy Storchakadba90392016-05-10 12:01:23 +03001469 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001470 -n, --noisy be noisy
1471 --dry-run new dry-run option
1472
1473
1474.. _optparse-cleanup:
1475
1476Cleanup
1477^^^^^^^
1478
1479OptionParser instances have several cyclic references. This should not be a
1480problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandl15a515f2009-09-17 22:11:49 +00001481references explicitly by calling :meth:`~OptionParser.destroy` on your
1482OptionParser once you are done with it. This is particularly useful in
1483long-running applications where large object graphs are reachable from your
1484OptionParser.
Georg Brandl116aa622007-08-15 14:28:22 +00001485
1486
1487.. _optparse-other-methods:
1488
1489Other methods
1490^^^^^^^^^^^^^
1491
1492OptionParser supports several other public methods:
1493
Georg Brandl15a515f2009-09-17 22:11:49 +00001494.. method:: OptionParser.set_usage(usage)
Georg Brandl116aa622007-08-15 14:28:22 +00001495
Georg Brandl15a515f2009-09-17 22:11:49 +00001496 Set the usage string according to the rules described above for the ``usage``
1497 constructor keyword argument. Passing ``None`` sets the default usage
1498 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl116aa622007-08-15 14:28:22 +00001499
Ezio Melotti1ce43192010-01-04 21:53:17 +00001500.. method:: OptionParser.print_usage(file=None)
1501
1502 Print the usage message for the current program (``self.usage``) to *file*
Éric Araujo713d3032010-11-18 16:38:46 +00001503 (default stdout). Any occurrence of the string ``%prog`` in ``self.usage``
Ezio Melotti1ce43192010-01-04 21:53:17 +00001504 is replaced with the name of the current program. Does nothing if
1505 ``self.usage`` is empty or not defined.
1506
1507.. method:: OptionParser.get_usage()
1508
1509 Same as :meth:`print_usage` but returns the usage string instead of
1510 printing it.
1511
Georg Brandl15a515f2009-09-17 22:11:49 +00001512.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +00001513
Georg Brandl15a515f2009-09-17 22:11:49 +00001514 Set default values for several option destinations at once. Using
1515 :meth:`set_defaults` is the preferred way to set default values for options,
1516 since multiple options can share the same destination. For example, if
1517 several "mode" options all set the same destination, any one of them can set
1518 the default, and the last one wins::
Georg Brandl116aa622007-08-15 14:28:22 +00001519
Georg Brandl15a515f2009-09-17 22:11:49 +00001520 parser.add_option("--advanced", action="store_const",
1521 dest="mode", const="advanced",
1522 default="novice") # overridden below
1523 parser.add_option("--novice", action="store_const",
1524 dest="mode", const="novice",
1525 default="advanced") # overrides above setting
Georg Brandl116aa622007-08-15 14:28:22 +00001526
Georg Brandl15a515f2009-09-17 22:11:49 +00001527 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl116aa622007-08-15 14:28:22 +00001528
Georg Brandl15a515f2009-09-17 22:11:49 +00001529 parser.set_defaults(mode="advanced")
1530 parser.add_option("--advanced", action="store_const",
1531 dest="mode", const="advanced")
1532 parser.add_option("--novice", action="store_const",
1533 dest="mode", const="novice")
Georg Brandl116aa622007-08-15 14:28:22 +00001534
Georg Brandl116aa622007-08-15 14:28:22 +00001535
1536.. _optparse-option-callbacks:
1537
1538Option Callbacks
1539----------------
1540
1541When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1542needs, you have two choices: extend :mod:`optparse` or define a callback option.
1543Extending :mod:`optparse` is more general, but overkill for a lot of simple
1544cases. Quite often a simple callback is all you need.
1545
1546There are two steps to defining a callback option:
1547
Georg Brandl15a515f2009-09-17 22:11:49 +00001548* define the option itself using the ``"callback"`` action
Georg Brandl116aa622007-08-15 14:28:22 +00001549
1550* write the callback; this is a function (or method) that takes at least four
1551 arguments, as described below
1552
1553
1554.. _optparse-defining-callback-option:
1555
1556Defining a callback option
1557^^^^^^^^^^^^^^^^^^^^^^^^^^
1558
1559As always, the easiest way to define a callback option is by using the
Georg Brandl15a515f2009-09-17 22:11:49 +00001560:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1561only option attribute you must specify is ``callback``, the function to call::
Georg Brandl116aa622007-08-15 14:28:22 +00001562
1563 parser.add_option("-c", action="callback", callback=my_callback)
1564
1565``callback`` is a function (or other callable object), so you must have already
1566defined ``my_callback()`` when you create this callback option. In this simple
Éric Araujo713d3032010-11-18 16:38:46 +00001567case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
Georg Brandl116aa622007-08-15 14:28:22 +00001568which usually means that the option takes no arguments---the mere presence of
Éric Araujo713d3032010-11-18 16:38:46 +00001569``-c`` on the command-line is all it needs to know. In some
Georg Brandl116aa622007-08-15 14:28:22 +00001570circumstances, though, you might want your callback to consume an arbitrary
1571number of command-line arguments. This is where writing callbacks gets tricky;
1572it's covered later in this section.
1573
1574:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandl15a515f2009-09-17 22:11:49 +00001575will only pass additional arguments if you specify them via
1576:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1577minimal callback function signature is::
Georg Brandl116aa622007-08-15 14:28:22 +00001578
1579 def my_callback(option, opt, value, parser):
1580
1581The four arguments to a callback are described below.
1582
1583There are several other option attributes that you can supply when you define a
1584callback option:
1585
Georg Brandl15a515f2009-09-17 22:11:49 +00001586:attr:`~Option.type`
1587 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1588 instructs :mod:`optparse` to consume one argument and convert it to
1589 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1590 though, :mod:`optparse` passes it to your callback function.
Georg Brandl116aa622007-08-15 14:28:22 +00001591
Georg Brandl15a515f2009-09-17 22:11:49 +00001592:attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001593 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001594 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1595 :attr:`~Option.type`. It then passes a tuple of converted values to your
1596 callback.
Georg Brandl116aa622007-08-15 14:28:22 +00001597
Georg Brandl15a515f2009-09-17 22:11:49 +00001598:attr:`~Option.callback_args`
Georg Brandl116aa622007-08-15 14:28:22 +00001599 a tuple of extra positional arguments to pass to the callback
1600
Georg Brandl15a515f2009-09-17 22:11:49 +00001601:attr:`~Option.callback_kwargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001602 a dictionary of extra keyword arguments to pass to the callback
1603
1604
1605.. _optparse-how-callbacks-called:
1606
1607How callbacks are called
1608^^^^^^^^^^^^^^^^^^^^^^^^
1609
1610All callbacks are called as follows::
1611
1612 func(option, opt_str, value, parser, *args, **kwargs)
1613
1614where
1615
1616``option``
1617 is the Option instance that's calling the callback
1618
1619``opt_str``
1620 is the option string seen on the command-line that's triggering the callback.
Georg Brandl15a515f2009-09-17 22:11:49 +00001621 (If an abbreviated long option was used, ``opt_str`` will be the full,
Éric Araujo713d3032010-11-18 16:38:46 +00001622 canonical option string---e.g. if the user puts ``--foo`` on the
1623 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
Georg Brandl15a515f2009-09-17 22:11:49 +00001624 ``"--foobar"``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001625
1626``value``
1627 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001628 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1629 the type implied by the option's type. If :attr:`~Option.type` for this option is
1630 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001631 > 1, ``value`` will be a tuple of values of the appropriate type.
1632
1633``parser``
Georg Brandl15a515f2009-09-17 22:11:49 +00001634 is the OptionParser instance driving the whole thing, mainly useful because
1635 you can access some other interesting data through its instance attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001636
1637 ``parser.largs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001638 the current list of leftover arguments, ie. arguments that have been
1639 consumed but are neither options nor option arguments. Feel free to modify
1640 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1641 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001642
1643 ``parser.rargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001644 the current list of remaining arguments, ie. with ``opt_str`` and
1645 ``value`` (if applicable) removed, and only the arguments following them
1646 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1647 arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001648
1649 ``parser.values``
1650 the object where option values are by default stored (an instance of
Georg Brandl15a515f2009-09-17 22:11:49 +00001651 optparse.OptionValues). This lets callbacks use the same mechanism as the
1652 rest of :mod:`optparse` for storing option values; you don't need to mess
1653 around with globals or closures. You can also access or modify the
1654 value(s) of any options already encountered on the command-line.
Georg Brandl116aa622007-08-15 14:28:22 +00001655
1656``args``
Georg Brandl15a515f2009-09-17 22:11:49 +00001657 is a tuple of arbitrary positional arguments supplied via the
1658 :attr:`~Option.callback_args` option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001659
1660``kwargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001661 is a dictionary of arbitrary keyword arguments supplied via
1662 :attr:`~Option.callback_kwargs`.
Georg Brandl116aa622007-08-15 14:28:22 +00001663
1664
1665.. _optparse-raising-errors-in-callback:
1666
1667Raising errors in a callback
1668^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1669
Georg Brandl15a515f2009-09-17 22:11:49 +00001670The callback function should raise :exc:`OptionValueError` if there are any
1671problems with the option or its argument(s). :mod:`optparse` catches this and
1672terminates the program, printing the error message you supply to stderr. Your
1673message should be clear, concise, accurate, and mention the option at fault.
1674Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl116aa622007-08-15 14:28:22 +00001675
1676
1677.. _optparse-callback-example-1:
1678
1679Callback example 1: trivial callback
1680^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1681
1682Here's an example of a callback option that takes no arguments, and simply
1683records that the option was seen::
1684
1685 def record_foo_seen(option, opt_str, value, parser):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001686 parser.values.saw_foo = True
Georg Brandl116aa622007-08-15 14:28:22 +00001687
1688 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1689
Georg Brandl15a515f2009-09-17 22:11:49 +00001690Of course, you could do that with the ``"store_true"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001691
1692
1693.. _optparse-callback-example-2:
1694
1695Callback example 2: check option order
1696^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1697
Éric Araujo713d3032010-11-18 16:38:46 +00001698Here's a slightly more interesting example: record the fact that ``-a`` is
1699seen, but blow up if it comes after ``-b`` in the command-line. ::
Georg Brandl116aa622007-08-15 14:28:22 +00001700
1701 def check_order(option, opt_str, value, parser):
1702 if parser.values.b:
1703 raise OptionValueError("can't use -a after -b")
1704 parser.values.a = 1
Serhiy Storchakadba90392016-05-10 12:01:23 +03001705 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001706 parser.add_option("-a", action="callback", callback=check_order)
1707 parser.add_option("-b", action="store_true", dest="b")
1708
1709
1710.. _optparse-callback-example-3:
1711
1712Callback example 3: check option order (generalized)
1713^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1714
1715If you want to re-use this callback for several similar options (set a flag, but
Éric Araujo713d3032010-11-18 16:38:46 +00001716blow up if ``-b`` has already been seen), it needs a bit of work: the error
Georg Brandl116aa622007-08-15 14:28:22 +00001717message and the flag that it sets must be generalized. ::
1718
1719 def check_order(option, opt_str, value, parser):
1720 if parser.values.b:
1721 raise OptionValueError("can't use %s after -b" % opt_str)
1722 setattr(parser.values, option.dest, 1)
Serhiy Storchakadba90392016-05-10 12:01:23 +03001723 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001724 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1725 parser.add_option("-b", action="store_true", dest="b")
1726 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1727
1728
1729.. _optparse-callback-example-4:
1730
1731Callback example 4: check arbitrary condition
1732^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1733
1734Of course, you could put any condition in there---you're not limited to checking
1735the values of already-defined options. For example, if you have options that
1736should not be called when the moon is full, all you have to do is this::
1737
1738 def check_moon(option, opt_str, value, parser):
1739 if is_moon_full():
1740 raise OptionValueError("%s option invalid when moon is full"
1741 % opt_str)
1742 setattr(parser.values, option.dest, 1)
Serhiy Storchakadba90392016-05-10 12:01:23 +03001743 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001744 parser.add_option("--foo",
1745 action="callback", callback=check_moon, dest="foo")
1746
1747(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1748
1749
1750.. _optparse-callback-example-5:
1751
1752Callback example 5: fixed arguments
1753^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1754
1755Things get slightly more interesting when you define callback options that take
1756a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandl15a515f2009-09-17 22:11:49 +00001757is similar to defining a ``"store"`` or ``"append"`` option: if you define
1758:attr:`~Option.type`, then the option takes one argument that must be
1759convertible to that type; if you further define :attr:`~Option.nargs`, then the
1760option takes :attr:`~Option.nargs` arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001761
Georg Brandl15a515f2009-09-17 22:11:49 +00001762Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl116aa622007-08-15 14:28:22 +00001763
1764 def store_value(option, opt_str, value, parser):
1765 setattr(parser.values, option.dest, value)
Serhiy Storchakadba90392016-05-10 12:01:23 +03001766 ...
Georg Brandl116aa622007-08-15 14:28:22 +00001767 parser.add_option("--foo",
1768 action="callback", callback=store_value,
1769 type="int", nargs=3, dest="foo")
1770
1771Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1772them to integers for you; all you have to do is store them. (Or whatever;
1773obviously you don't need a callback for this example.)
1774
1775
1776.. _optparse-callback-example-6:
1777
1778Callback example 6: variable arguments
1779^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1780
1781Things get hairy when you want an option to take a variable number of arguments.
1782For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1783built-in capabilities for it. And you have to deal with certain intricacies of
1784conventional Unix command-line parsing that :mod:`optparse` normally handles for
1785you. In particular, callbacks should implement the conventional rules for bare
Éric Araujo713d3032010-11-18 16:38:46 +00001786``--`` and ``-`` arguments:
Georg Brandl116aa622007-08-15 14:28:22 +00001787
Éric Araujo713d3032010-11-18 16:38:46 +00001788* either ``--`` or ``-`` can be option arguments
Georg Brandl116aa622007-08-15 14:28:22 +00001789
Éric Araujo713d3032010-11-18 16:38:46 +00001790* bare ``--`` (if not the argument to some option): halt command-line
1791 processing and discard the ``--``
Georg Brandl116aa622007-08-15 14:28:22 +00001792
Éric Araujo713d3032010-11-18 16:38:46 +00001793* bare ``-`` (if not the argument to some option): halt command-line
1794 processing but keep the ``-`` (append it to ``parser.largs``)
Georg Brandl116aa622007-08-15 14:28:22 +00001795
1796If you want an option that takes a variable number of arguments, there are
1797several subtle, tricky issues to worry about. The exact implementation you
1798choose will be based on which trade-offs you're willing to make for your
1799application (which is why :mod:`optparse` doesn't support this sort of thing
1800directly).
1801
1802Nevertheless, here's a stab at a callback for an option with variable
1803arguments::
1804
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001805 def vararg_callback(option, opt_str, value, parser):
1806 assert value is None
1807 value = []
Georg Brandl116aa622007-08-15 14:28:22 +00001808
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001809 def floatable(str):
1810 try:
1811 float(str)
1812 return True
1813 except ValueError:
1814 return False
Georg Brandl116aa622007-08-15 14:28:22 +00001815
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001816 for arg in parser.rargs:
1817 # stop on --foo like options
1818 if arg[:2] == "--" and len(arg) > 2:
1819 break
1820 # stop on -a, but not on -3 or -3.0
1821 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1822 break
1823 value.append(arg)
1824
1825 del parser.rargs[:len(value)]
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001826 setattr(parser.values, option.dest, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001827
Serhiy Storchakadba90392016-05-10 12:01:23 +03001828 ...
1829 parser.add_option("-c", "--callback", dest="vararg_attr",
1830 action="callback", callback=vararg_callback)
Georg Brandl116aa622007-08-15 14:28:22 +00001831
Georg Brandl116aa622007-08-15 14:28:22 +00001832
1833.. _optparse-extending-optparse:
1834
1835Extending :mod:`optparse`
1836-------------------------
1837
1838Since the two major controlling factors in how :mod:`optparse` interprets
1839command-line options are the action and type of each option, the most likely
1840direction of extension is to add new actions and new types.
1841
1842
1843.. _optparse-adding-new-types:
1844
1845Adding new types
1846^^^^^^^^^^^^^^^^
1847
1848To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandl15a515f2009-09-17 22:11:49 +00001849:class:`Option` class. This class has a couple of attributes that define
1850:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl116aa622007-08-15 14:28:22 +00001851
Georg Brandl15a515f2009-09-17 22:11:49 +00001852.. attribute:: Option.TYPES
Georg Brandl116aa622007-08-15 14:28:22 +00001853
Georg Brandl15a515f2009-09-17 22:11:49 +00001854 A tuple of type names; in your subclass, simply define a new tuple
1855 :attr:`TYPES` that builds on the standard one.
Georg Brandl116aa622007-08-15 14:28:22 +00001856
Georg Brandl15a515f2009-09-17 22:11:49 +00001857.. attribute:: Option.TYPE_CHECKER
Georg Brandl116aa622007-08-15 14:28:22 +00001858
Georg Brandl15a515f2009-09-17 22:11:49 +00001859 A dictionary mapping type names to type-checking functions. A type-checking
1860 function has the following signature::
Georg Brandl116aa622007-08-15 14:28:22 +00001861
Georg Brandl15a515f2009-09-17 22:11:49 +00001862 def check_mytype(option, opt, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001863
Georg Brandl15a515f2009-09-17 22:11:49 +00001864 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
Éric Araujo713d3032010-11-18 16:38:46 +00001865 (e.g., ``-f``), and ``value`` is the string from the command line that must
Georg Brandl15a515f2009-09-17 22:11:49 +00001866 be checked and converted to your desired type. ``check_mytype()`` should
1867 return an object of the hypothetical type ``mytype``. The value returned by
1868 a type-checking function will wind up in the OptionValues instance returned
1869 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1870 ``value`` parameter.
1871
1872 Your type-checking function should raise :exc:`OptionValueError` if it
1873 encounters any problems. :exc:`OptionValueError` takes a single string
1874 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1875 method, which in turn prepends the program name and the string ``"error:"``
1876 and prints everything to stderr before terminating the process.
1877
1878Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl116aa622007-08-15 14:28:22 +00001879parse Python-style complex numbers on the command line. (This is even sillier
1880than it used to be, because :mod:`optparse` 1.3 added built-in support for
1881complex numbers, but never mind.)
1882
1883First, the necessary imports::
1884
1885 from copy import copy
1886 from optparse import Option, OptionValueError
1887
1888You need to define your type-checker first, since it's referred to later (in the
Georg Brandl15a515f2009-09-17 22:11:49 +00001889:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl116aa622007-08-15 14:28:22 +00001890
1891 def check_complex(option, opt, value):
1892 try:
1893 return complex(value)
1894 except ValueError:
1895 raise OptionValueError(
1896 "option %s: invalid complex value: %r" % (opt, value))
1897
1898Finally, the Option subclass::
1899
1900 class MyOption (Option):
1901 TYPES = Option.TYPES + ("complex",)
1902 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1903 TYPE_CHECKER["complex"] = check_complex
1904
1905(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandl15a515f2009-09-17 22:11:49 +00001906up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1907Option class. This being Python, nothing stops you from doing that except good
1908manners and common sense.)
Georg Brandl116aa622007-08-15 14:28:22 +00001909
1910That's it! Now you can write a script that uses the new option type just like
1911any other :mod:`optparse`\ -based script, except you have to instruct your
1912OptionParser to use MyOption instead of Option::
1913
1914 parser = OptionParser(option_class=MyOption)
1915 parser.add_option("-c", type="complex")
1916
1917Alternately, you can build your own option list and pass it to OptionParser; if
1918you don't use :meth:`add_option` in the above way, you don't need to tell
1919OptionParser which option class to use::
1920
1921 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1922 parser = OptionParser(option_list=option_list)
1923
1924
1925.. _optparse-adding-new-actions:
1926
1927Adding new actions
1928^^^^^^^^^^^^^^^^^^
1929
1930Adding new actions is a bit trickier, because you have to understand that
1931:mod:`optparse` has a couple of classifications for actions:
1932
1933"store" actions
1934 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandl15a515f2009-09-17 22:11:49 +00001935 current OptionValues instance; these options require a :attr:`~Option.dest`
1936 attribute to be supplied to the Option constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001937
1938"typed" actions
Georg Brandl15a515f2009-09-17 22:11:49 +00001939 actions that take a value from the command line and expect it to be of a
1940 certain type; or rather, a string that can be converted to a certain type.
1941 These options require a :attr:`~Option.type` attribute to the Option
1942 constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001943
Georg Brandl15a515f2009-09-17 22:11:49 +00001944These are overlapping sets: some default "store" actions are ``"store"``,
1945``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1946actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001947
1948When you add an action, you need to categorize it by listing it in at least one
1949of the following class attributes of Option (all are lists of strings):
1950
Georg Brandl15a515f2009-09-17 22:11:49 +00001951.. attribute:: Option.ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001952
Georg Brandl15a515f2009-09-17 22:11:49 +00001953 All actions must be listed in ACTIONS.
Georg Brandl116aa622007-08-15 14:28:22 +00001954
Georg Brandl15a515f2009-09-17 22:11:49 +00001955.. attribute:: Option.STORE_ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001956
Georg Brandl15a515f2009-09-17 22:11:49 +00001957 "store" actions are additionally listed here.
1958
1959.. attribute:: Option.TYPED_ACTIONS
1960
1961 "typed" actions are additionally listed here.
1962
1963.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1964
1965 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl116aa622007-08-15 14:28:22 +00001966 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001967 assigns the default type, ``"string"``, to options with no explicit type
1968 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001969
1970In order to actually implement your new action, you must override Option's
1971:meth:`take_action` method and add a case that recognizes your action.
1972
Georg Brandl15a515f2009-09-17 22:11:49 +00001973For example, let's add an ``"extend"`` action. This is similar to the standard
1974``"append"`` action, but instead of taking a single value from the command-line
1975and appending it to an existing list, ``"extend"`` will take multiple values in
1976a single comma-delimited string, and extend an existing list with them. That
Éric Araujo713d3032010-11-18 16:38:46 +00001977is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
Georg Brandl15a515f2009-09-17 22:11:49 +00001978line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001979
1980 --names=foo,bar --names blah --names ding,dong
1981
1982would result in a list ::
1983
1984 ["foo", "bar", "blah", "ding", "dong"]
1985
1986Again we define a subclass of Option::
1987
Ezio Melotti383ae952010-01-03 09:06:02 +00001988 class MyOption(Option):
Georg Brandl116aa622007-08-15 14:28:22 +00001989
1990 ACTIONS = Option.ACTIONS + ("extend",)
1991 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1992 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1993 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1994
1995 def take_action(self, action, dest, opt, value, values, parser):
1996 if action == "extend":
1997 lvalue = value.split(",")
1998 values.ensure_value(dest, []).extend(lvalue)
1999 else:
2000 Option.take_action(
2001 self, action, dest, opt, value, values, parser)
2002
2003Features of note:
2004
Georg Brandl15a515f2009-09-17 22:11:49 +00002005* ``"extend"`` both expects a value on the command-line and stores that value
2006 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
2007 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00002008
Georg Brandl15a515f2009-09-17 22:11:49 +00002009* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
2010 ``"extend"`` actions, we put the ``"extend"`` action in
2011 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl116aa622007-08-15 14:28:22 +00002012
2013* :meth:`MyOption.take_action` implements just this one new action, and passes
2014 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00002015 actions.
Georg Brandl116aa622007-08-15 14:28:22 +00002016
Georg Brandl15a515f2009-09-17 22:11:49 +00002017* ``values`` is an instance of the optparse_parser.Values class, which provides
2018 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
2019 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00002020
2021 values.ensure_value(attr, value)
2022
2023 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandl15a515f2009-09-17 22:11:49 +00002024 ensure_value() first sets it to ``value``, and then returns 'value. This is
2025 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
2026 of which accumulate data in a variable and expect that variable to be of a
2027 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl116aa622007-08-15 14:28:22 +00002028 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandl15a515f2009-09-17 22:11:49 +00002029 about setting a default value for the option destinations in question; they
2030 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl116aa622007-08-15 14:28:22 +00002031 getting it right when it's needed.