blob: d2f7b83e20837c3b8cfb559f0a94294c4f67cc48 [file] [log] [blame]
Steven Betharde9330e72010-03-02 08:38:09 +00001:mod:`optparse` --- Parser for command line options
2===================================================
Georg Brandl8ec7f652007-08-15 14:28:01 +00003
4.. module:: optparse
Steven Betharde9330e72010-03-02 08:38:09 +00005 :synopsis: Command-line option parsing library.
Steven Bethard74bd9cf2010-05-24 02:38:00 +00006 :deprecated:
Georg Brandl8ec7f652007-08-15 14:28:01 +00007
Steven Bethard74bd9cf2010-05-24 02:38:00 +00008.. deprecated:: 2.7
9 The :mod:`optparse` module is deprecated and will not be developed further;
10 development will continue with the :mod:`argparse` module.
11
12.. moduleauthor:: Greg Ward <gward@python.net>
Georg Brandl8ec7f652007-08-15 14:28:01 +000013
14.. versionadded:: 2.3
15
16.. sectionauthor:: Greg Ward <gward@python.net>
17
18
Georg Brandlb926ebb2009-09-17 17:14:04 +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 Brandl8ec7f652007-08-15 14:28:01 +000025
Georg Brandlb926ebb2009-09-17 17:14:04 +000026Here's an example of using :mod:`optparse` in a simple script::
Georg Brandl8ec7f652007-08-15 14:28:01 +000027
28 from optparse import OptionParser
29 [...]
30 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 Brandlb926ebb2009-09-17 17:14:04 +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 Brandl8ec7f652007-08-15 14:28:01 +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 Melotti5129ed32010-01-03 09:01:27 +000063and :mod:`optparse` will print out a brief summary of your script's options:
64
65.. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +000066
67 usage: <yourscript> [options]
68
69 options:
70 -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 Brandl8ec7f652007-08-15 14:28:01 +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 Brandlb926ebb2009-09-17 17:14:04 +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 Brandl8ec7f652007-08-15 14:28:01 +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
Andrew M. Kuchling810f8072008-09-06 13:04:02 +0000106option
Georg Brandlb926ebb2009-09-17 17:14:04 +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 Araujoa8132ec2010-12-16 03:53:53 +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 Brandlb926ebb2009-09-17 17:14:04 +0000114 only two option syntaxes provided by :mod:`optparse`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000115
116 Some other option syntaxes that the world has seen include:
117
Éric Araujoa8132ec2010-12-16 03:53:53 +0000118 * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
Georg Brandl8ec7f652007-08-15 14:28:01 +0000119 as multiple options merged into a single argument)
120
Éric Araujoa8132ec2010-12-16 03:53:53 +0000121 * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Araujoa8132ec2010-12-16 03:53:53 +0000126 ``+f``, ``+rgb``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
Éric Araujoa8132ec2010-12-16 03:53:53 +0000128 * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``,
129 ``/file``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000130
Georg Brandlb926ebb2009-09-17 17:14:04 +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 Brandl8ec7f652007-08-15 14:28:01 +0000135
136option argument
Georg Brandlb926ebb2009-09-17 17:14:04 +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 Melotti5129ed32010-01-03 09:01:27 +0000140 their option:
141
142 .. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143
144 -f foo
145 --file foo
146
Ezio Melotti5129ed32010-01-03 09:01:27 +0000147 or included in the same argument:
148
149 .. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
151 -ffoo
152 --file=foo
153
Georg Brandlb926ebb2009-09-17 17:14:04 +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 Araujoa8132ec2010-12-16 03:53:53 +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 Brandlb926ebb2009-09-17 17:14:04 +0000160 support this feature.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161
162positional argument
163 something leftover in the argument list after options have been parsed, i.e.
Georg Brandlb926ebb2009-09-17 17:14:04 +0000164 after options and their arguments have been parsed and removed from the
165 argument list.
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Brandlb926ebb2009-09-17 17:14:04 +0000170 prevent you from implementing required options, but doesn't give you much
Georg Brandl66d8d692009-12-28 08:48:24 +0000171 help at it either.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000172
173For example, consider this hypothetical command-line::
174
175 prog -v --report /tmp/report.txt foo bar
176
Éric Araujoa8132ec2010-12-16 03:53:53 +0000177``-v`` and ``--report`` are both options. Assuming that ``--report``
178takes one argument, ``/tmp/report.txt`` is an option argument. ``foo`` and
179``bar`` are positional arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +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 Brandl8ec7f652007-08-15 14:28:01 +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
256 [...]
257 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 Araujoa8132ec2010-12-16 03:53:53 +0000264Each option has one or more option strings, such as ``-f`` or ``--file``,
Georg Brandl8ec7f652007-08-15 14:28:01 +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
277The option strings passed to :meth:`add_option` are effectively labels for the
278option defined by that call. For brevity, we will frequently refer to
279*encountering an option* on the command line; in reality, :mod:`optparse`
280encounters *option strings* and looks up options from them.
281
282Once all of your options are defined, instruct :mod:`optparse` to parse your
283program's command line::
284
285 (options, args) = parser.parse_args()
286
287(If you like, you can pass a custom argument list to :meth:`parse_args`, but
288that's rarely necessary: by default it uses ``sys.argv[1:]``.)
289
290:meth:`parse_args` returns two values:
291
292* ``options``, an object containing values for all of your options---e.g. if
Éric Araujoa8132ec2010-12-16 03:53:53 +0000293 ``--file`` takes a single string argument, then ``options.file`` will be the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000294 filename supplied by the user, or ``None`` if the user did not supply that
295 option
296
297* ``args``, the list of positional arguments leftover after parsing options
298
299This tutorial section only covers the four most important option attributes:
Georg Brandlb926ebb2009-09-17 17:14:04 +0000300:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
301(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
302most fundamental.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000303
304
305.. _optparse-understanding-option-actions:
306
307Understanding option actions
308^^^^^^^^^^^^^^^^^^^^^^^^^^^^
309
310Actions tell :mod:`optparse` what to do when it encounters an option on the
311command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
312adding new actions is an advanced topic covered in section
Georg Brandlb926ebb2009-09-17 17:14:04 +0000313:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
314a value in some variable---for example, take a string from the command line and
315store it in an attribute of ``options``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000316
317If you don't specify an option action, :mod:`optparse` defaults to ``store``.
318
319
320.. _optparse-store-action:
321
322The store action
323^^^^^^^^^^^^^^^^
324
325The most common option action is ``store``, which tells :mod:`optparse` to take
326the next argument (or the remainder of the current argument), ensure that it is
327of the correct type, and store it to your chosen destination.
328
329For example::
330
331 parser.add_option("-f", "--file",
332 action="store", type="string", dest="filename")
333
334Now let's make up a fake command line and ask :mod:`optparse` to parse it::
335
336 args = ["-f", "foo.txt"]
337 (options, args) = parser.parse_args(args)
338
Éric Araujoa8132ec2010-12-16 03:53:53 +0000339When :mod:`optparse` sees the option string ``-f``, it consumes the next
340argument, ``foo.txt``, and stores it in ``options.filename``. So, after this
Georg Brandl8ec7f652007-08-15 14:28:01 +0000341call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
342
343Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
344Here's an option that expects an integer argument::
345
346 parser.add_option("-n", type="int", dest="num")
347
348Note that this option has no long option string, which is perfectly acceptable.
349Also, there's no explicit action, since the default is ``store``.
350
351Let's parse another fake command-line. This time, we'll jam the option argument
Éric Araujoa8132ec2010-12-16 03:53:53 +0000352right up against the option: since ``-n42`` (one argument) is equivalent to
353``-n 42`` (two arguments), the code ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000354
355 (options, args) = parser.parse_args(["-n42"])
356 print options.num
357
Éric Araujoa8132ec2010-12-16 03:53:53 +0000358will print ``42``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000359
360If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
361the fact that the default action is ``store``, that means our first example can
362be a lot shorter::
363
364 parser.add_option("-f", "--file", dest="filename")
365
366If you don't supply a destination, :mod:`optparse` figures out a sensible
367default from the option strings: if the first long option string is
Éric Araujoa8132ec2010-12-16 03:53:53 +0000368``--foo-bar``, then the default destination is ``foo_bar``. If there are no
Georg Brandl8ec7f652007-08-15 14:28:01 +0000369long option strings, :mod:`optparse` looks at the first short option string: the
Éric Araujoa8132ec2010-12-16 03:53:53 +0000370default destination for ``-f`` is ``f``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000371
372:mod:`optparse` also includes built-in ``long`` and ``complex`` types. Adding
373types is covered in section :ref:`optparse-extending-optparse`.
374
375
376.. _optparse-handling-boolean-options:
377
378Handling boolean (flag) options
379^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
380
381Flag options---set a variable to true or false when a particular option is seen
382---are quite common. :mod:`optparse` supports them with two separate actions,
383``store_true`` and ``store_false``. For example, you might have a ``verbose``
Éric Araujoa8132ec2010-12-16 03:53:53 +0000384flag that is turned on with ``-v`` and off with ``-q``::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000385
386 parser.add_option("-v", action="store_true", dest="verbose")
387 parser.add_option("-q", action="store_false", dest="verbose")
388
389Here we have two different options with the same destination, which is perfectly
390OK. (It just means you have to be a bit careful when setting default values---
391see below.)
392
Éric Araujoa8132ec2010-12-16 03:53:53 +0000393When :mod:`optparse` encounters ``-v`` on the command line, it sets
394``options.verbose`` to ``True``; when it encounters ``-q``,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000395``options.verbose`` is set to ``False``.
396
397
398.. _optparse-other-actions:
399
400Other actions
401^^^^^^^^^^^^^
402
403Some other actions supported by :mod:`optparse` are:
404
Georg Brandlb926ebb2009-09-17 17:14:04 +0000405``"store_const"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000406 store a constant value
407
Georg Brandlb926ebb2009-09-17 17:14:04 +0000408``"append"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000409 append this option's argument to a list
410
Georg Brandlb926ebb2009-09-17 17:14:04 +0000411``"count"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000412 increment a counter by one
413
Georg Brandlb926ebb2009-09-17 17:14:04 +0000414``"callback"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000415 call a specified function
416
417These are covered in section :ref:`optparse-reference-guide`, Reference Guide
418and section :ref:`optparse-option-callbacks`.
419
420
421.. _optparse-default-values:
422
423Default values
424^^^^^^^^^^^^^^
425
426All of the above examples involve setting some variable (the "destination") when
427certain command-line options are seen. What happens if those options are never
428seen? Since we didn't supply any defaults, they are all set to ``None``. This
429is usually fine, but sometimes you want more control. :mod:`optparse` lets you
430supply a default value for each destination, which is assigned before the
431command line is parsed.
432
433First, consider the verbose/quiet example. If we want :mod:`optparse` to set
Éric Araujoa8132ec2010-12-16 03:53:53 +0000434``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000435
436 parser.add_option("-v", action="store_true", dest="verbose", default=True)
437 parser.add_option("-q", action="store_false", dest="verbose")
438
439Since default values apply to the *destination* rather than to any particular
440option, and these two options happen to have the same destination, this is
441exactly equivalent::
442
443 parser.add_option("-v", action="store_true", dest="verbose")
444 parser.add_option("-q", action="store_false", dest="verbose", default=True)
445
446Consider this::
447
448 parser.add_option("-v", action="store_true", dest="verbose", default=False)
449 parser.add_option("-q", action="store_false", dest="verbose", default=True)
450
451Again, the default value for ``verbose`` will be ``True``: the last default
452value supplied for any particular destination is the one that counts.
453
454A clearer way to specify default values is the :meth:`set_defaults` method of
455OptionParser, which you can call at any time before calling :meth:`parse_args`::
456
457 parser.set_defaults(verbose=True)
458 parser.add_option(...)
459 (options, args) = parser.parse_args()
460
461As before, the last value specified for a given option destination is the one
462that counts. For clarity, try to use one method or the other of setting default
463values, not both.
464
465
466.. _optparse-generating-help:
467
468Generating help
469^^^^^^^^^^^^^^^
470
471:mod:`optparse`'s ability to generate help and usage text automatically is
472useful for creating user-friendly command-line interfaces. All you have to do
Georg Brandlb926ebb2009-09-17 17:14:04 +0000473is supply a :attr:`~Option.help` value for each option, and optionally a short
474usage message for your whole program. Here's an OptionParser populated with
Georg Brandl8ec7f652007-08-15 14:28:01 +0000475user-friendly (documented) options::
476
477 usage = "usage: %prog [options] arg1 arg2"
478 parser = OptionParser(usage=usage)
479 parser.add_option("-v", "--verbose",
480 action="store_true", dest="verbose", default=True,
481 help="make lots of noise [default]")
482 parser.add_option("-q", "--quiet",
Andrew M. Kuchling810f8072008-09-06 13:04:02 +0000483 action="store_false", dest="verbose",
Georg Brandl8ec7f652007-08-15 14:28:01 +0000484 help="be vewwy quiet (I'm hunting wabbits)")
485 parser.add_option("-f", "--filename",
Georg Brandld7226ff2009-09-16 13:06:22 +0000486 metavar="FILE", help="write output to FILE")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000487 parser.add_option("-m", "--mode",
488 default="intermediate",
489 help="interaction mode: novice, intermediate, "
490 "or expert [default: %default]")
491
Éric Araujoa8132ec2010-12-16 03:53:53 +0000492If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000493command-line, or if you just call :meth:`parser.print_help`, it prints the
Ezio Melotti5129ed32010-01-03 09:01:27 +0000494following to standard output:
495
496.. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +0000497
498 usage: <yourscript> [options] arg1 arg2
499
500 options:
501 -h, --help show this help message and exit
502 -v, --verbose make lots of noise [default]
503 -q, --quiet be vewwy quiet (I'm hunting wabbits)
504 -f FILE, --filename=FILE
505 write output to FILE
506 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
507 expert [default: intermediate]
508
509(If the help output is triggered by a help option, :mod:`optparse` exits after
510printing the help text.)
511
512There's a lot going on here to help :mod:`optparse` generate the best possible
513help message:
514
515* the script defines its own usage message::
516
517 usage = "usage: %prog [options] arg1 arg2"
518
Éric Araujoa8132ec2010-12-16 03:53:53 +0000519 :mod:`optparse` expands ``%prog`` in the usage string to the name of the
Georg Brandlb926ebb2009-09-17 17:14:04 +0000520 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
521 is then printed before the detailed option help.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000522
523 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandlb926ebb2009-09-17 17:14:04 +0000524 default: ``"usage: %prog [options]"``, which is fine if your script doesn't
525 take any positional arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000526
527* every option defines a help string, and doesn't worry about line-wrapping---
528 :mod:`optparse` takes care of wrapping lines and making the help output look
529 good.
530
531* options that take a value indicate this fact in their automatically-generated
532 help message, e.g. for the "mode" option::
533
534 -m MODE, --mode=MODE
535
536 Here, "MODE" is called the meta-variable: it stands for the argument that the
Éric Araujoa8132ec2010-12-16 03:53:53 +0000537 user is expected to supply to ``-m``/``--mode``. By default,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000538 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandlb926ebb2009-09-17 17:14:04 +0000539 that for the meta-variable. Sometimes, that's not what you want---for
Éric Araujoa8132ec2010-12-16 03:53:53 +0000540 example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
Georg Brandlb926ebb2009-09-17 17:14:04 +0000541 resulting in this automatically-generated option description::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000542
543 -f FILE, --filename=FILE
544
Georg Brandlb926ebb2009-09-17 17:14:04 +0000545 This is important for more than just saving space, though: the manually
Éric Araujoa8132ec2010-12-16 03:53:53 +0000546 written help text uses the meta-variable ``FILE`` to clue the user in that
547 there's a connection between the semi-formal syntax ``-f FILE`` and the informal
Georg Brandlb926ebb2009-09-17 17:14:04 +0000548 semantic description "write output to FILE". This is a simple but effective
549 way to make your help text a lot clearer and more useful for end users.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000550
Georg Brandl799b3722008-03-25 08:39:10 +0000551.. versionadded:: 2.4
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``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000556
Georg Brandlb926ebb2009-09-17 17:14:04 +0000557When dealing with many options, it is convenient to group these options for
558better help output. An :class:`OptionParser` can contain several option groups,
559each of which can contain several options.
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000560
Georg Brandlb926ebb2009-09-17 17:14:04 +0000561Continuing with the parser defined above, adding an :class:`OptionGroup` to a
562parser is easy::
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000563
564 group = OptionGroup(parser, "Dangerous Options",
Georg Brandl7044b112009-01-03 21:04:55 +0000565 "Caution: use these options at your own risk. "
566 "It is believed that some of them bite.")
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000567 group.add_option("-g", action="store_true", help="Group option.")
568 parser.add_option_group(group)
569
Ezio Melotti5129ed32010-01-03 09:01:27 +0000570This would result in the following help output:
571
572.. code-block:: text
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000573
574 usage: [options] arg1 arg2
575
576 options:
577 -h, --help show this help message and exit
578 -v, --verbose make lots of noise [default]
579 -q, --quiet be vewwy quiet (I'm hunting wabbits)
580 -fFILE, --file=FILE write output to FILE
581 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
Georg Brandl7044b112009-01-03 21:04:55 +0000582 [default], 'expert'
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000583
584 Dangerous Options:
Georg Brandl7044b112009-01-03 21:04:55 +0000585 Caution: use of these options is at your own risk. It is believed that
586 some of them bite.
587 -g Group option.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000588
589.. _optparse-printing-version-string:
590
591Printing a version string
592^^^^^^^^^^^^^^^^^^^^^^^^^
593
594Similar to the brief usage string, :mod:`optparse` can also print a version
595string for your program. You have to supply the string as the ``version``
596argument to OptionParser::
597
598 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
599
Éric Araujoa8132ec2010-12-16 03:53:53 +0000600``%prog`` is expanded just like it is in ``usage``. Apart from that,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000601``version`` can contain anything you like. When you supply it, :mod:`optparse`
Éric Araujoa8132ec2010-12-16 03:53:53 +0000602automatically adds a ``--version`` option to your parser. If it encounters
Georg Brandl8ec7f652007-08-15 14:28:01 +0000603this option on the command line, it expands your ``version`` string (by
Éric Araujoa8132ec2010-12-16 03:53:53 +0000604replacing ``%prog``), prints it to stdout, and exits.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000605
606For example, if your script is called ``/usr/bin/foo``::
607
608 $ /usr/bin/foo --version
609 foo 1.0
610
Ezio Melottib9c3ed42010-01-04 21:43:02 +0000611The following two methods can be used to print and get the ``version`` string:
612
613.. method:: OptionParser.print_version(file=None)
614
615 Print the version message for the current program (``self.version``) to
616 *file* (default stdout). As with :meth:`print_usage`, any occurrence
Éric Araujoa8132ec2010-12-16 03:53:53 +0000617 of ``%prog`` in ``self.version`` is replaced with the name of the current
Ezio Melottib9c3ed42010-01-04 21:43:02 +0000618 program. Does nothing if ``self.version`` is empty or undefined.
619
620.. method:: OptionParser.get_version()
621
622 Same as :meth:`print_version` but returns the version string instead of
623 printing it.
624
Georg Brandl8ec7f652007-08-15 14:28:01 +0000625
626.. _optparse-how-optparse-handles-errors:
627
628How :mod:`optparse` handles errors
629^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
630
631There are two broad classes of errors that :mod:`optparse` has to worry about:
632programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandlb926ebb2009-09-17 17:14:04 +0000633calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
634option attributes, missing option attributes, etc. These are dealt with in the
635usual way: raise an exception (either :exc:`optparse.OptionError` or
636:exc:`TypeError`) and let the program crash.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000637
638Handling user errors is much more important, since they are guaranteed to happen
639no matter how stable your code is. :mod:`optparse` can automatically detect
Éric Araujoa8132ec2010-12-16 03:53:53 +0000640some user errors, such as bad option arguments (passing ``-n 4x`` where
641``-n`` takes an integer argument), missing arguments (``-n`` at the end
642of the command line, where ``-n`` takes an argument of any type). Also,
Georg Brandlb926ebb2009-09-17 17:14:04 +0000643you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl8ec7f652007-08-15 14:28:01 +0000644condition::
645
646 (options, args) = parser.parse_args()
647 [...]
648 if options.a and options.b:
649 parser.error("options -a and -b are mutually exclusive")
650
651In either case, :mod:`optparse` handles the error the same way: it prints the
652program's usage message and an error message to standard error and exits with
653error status 2.
654
Éric Araujoa8132ec2010-12-16 03:53:53 +0000655Consider the first example above, where the user passes ``4x`` to an option
Georg Brandl8ec7f652007-08-15 14:28:01 +0000656that takes an integer::
657
658 $ /usr/bin/foo -n 4x
659 usage: foo [options]
660
661 foo: error: option -n: invalid integer value: '4x'
662
663Or, where the user fails to pass a value at all::
664
665 $ /usr/bin/foo -n
666 usage: foo [options]
667
668 foo: error: -n option requires an argument
669
670:mod:`optparse`\ -generated error messages take care always to mention the
671option involved in the error; be sure to do the same when calling
Georg Brandlb926ebb2009-09-17 17:14:04 +0000672:func:`OptionParser.error` from your application code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000673
Georg Brandl60c0be32008-06-13 13:26:54 +0000674If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Georg Brandl0c9eb432009-06-30 16:35:11 +0000675you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
676and/or :meth:`~OptionParser.error` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000677
678
679.. _optparse-putting-it-all-together:
680
681Putting it all together
682^^^^^^^^^^^^^^^^^^^^^^^
683
684Here's what :mod:`optparse`\ -based scripts usually look like::
685
686 from optparse import OptionParser
687 [...]
688 def main():
689 usage = "usage: %prog [options] arg"
690 parser = OptionParser(usage)
691 parser.add_option("-f", "--file", dest="filename",
692 help="read data from FILENAME")
693 parser.add_option("-v", "--verbose",
694 action="store_true", dest="verbose")
695 parser.add_option("-q", "--quiet",
696 action="store_false", dest="verbose")
697 [...]
698 (options, args) = parser.parse_args()
699 if len(args) != 1:
700 parser.error("incorrect number of arguments")
701 if options.verbose:
702 print "reading %s..." % options.filename
703 [...]
704
705 if __name__ == "__main__":
706 main()
707
Georg Brandl8ec7f652007-08-15 14:28:01 +0000708
709.. _optparse-reference-guide:
710
711Reference Guide
712---------------
713
714
715.. _optparse-creating-parser:
716
717Creating the parser
718^^^^^^^^^^^^^^^^^^^
719
Georg Brandlb926ebb2009-09-17 17:14:04 +0000720The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000721
Georg Brandlb926ebb2009-09-17 17:14:04 +0000722.. class:: OptionParser(...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000723
Georg Brandlb926ebb2009-09-17 17:14:04 +0000724 The OptionParser constructor has no required arguments, but a number of
725 optional keyword arguments. You should always pass them as keyword
726 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000727
728 ``usage`` (default: ``"%prog [options]"``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000729 The usage summary to print when your program is run incorrectly or with a
730 help option. When :mod:`optparse` prints the usage string, it expands
731 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
732 passed that keyword argument). To suppress a usage message, pass the
733 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000734
735 ``option_list`` (default: ``[]``)
736 A list of Option objects to populate the parser with. The options in
Georg Brandlb926ebb2009-09-17 17:14:04 +0000737 ``option_list`` are added after any options in ``standard_option_list`` (a
738 class attribute that may be set by OptionParser subclasses), but before
739 any version or help options. Deprecated; use :meth:`add_option` after
740 creating the parser instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000741
742 ``option_class`` (default: optparse.Option)
743 Class to use when adding options to the parser in :meth:`add_option`.
744
745 ``version`` (default: ``None``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000746 A version string to print when the user supplies a version option. If you
747 supply a true value for ``version``, :mod:`optparse` automatically adds a
Éric Araujoa8132ec2010-12-16 03:53:53 +0000748 version option with the single option string ``--version``. The
749 substring ``%prog`` is expanded the same as for ``usage``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000750
751 ``conflict_handler`` (default: ``"error"``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000752 Specifies what to do when options with conflicting option strings are
753 added to the parser; see section
754 :ref:`optparse-conflicts-between-options`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000755
756 ``description`` (default: ``None``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000757 A paragraph of text giving a brief overview of your program.
758 :mod:`optparse` reformats this paragraph to fit the current terminal width
759 and prints it when the user requests help (after ``usage``, but before the
760 list of options).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000761
Georg Brandlb926ebb2009-09-17 17:14:04 +0000762 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
763 An instance of optparse.HelpFormatter that will be used for printing help
764 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000765 IndentedHelpFormatter and TitledHelpFormatter.
766
767 ``add_help_option`` (default: ``True``)
Éric Araujoa8132ec2010-12-16 03:53:53 +0000768 If true, :mod:`optparse` will add a help option (with option strings ``-h``
769 and ``--help``) to the parser.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000770
771 ``prog``
Éric Araujoa8132ec2010-12-16 03:53:53 +0000772 The string to use when expanding ``%prog`` in ``usage`` and ``version``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000773 instead of ``os.path.basename(sys.argv[0])``.
774
Senthil Kumaran67b4e182010-03-23 08:46:31 +0000775 ``epilog`` (default: ``None``)
776 A paragraph of help text to print after the option help.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000777
778.. _optparse-populating-parser:
779
780Populating the parser
781^^^^^^^^^^^^^^^^^^^^^
782
783There are several ways to populate the parser with options. The preferred way
Georg Brandlb926ebb2009-09-17 17:14:04 +0000784is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl8ec7f652007-08-15 14:28:01 +0000785:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
786
787* pass it an Option instance (as returned by :func:`make_option`)
788
789* pass it any combination of positional and keyword arguments that are
Georg Brandlb926ebb2009-09-17 17:14:04 +0000790 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
791 will create the Option instance for you
Georg Brandl8ec7f652007-08-15 14:28:01 +0000792
793The other alternative is to pass a list of pre-constructed Option instances to
794the OptionParser constructor, as in::
795
796 option_list = [
797 make_option("-f", "--filename",
798 action="store", type="string", dest="filename"),
799 make_option("-q", "--quiet",
800 action="store_false", dest="verbose"),
801 ]
802 parser = OptionParser(option_list=option_list)
803
804(:func:`make_option` is a factory function for creating Option instances;
805currently it is an alias for the Option constructor. A future version of
806:mod:`optparse` may split Option into several classes, and :func:`make_option`
807will pick the right class to instantiate. Do not instantiate Option directly.)
808
809
810.. _optparse-defining-options:
811
812Defining options
813^^^^^^^^^^^^^^^^
814
815Each Option instance represents a set of synonymous command-line option strings,
Éric Araujoa8132ec2010-12-16 03:53:53 +0000816e.g. ``-f`` and ``--file``. You can specify any number of short or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000817long option strings, but you must specify at least one overall option string.
818
Georg Brandlb926ebb2009-09-17 17:14:04 +0000819The canonical way to create an :class:`Option` instance is with the
820:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000821
Georg Brandlb926ebb2009-09-17 17:14:04 +0000822.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000823
Georg Brandlb926ebb2009-09-17 17:14:04 +0000824 To define an option with only a short option string::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000825
Georg Brandlb926ebb2009-09-17 17:14:04 +0000826 parser.add_option("-f", attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000827
Georg Brandlb926ebb2009-09-17 17:14:04 +0000828 And to define an option with only a long option string::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000829
Georg Brandlb926ebb2009-09-17 17:14:04 +0000830 parser.add_option("--foo", attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000831
Georg Brandlb926ebb2009-09-17 17:14:04 +0000832 The keyword arguments define attributes of the new Option object. The most
833 important option attribute is :attr:`~Option.action`, and it largely
834 determines which other attributes are relevant or required. If you pass
835 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
836 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000837
Georg Brandlb926ebb2009-09-17 17:14:04 +0000838 An option's *action* determines what :mod:`optparse` does when it encounters
839 this option on the command-line. The standard option actions hard-coded into
840 :mod:`optparse` are:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000841
Georg Brandlb926ebb2009-09-17 17:14:04 +0000842 ``"store"``
843 store this option's argument (default)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000844
Georg Brandlb926ebb2009-09-17 17:14:04 +0000845 ``"store_const"``
846 store a constant value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000847
Georg Brandlb926ebb2009-09-17 17:14:04 +0000848 ``"store_true"``
849 store a true value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000850
Georg Brandlb926ebb2009-09-17 17:14:04 +0000851 ``"store_false"``
852 store a false value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000853
Georg Brandlb926ebb2009-09-17 17:14:04 +0000854 ``"append"``
855 append this option's argument to a list
Georg Brandl8ec7f652007-08-15 14:28:01 +0000856
Georg Brandlb926ebb2009-09-17 17:14:04 +0000857 ``"append_const"``
858 append a constant value to a list
Georg Brandl8ec7f652007-08-15 14:28:01 +0000859
Georg Brandlb926ebb2009-09-17 17:14:04 +0000860 ``"count"``
861 increment a counter by one
Georg Brandl8ec7f652007-08-15 14:28:01 +0000862
Georg Brandlb926ebb2009-09-17 17:14:04 +0000863 ``"callback"``
864 call a specified function
Georg Brandl8ec7f652007-08-15 14:28:01 +0000865
Georg Brandlb926ebb2009-09-17 17:14:04 +0000866 ``"help"``
867 print a usage message including all options and the documentation for them
Georg Brandl8ec7f652007-08-15 14:28:01 +0000868
Georg Brandlb926ebb2009-09-17 17:14:04 +0000869 (If you don't supply an action, the default is ``"store"``. For this action,
870 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
871 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000872
873As you can see, most actions involve storing or updating a value somewhere.
874:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandlb926ebb2009-09-17 17:14:04 +0000875``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl8ec7f652007-08-15 14:28:01 +0000876arguments (and various other values) are stored as attributes of this object,
Georg Brandlb926ebb2009-09-17 17:14:04 +0000877according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000878
Georg Brandlb926ebb2009-09-17 17:14:04 +0000879For example, when you call ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000880
881 parser.parse_args()
882
883one of the first things :mod:`optparse` does is create the ``options`` object::
884
885 options = Values()
886
Georg Brandlb926ebb2009-09-17 17:14:04 +0000887If one of the options in this parser is defined with ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000888
889 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
890
891and the command-line being parsed includes any of the following::
892
893 -ffoo
894 -f foo
895 --file=foo
896 --file foo
897
Georg Brandlb926ebb2009-09-17 17:14:04 +0000898then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000899
900 options.filename = "foo"
901
Georg Brandlb926ebb2009-09-17 17:14:04 +0000902The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
903as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
904one that makes sense for *all* options.
905
906
907.. _optparse-option-attributes:
908
909Option attributes
910^^^^^^^^^^^^^^^^^
911
912The following option attributes may be passed as keyword arguments to
913:meth:`OptionParser.add_option`. If you pass an option attribute that is not
914relevant to a particular option, or fail to pass a required option attribute,
915:mod:`optparse` raises :exc:`OptionError`.
916
917.. attribute:: Option.action
918
919 (default: ``"store"``)
920
921 Determines :mod:`optparse`'s behaviour when this option is seen on the
922 command line; the available options are documented :ref:`here
923 <optparse-standard-option-actions>`.
924
925.. attribute:: Option.type
926
927 (default: ``"string"``)
928
929 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
930 the available option types are documented :ref:`here
931 <optparse-standard-option-types>`.
932
933.. attribute:: Option.dest
934
935 (default: derived from option strings)
936
937 If the option's action implies writing or modifying a value somewhere, this
938 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
939 attribute of the ``options`` object that :mod:`optparse` builds as it parses
940 the command line.
941
942.. attribute:: Option.default
943
944 The value to use for this option's destination if the option is not seen on
945 the command line. See also :meth:`OptionParser.set_defaults`.
946
947.. attribute:: Option.nargs
948
949 (default: 1)
950
951 How many arguments of type :attr:`~Option.type` should be consumed when this
952 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
953 :attr:`~Option.dest`.
954
955.. attribute:: Option.const
956
957 For actions that store a constant value, the constant value to store.
958
959.. attribute:: Option.choices
960
961 For options of type ``"choice"``, the list of strings the user may choose
962 from.
963
964.. attribute:: Option.callback
965
966 For options with action ``"callback"``, the callable to call when this option
967 is seen. See section :ref:`optparse-option-callbacks` for detail on the
968 arguments passed to the callable.
969
970.. attribute:: Option.callback_args
971 Option.callback_kwargs
972
973 Additional positional and keyword arguments to pass to ``callback`` after the
974 four standard callback arguments.
975
976.. attribute:: Option.help
977
978 Help text to print for this option when listing all available options after
Éric Araujoa8132ec2010-12-16 03:53:53 +0000979 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
Georg Brandlb926ebb2009-09-17 17:14:04 +0000980 no help text is supplied, the option will be listed without help text. To
981 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
982
983.. attribute:: Option.metavar
984
985 (default: derived from option strings)
986
987 Stand-in for the option argument(s) to use when printing help text. See
988 section :ref:`optparse-tutorial` for an example.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000989
990
991.. _optparse-standard-option-actions:
992
993Standard option actions
994^^^^^^^^^^^^^^^^^^^^^^^
995
996The various option actions all have slightly different requirements and effects.
997Most actions have several relevant option attributes which you may specify to
998guide :mod:`optparse`'s behaviour; a few have required attributes, which you
999must specify for any option using that action.
1000
Georg Brandlb926ebb2009-09-17 17:14:04 +00001001* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1002 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001003
1004 The option must be followed by an argument, which is converted to a value
Georg Brandlb926ebb2009-09-17 17:14:04 +00001005 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1006 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1007 command line; all will be converted according to :attr:`~Option.type` and
1008 stored to :attr:`~Option.dest` as a tuple. See the
1009 :ref:`optparse-standard-option-types` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001010
Georg Brandlb926ebb2009-09-17 17:14:04 +00001011 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1012 defaults to ``"choice"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001013
Georg Brandlb926ebb2009-09-17 17:14:04 +00001014 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001015
Georg Brandlb926ebb2009-09-17 17:14:04 +00001016 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
Éric Araujoa8132ec2010-12-16 03:53:53 +00001017 from the first long option string (e.g., ``--foo-bar`` implies
Georg Brandlb926ebb2009-09-17 17:14:04 +00001018 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
Éric Araujoa8132ec2010-12-16 03:53:53 +00001019 destination from the first short option string (e.g., ``-f`` implies ``f``).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001020
1021 Example::
1022
1023 parser.add_option("-f")
1024 parser.add_option("-p", type="float", nargs=3, dest="point")
1025
Georg Brandlb926ebb2009-09-17 17:14:04 +00001026 As it parses the command line ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001027
1028 -f foo.txt -p 1 -3.5 4 -fbar.txt
1029
Georg Brandlb926ebb2009-09-17 17:14:04 +00001030 :mod:`optparse` will set ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001031
1032 options.f = "foo.txt"
1033 options.point = (1.0, -3.5, 4.0)
1034 options.f = "bar.txt"
1035
Georg Brandlb926ebb2009-09-17 17:14:04 +00001036* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1037 :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001038
Georg Brandlb926ebb2009-09-17 17:14:04 +00001039 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040
1041 Example::
1042
1043 parser.add_option("-q", "--quiet",
1044 action="store_const", const=0, dest="verbose")
1045 parser.add_option("-v", "--verbose",
1046 action="store_const", const=1, dest="verbose")
1047 parser.add_option("--noisy",
1048 action="store_const", const=2, dest="verbose")
1049
Éric Araujoa8132ec2010-12-16 03:53:53 +00001050 If ``--noisy`` is seen, :mod:`optparse` will set ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001051
1052 options.verbose = 2
1053
Georg Brandlb926ebb2009-09-17 17:14:04 +00001054* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001055
Georg Brandlb926ebb2009-09-17 17:14:04 +00001056 A special case of ``"store_const"`` that stores a true value to
1057 :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001058
Georg Brandlb926ebb2009-09-17 17:14:04 +00001059* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001060
Georg Brandlb926ebb2009-09-17 17:14:04 +00001061 Like ``"store_true"``, but stores a false value.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001062
1063 Example::
1064
1065 parser.add_option("--clobber", action="store_true", dest="clobber")
1066 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1067
Georg Brandlb926ebb2009-09-17 17:14:04 +00001068* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1069 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001070
1071 The option must be followed by an argument, which is appended to the list in
Georg Brandlb926ebb2009-09-17 17:14:04 +00001072 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1073 supplied, an empty list is automatically created when :mod:`optparse` first
1074 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1075 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1076 is appended to :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001077
Georg Brandlb926ebb2009-09-17 17:14:04 +00001078 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1079 for the ``"store"`` action.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001080
1081 Example::
1082
1083 parser.add_option("-t", "--tracks", action="append", type="int")
1084
Éric Araujoa8132ec2010-12-16 03:53:53 +00001085 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
Georg Brandl8ec7f652007-08-15 14:28:01 +00001086 of::
1087
1088 options.tracks = []
1089 options.tracks.append(int("3"))
1090
Éric Araujoa8132ec2010-12-16 03:53:53 +00001091 If, a little later on, ``--tracks=4`` is seen, it does::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001092
1093 options.tracks.append(int("4"))
1094
Georg Brandlb926ebb2009-09-17 17:14:04 +00001095* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1096 :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001097
Georg Brandlb926ebb2009-09-17 17:14:04 +00001098 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1099 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1100 ``None``, and an empty list is automatically created the first time the option
1101 is encountered.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001102
Georg Brandlb926ebb2009-09-17 17:14:04 +00001103* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001104
Georg Brandlb926ebb2009-09-17 17:14:04 +00001105 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1106 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1107 first time.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001108
1109 Example::
1110
1111 parser.add_option("-v", action="count", dest="verbosity")
1112
Éric Araujoa8132ec2010-12-16 03:53:53 +00001113 The first time ``-v`` is seen on the command line, :mod:`optparse` does the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001114 equivalent of::
1115
1116 options.verbosity = 0
1117 options.verbosity += 1
1118
Éric Araujoa8132ec2010-12-16 03:53:53 +00001119 Every subsequent occurrence of ``-v`` results in ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001120
1121 options.verbosity += 1
1122
Georg Brandlb926ebb2009-09-17 17:14:04 +00001123* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1124 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1125 :attr:`~Option.callback_kwargs`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001126
Georg Brandlb926ebb2009-09-17 17:14:04 +00001127 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001128
1129 func(option, opt_str, value, parser, *args, **kwargs)
1130
1131 See section :ref:`optparse-option-callbacks` for more detail.
1132
Georg Brandlb926ebb2009-09-17 17:14:04 +00001133* ``"help"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001134
Georg Brandlb926ebb2009-09-17 17:14:04 +00001135 Prints a complete help message for all the options in the current option
1136 parser. The help message is constructed from the ``usage`` string passed to
1137 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1138 option.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001139
Georg Brandlb926ebb2009-09-17 17:14:04 +00001140 If no :attr:`~Option.help` string is supplied for an option, it will still be
1141 listed in the help message. To omit an option entirely, use the special value
1142 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001143
Georg Brandlb926ebb2009-09-17 17:14:04 +00001144 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1145 OptionParsers, so you do not normally need to create one.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001146
1147 Example::
1148
1149 from optparse import OptionParser, SUPPRESS_HELP
1150
Georg Brandl718b2212009-09-16 13:11:06 +00001151 # usually, a help option is added automatically, but that can
1152 # be suppressed using the add_help_option argument
1153 parser = OptionParser(add_help_option=False)
1154
Georg Brandld7226ff2009-09-16 13:06:22 +00001155 parser.add_option("-h", "--help", action="help")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001156 parser.add_option("-v", action="store_true", dest="verbose",
1157 help="Be moderately verbose")
1158 parser.add_option("--file", dest="filename",
Georg Brandld7226ff2009-09-16 13:06:22 +00001159 help="Input file to read data from")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001160 parser.add_option("--secret", help=SUPPRESS_HELP)
1161
Éric Araujoa8132ec2010-12-16 03:53:53 +00001162 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
Georg Brandlb926ebb2009-09-17 17:14:04 +00001163 it will print something like the following help message to stdout (assuming
Ezio Melotti5129ed32010-01-03 09:01:27 +00001164 ``sys.argv[0]`` is ``"foo.py"``):
1165
1166 .. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +00001167
1168 usage: foo.py [options]
1169
1170 options:
1171 -h, --help Show this help message and exit
1172 -v Be moderately verbose
1173 --file=FILENAME Input file to read data from
1174
1175 After printing the help message, :mod:`optparse` terminates your process with
1176 ``sys.exit(0)``.
1177
Georg Brandlb926ebb2009-09-17 17:14:04 +00001178* ``"version"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001179
Georg Brandlb926ebb2009-09-17 17:14:04 +00001180 Prints the version number supplied to the OptionParser to stdout and exits.
1181 The version number is actually formatted and printed by the
1182 ``print_version()`` method of OptionParser. Generally only relevant if the
1183 ``version`` argument is supplied to the OptionParser constructor. As with
1184 :attr:`~Option.help` options, you will rarely create ``version`` options,
1185 since :mod:`optparse` automatically adds them when needed.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001186
1187
1188.. _optparse-standard-option-types:
1189
1190Standard option types
1191^^^^^^^^^^^^^^^^^^^^^
1192
Georg Brandlb926ebb2009-09-17 17:14:04 +00001193:mod:`optparse` has six built-in option types: ``"string"``, ``"int"``,
1194``"long"``, ``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1195option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001196
1197Arguments to string options are not checked or converted in any way: the text on
1198the command line is stored in the destination (or passed to the callback) as-is.
1199
Georg Brandlb926ebb2009-09-17 17:14:04 +00001200Integer arguments (type ``"int"`` or ``"long"``) are parsed as follows:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001201
1202* if the number starts with ``0x``, it is parsed as a hexadecimal number
1203
1204* if the number starts with ``0``, it is parsed as an octal number
1205
Georg Brandl97ca5832007-09-24 17:55:47 +00001206* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl8ec7f652007-08-15 14:28:01 +00001207
1208* otherwise, the number is parsed as a decimal number
1209
1210
Georg Brandlb926ebb2009-09-17 17:14:04 +00001211The conversion is done by calling either :func:`int` or :func:`long` with the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001212appropriate base (2, 8, 10, or 16). If this fails, so will :mod:`optparse`,
1213although with a more useful error message.
1214
Georg Brandlb926ebb2009-09-17 17:14:04 +00001215``"float"`` and ``"complex"`` option arguments are converted directly with
1216:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001217
Georg Brandlb926ebb2009-09-17 17:14:04 +00001218``"choice"`` options are a subtype of ``"string"`` options. The
Georg Brandl35e7a8f2010-10-06 10:41:31 +00001219:attr:`~Option.choices` option attribute (a sequence of strings) defines the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001220set of allowed option arguments. :func:`optparse.check_choice` compares
1221user-supplied option arguments against this master list and raises
1222:exc:`OptionValueError` if an invalid string is given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001223
1224
1225.. _optparse-parsing-arguments:
1226
1227Parsing arguments
1228^^^^^^^^^^^^^^^^^
1229
1230The whole point of creating and populating an OptionParser is to call its
1231:meth:`parse_args` method::
1232
1233 (options, args) = parser.parse_args(args=None, values=None)
1234
1235where the input parameters are
1236
1237``args``
1238 the list of arguments to process (default: ``sys.argv[1:]``)
1239
1240``values``
Georg Brandl0347c712010-08-01 19:02:09 +00001241 a :class:`optparse.Values` object to store option arguments in (default: a
1242 new instance of :class:`Values`) -- if you give an existing object, the
1243 option defaults will not be initialized on it
Georg Brandl8ec7f652007-08-15 14:28:01 +00001244
1245and the return values are
1246
1247``options``
Georg Brandl8514b852009-09-01 08:06:03 +00001248 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl8ec7f652007-08-15 14:28:01 +00001249 instance created by :mod:`optparse`
1250
1251``args``
1252 the leftover positional arguments after all options have been processed
1253
1254The most common usage is to supply neither keyword argument. If you supply
Georg Brandlb926ebb2009-09-17 17:14:04 +00001255``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl8ec7f652007-08-15 14:28:01 +00001256for every option argument stored to an option destination) and returned by
1257:meth:`parse_args`.
1258
1259If :meth:`parse_args` encounters any errors in the argument list, it calls the
1260OptionParser's :meth:`error` method with an appropriate end-user error message.
1261This ultimately terminates your process with an exit status of 2 (the
1262traditional Unix exit status for command-line errors).
1263
1264
1265.. _optparse-querying-manipulating-option-parser:
1266
1267Querying and manipulating your option parser
1268^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1269
Georg Brandlb926ebb2009-09-17 17:14:04 +00001270The default behavior of the option parser can be customized slightly, and you
1271can also poke around your option parser and see what's there. OptionParser
1272provides several methods to help you out:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001273
Georg Brandlb926ebb2009-09-17 17:14:04 +00001274.. method:: OptionParser.disable_interspersed_args()
Georg Brandl7842a412009-09-17 16:26:06 +00001275
Éric Araujoa8132ec2010-12-16 03:53:53 +00001276 Set parsing to stop on the first non-option. For example, if ``-a`` and
1277 ``-b`` are both simple options that take no arguments, :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00001278 normally accepts this syntax::
Georg Brandl7842a412009-09-17 16:26:06 +00001279
Georg Brandlb926ebb2009-09-17 17:14:04 +00001280 prog -a arg1 -b arg2
Georg Brandl7842a412009-09-17 16:26:06 +00001281
Georg Brandlb926ebb2009-09-17 17:14:04 +00001282 and treats it as equivalent to ::
Georg Brandl7842a412009-09-17 16:26:06 +00001283
Georg Brandlb926ebb2009-09-17 17:14:04 +00001284 prog -a -b arg1 arg2
Georg Brandl7842a412009-09-17 16:26:06 +00001285
Georg Brandlb926ebb2009-09-17 17:14:04 +00001286 To disable this feature, call :meth:`disable_interspersed_args`. This
1287 restores traditional Unix syntax, where option parsing stops with the first
1288 non-option argument.
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001289
Georg Brandlb926ebb2009-09-17 17:14:04 +00001290 Use this if you have a command processor which runs another command which has
1291 options of its own and you want to make sure these options don't get
1292 confused. For example, each command might have a different set of options.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001293
Georg Brandlb926ebb2009-09-17 17:14:04 +00001294.. method:: OptionParser.enable_interspersed_args()
1295
1296 Set parsing to not stop on the first non-option, allowing interspersing
1297 switches with command arguments. This is the default behavior.
1298
1299.. method:: OptionParser.get_option(opt_str)
1300
1301 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl8ec7f652007-08-15 14:28:01 +00001302 no options have that option string.
1303
Georg Brandlb926ebb2009-09-17 17:14:04 +00001304.. method:: OptionParser.has_option(opt_str)
1305
1306 Return true if the OptionParser has an option with option string *opt_str*
Éric Araujoa8132ec2010-12-16 03:53:53 +00001307 (e.g., ``-q`` or ``--verbose``).
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001308
Georg Brandlb926ebb2009-09-17 17:14:04 +00001309.. method:: OptionParser.remove_option(opt_str)
1310
1311 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1312 option is removed. If that option provided any other option strings, all of
1313 those option strings become invalid. If *opt_str* does not occur in any
1314 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001315
1316
1317.. _optparse-conflicts-between-options:
1318
1319Conflicts between options
1320^^^^^^^^^^^^^^^^^^^^^^^^^
1321
1322If you're not careful, it's easy to define options with conflicting option
1323strings::
1324
1325 parser.add_option("-n", "--dry-run", ...)
1326 [...]
1327 parser.add_option("-n", "--noisy", ...)
1328
1329(This is particularly true if you've defined your own OptionParser subclass with
1330some standard options.)
1331
1332Every time you add an option, :mod:`optparse` checks for conflicts with existing
1333options. If it finds any, it invokes the current conflict-handling mechanism.
1334You can set the conflict-handling mechanism either in the constructor::
1335
1336 parser = OptionParser(..., conflict_handler=handler)
1337
1338or with a separate call::
1339
1340 parser.set_conflict_handler(handler)
1341
1342The available conflict handlers are:
1343
Georg Brandlb926ebb2009-09-17 17:14:04 +00001344 ``"error"`` (default)
1345 assume option conflicts are a programming error and raise
1346 :exc:`OptionConflictError`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001347
Georg Brandlb926ebb2009-09-17 17:14:04 +00001348 ``"resolve"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001349 resolve option conflicts intelligently (see below)
1350
1351
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001352As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl8ec7f652007-08-15 14:28:01 +00001353intelligently and add conflicting options to it::
1354
1355 parser = OptionParser(conflict_handler="resolve")
1356 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1357 parser.add_option("-n", "--noisy", ..., help="be noisy")
1358
1359At this point, :mod:`optparse` detects that a previously-added option is already
Éric Araujoa8132ec2010-12-16 03:53:53 +00001360using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1361it resolves the situation by removing ``-n`` from the earlier option's list of
1362option strings. Now ``--dry-run`` is the only way for the user to activate
Georg Brandl8ec7f652007-08-15 14:28:01 +00001363that option. If the user asks for help, the help message will reflect that::
1364
1365 options:
1366 --dry-run do no harm
1367 [...]
1368 -n, --noisy be noisy
1369
1370It's possible to whittle away the option strings for a previously-added option
1371until there are none left, and the user has no way of invoking that option from
1372the command-line. In that case, :mod:`optparse` removes that option completely,
1373so it doesn't show up in help text or anywhere else. Carrying on with our
1374existing OptionParser::
1375
1376 parser.add_option("--dry-run", ..., help="new dry-run option")
1377
Éric Araujoa8132ec2010-12-16 03:53:53 +00001378At this point, the original ``-n``/``--dry-run`` option is no longer
Georg Brandl8ec7f652007-08-15 14:28:01 +00001379accessible, so :mod:`optparse` removes it, leaving this help text::
1380
1381 options:
1382 [...]
1383 -n, --noisy be noisy
1384 --dry-run new dry-run option
1385
1386
1387.. _optparse-cleanup:
1388
1389Cleanup
1390^^^^^^^
1391
1392OptionParser instances have several cyclic references. This should not be a
1393problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandlb926ebb2009-09-17 17:14:04 +00001394references explicitly by calling :meth:`~OptionParser.destroy` on your
1395OptionParser once you are done with it. This is particularly useful in
1396long-running applications where large object graphs are reachable from your
1397OptionParser.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001398
1399
1400.. _optparse-other-methods:
1401
1402Other methods
1403^^^^^^^^^^^^^
1404
1405OptionParser supports several other public methods:
1406
Georg Brandlb926ebb2009-09-17 17:14:04 +00001407.. method:: OptionParser.set_usage(usage)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001408
Georg Brandlb926ebb2009-09-17 17:14:04 +00001409 Set the usage string according to the rules described above for the ``usage``
1410 constructor keyword argument. Passing ``None`` sets the default usage
1411 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001412
Ezio Melottib9c3ed42010-01-04 21:43:02 +00001413.. method:: OptionParser.print_usage(file=None)
1414
1415 Print the usage message for the current program (``self.usage``) to *file*
Éric Araujoa8132ec2010-12-16 03:53:53 +00001416 (default stdout). Any occurrence of the string ``%prog`` in ``self.usage``
Ezio Melottib9c3ed42010-01-04 21:43:02 +00001417 is replaced with the name of the current program. Does nothing if
1418 ``self.usage`` is empty or not defined.
1419
1420.. method:: OptionParser.get_usage()
1421
1422 Same as :meth:`print_usage` but returns the usage string instead of
1423 printing it.
1424
Georg Brandlb926ebb2009-09-17 17:14:04 +00001425.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001426
Georg Brandlb926ebb2009-09-17 17:14:04 +00001427 Set default values for several option destinations at once. Using
1428 :meth:`set_defaults` is the preferred way to set default values for options,
1429 since multiple options can share the same destination. For example, if
1430 several "mode" options all set the same destination, any one of them can set
1431 the default, and the last one wins::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001432
Georg Brandlb926ebb2009-09-17 17:14:04 +00001433 parser.add_option("--advanced", action="store_const",
1434 dest="mode", const="advanced",
1435 default="novice") # overridden below
1436 parser.add_option("--novice", action="store_const",
1437 dest="mode", const="novice",
1438 default="advanced") # overrides above setting
Georg Brandl8ec7f652007-08-15 14:28:01 +00001439
Georg Brandlb926ebb2009-09-17 17:14:04 +00001440 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001441
Georg Brandlb926ebb2009-09-17 17:14:04 +00001442 parser.set_defaults(mode="advanced")
1443 parser.add_option("--advanced", action="store_const",
1444 dest="mode", const="advanced")
1445 parser.add_option("--novice", action="store_const",
1446 dest="mode", const="novice")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001447
Georg Brandl8ec7f652007-08-15 14:28:01 +00001448
1449.. _optparse-option-callbacks:
1450
1451Option Callbacks
1452----------------
1453
1454When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1455needs, you have two choices: extend :mod:`optparse` or define a callback option.
1456Extending :mod:`optparse` is more general, but overkill for a lot of simple
1457cases. Quite often a simple callback is all you need.
1458
1459There are two steps to defining a callback option:
1460
Georg Brandlb926ebb2009-09-17 17:14:04 +00001461* define the option itself using the ``"callback"`` action
Georg Brandl8ec7f652007-08-15 14:28:01 +00001462
1463* write the callback; this is a function (or method) that takes at least four
1464 arguments, as described below
1465
1466
1467.. _optparse-defining-callback-option:
1468
1469Defining a callback option
1470^^^^^^^^^^^^^^^^^^^^^^^^^^
1471
1472As always, the easiest way to define a callback option is by using the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001473:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1474only option attribute you must specify is ``callback``, the function to call::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001475
1476 parser.add_option("-c", action="callback", callback=my_callback)
1477
1478``callback`` is a function (or other callable object), so you must have already
1479defined ``my_callback()`` when you create this callback option. In this simple
Éric Araujoa8132ec2010-12-16 03:53:53 +00001480case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001481which usually means that the option takes no arguments---the mere presence of
Éric Araujoa8132ec2010-12-16 03:53:53 +00001482``-c`` on the command-line is all it needs to know. In some
Georg Brandl8ec7f652007-08-15 14:28:01 +00001483circumstances, though, you might want your callback to consume an arbitrary
1484number of command-line arguments. This is where writing callbacks gets tricky;
1485it's covered later in this section.
1486
1487:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandlb926ebb2009-09-17 17:14:04 +00001488will only pass additional arguments if you specify them via
1489:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1490minimal callback function signature is::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001491
1492 def my_callback(option, opt, value, parser):
1493
1494The four arguments to a callback are described below.
1495
1496There are several other option attributes that you can supply when you define a
1497callback option:
1498
Georg Brandlb926ebb2009-09-17 17:14:04 +00001499:attr:`~Option.type`
1500 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1501 instructs :mod:`optparse` to consume one argument and convert it to
1502 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1503 though, :mod:`optparse` passes it to your callback function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001504
Georg Brandlb926ebb2009-09-17 17:14:04 +00001505:attr:`~Option.nargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001506 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandlb926ebb2009-09-17 17:14:04 +00001507 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1508 :attr:`~Option.type`. It then passes a tuple of converted values to your
1509 callback.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001510
Georg Brandlb926ebb2009-09-17 17:14:04 +00001511:attr:`~Option.callback_args`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001512 a tuple of extra positional arguments to pass to the callback
1513
Georg Brandlb926ebb2009-09-17 17:14:04 +00001514:attr:`~Option.callback_kwargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001515 a dictionary of extra keyword arguments to pass to the callback
1516
1517
1518.. _optparse-how-callbacks-called:
1519
1520How callbacks are called
1521^^^^^^^^^^^^^^^^^^^^^^^^
1522
1523All callbacks are called as follows::
1524
1525 func(option, opt_str, value, parser, *args, **kwargs)
1526
1527where
1528
1529``option``
1530 is the Option instance that's calling the callback
1531
1532``opt_str``
1533 is the option string seen on the command-line that's triggering the callback.
Georg Brandlb926ebb2009-09-17 17:14:04 +00001534 (If an abbreviated long option was used, ``opt_str`` will be the full,
Éric Araujoa8132ec2010-12-16 03:53:53 +00001535 canonical option string---e.g. if the user puts ``--foo`` on the
1536 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
Georg Brandlb926ebb2009-09-17 17:14:04 +00001537 ``"--foobar"``.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001538
1539``value``
1540 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandlb926ebb2009-09-17 17:14:04 +00001541 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1542 the type implied by the option's type. If :attr:`~Option.type` for this option is
1543 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001544 > 1, ``value`` will be a tuple of values of the appropriate type.
1545
1546``parser``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001547 is the OptionParser instance driving the whole thing, mainly useful because
1548 you can access some other interesting data through its instance attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001549
1550 ``parser.largs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001551 the current list of leftover arguments, ie. arguments that have been
1552 consumed but are neither options nor option arguments. Feel free to modify
1553 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1554 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001555
1556 ``parser.rargs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001557 the current list of remaining arguments, ie. with ``opt_str`` and
1558 ``value`` (if applicable) removed, and only the arguments following them
1559 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1560 arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001561
1562 ``parser.values``
1563 the object where option values are by default stored (an instance of
Georg Brandlb926ebb2009-09-17 17:14:04 +00001564 optparse.OptionValues). This lets callbacks use the same mechanism as the
1565 rest of :mod:`optparse` for storing option values; you don't need to mess
1566 around with globals or closures. You can also access or modify the
1567 value(s) of any options already encountered on the command-line.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001568
1569``args``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001570 is a tuple of arbitrary positional arguments supplied via the
1571 :attr:`~Option.callback_args` option attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001572
1573``kwargs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001574 is a dictionary of arbitrary keyword arguments supplied via
1575 :attr:`~Option.callback_kwargs`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001576
1577
1578.. _optparse-raising-errors-in-callback:
1579
1580Raising errors in a callback
1581^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1582
Georg Brandlb926ebb2009-09-17 17:14:04 +00001583The callback function should raise :exc:`OptionValueError` if there are any
1584problems with the option or its argument(s). :mod:`optparse` catches this and
1585terminates the program, printing the error message you supply to stderr. Your
1586message should be clear, concise, accurate, and mention the option at fault.
1587Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001588
1589
1590.. _optparse-callback-example-1:
1591
1592Callback example 1: trivial callback
1593^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1594
1595Here's an example of a callback option that takes no arguments, and simply
1596records that the option was seen::
1597
1598 def record_foo_seen(option, opt_str, value, parser):
Georg Brandl253a29f2009-02-05 11:33:21 +00001599 parser.values.saw_foo = True
Georg Brandl8ec7f652007-08-15 14:28:01 +00001600
1601 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1602
Georg Brandlb926ebb2009-09-17 17:14:04 +00001603Of course, you could do that with the ``"store_true"`` action.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001604
1605
1606.. _optparse-callback-example-2:
1607
1608Callback example 2: check option order
1609^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1610
Éric Araujoa8132ec2010-12-16 03:53:53 +00001611Here's a slightly more interesting example: record the fact that ``-a`` is
1612seen, but blow up if it comes after ``-b`` in the command-line. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001613
1614 def check_order(option, opt_str, value, parser):
1615 if parser.values.b:
1616 raise OptionValueError("can't use -a after -b")
1617 parser.values.a = 1
1618 [...]
1619 parser.add_option("-a", action="callback", callback=check_order)
1620 parser.add_option("-b", action="store_true", dest="b")
1621
1622
1623.. _optparse-callback-example-3:
1624
1625Callback example 3: check option order (generalized)
1626^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1627
1628If you want to re-use this callback for several similar options (set a flag, but
Éric Araujoa8132ec2010-12-16 03:53:53 +00001629blow up if ``-b`` has already been seen), it needs a bit of work: the error
Georg Brandl8ec7f652007-08-15 14:28:01 +00001630message and the flag that it sets must be generalized. ::
1631
1632 def check_order(option, opt_str, value, parser):
1633 if parser.values.b:
1634 raise OptionValueError("can't use %s after -b" % opt_str)
1635 setattr(parser.values, option.dest, 1)
1636 [...]
1637 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1638 parser.add_option("-b", action="store_true", dest="b")
1639 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1640
1641
1642.. _optparse-callback-example-4:
1643
1644Callback example 4: check arbitrary condition
1645^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1646
1647Of course, you could put any condition in there---you're not limited to checking
1648the values of already-defined options. For example, if you have options that
1649should not be called when the moon is full, all you have to do is this::
1650
1651 def check_moon(option, opt_str, value, parser):
1652 if is_moon_full():
1653 raise OptionValueError("%s option invalid when moon is full"
1654 % opt_str)
1655 setattr(parser.values, option.dest, 1)
1656 [...]
1657 parser.add_option("--foo",
1658 action="callback", callback=check_moon, dest="foo")
1659
1660(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1661
1662
1663.. _optparse-callback-example-5:
1664
1665Callback example 5: fixed arguments
1666^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1667
1668Things get slightly more interesting when you define callback options that take
1669a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandlb926ebb2009-09-17 17:14:04 +00001670is similar to defining a ``"store"`` or ``"append"`` option: if you define
1671:attr:`~Option.type`, then the option takes one argument that must be
1672convertible to that type; if you further define :attr:`~Option.nargs`, then the
1673option takes :attr:`~Option.nargs` arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001674
Georg Brandlb926ebb2009-09-17 17:14:04 +00001675Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001676
1677 def store_value(option, opt_str, value, parser):
1678 setattr(parser.values, option.dest, value)
1679 [...]
1680 parser.add_option("--foo",
1681 action="callback", callback=store_value,
1682 type="int", nargs=3, dest="foo")
1683
1684Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1685them to integers for you; all you have to do is store them. (Or whatever;
1686obviously you don't need a callback for this example.)
1687
1688
1689.. _optparse-callback-example-6:
1690
1691Callback example 6: variable arguments
1692^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1693
1694Things get hairy when you want an option to take a variable number of arguments.
1695For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1696built-in capabilities for it. And you have to deal with certain intricacies of
1697conventional Unix command-line parsing that :mod:`optparse` normally handles for
1698you. In particular, callbacks should implement the conventional rules for bare
Éric Araujoa8132ec2010-12-16 03:53:53 +00001699``--`` and ``-`` arguments:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001700
Éric Araujoa8132ec2010-12-16 03:53:53 +00001701* either ``--`` or ``-`` can be option arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +00001702
Éric Araujoa8132ec2010-12-16 03:53:53 +00001703* bare ``--`` (if not the argument to some option): halt command-line
1704 processing and discard the ``--``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001705
Éric Araujoa8132ec2010-12-16 03:53:53 +00001706* bare ``-`` (if not the argument to some option): halt command-line
1707 processing but keep the ``-`` (append it to ``parser.largs``)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001708
1709If you want an option that takes a variable number of arguments, there are
1710several subtle, tricky issues to worry about. The exact implementation you
1711choose will be based on which trade-offs you're willing to make for your
1712application (which is why :mod:`optparse` doesn't support this sort of thing
1713directly).
1714
1715Nevertheless, here's a stab at a callback for an option with variable
1716arguments::
1717
Georg Brandl60b2e382008-12-15 09:07:39 +00001718 def vararg_callback(option, opt_str, value, parser):
1719 assert value is None
1720 value = []
Georg Brandl8ec7f652007-08-15 14:28:01 +00001721
Georg Brandl60b2e382008-12-15 09:07:39 +00001722 def floatable(str):
1723 try:
1724 float(str)
1725 return True
1726 except ValueError:
1727 return False
Georg Brandl8ec7f652007-08-15 14:28:01 +00001728
Georg Brandl60b2e382008-12-15 09:07:39 +00001729 for arg in parser.rargs:
1730 # stop on --foo like options
1731 if arg[:2] == "--" and len(arg) > 2:
1732 break
1733 # stop on -a, but not on -3 or -3.0
1734 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1735 break
1736 value.append(arg)
1737
1738 del parser.rargs[:len(value)]
Georg Brandl174fbe72009-02-05 10:30:57 +00001739 setattr(parser.values, option.dest, value)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001740
1741 [...]
Andrew M. Kuchling810f8072008-09-06 13:04:02 +00001742 parser.add_option("-c", "--callback", dest="vararg_attr",
Benjamin Petersonc8590942008-04-23 20:38:06 +00001743 action="callback", callback=vararg_callback)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001744
Georg Brandl8ec7f652007-08-15 14:28:01 +00001745
1746.. _optparse-extending-optparse:
1747
1748Extending :mod:`optparse`
1749-------------------------
1750
1751Since the two major controlling factors in how :mod:`optparse` interprets
1752command-line options are the action and type of each option, the most likely
1753direction of extension is to add new actions and new types.
1754
1755
1756.. _optparse-adding-new-types:
1757
1758Adding new types
1759^^^^^^^^^^^^^^^^
1760
1761To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandlb926ebb2009-09-17 17:14:04 +00001762:class:`Option` class. This class has a couple of attributes that define
1763:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001764
Georg Brandlb926ebb2009-09-17 17:14:04 +00001765.. attribute:: Option.TYPES
Georg Brandl8ec7f652007-08-15 14:28:01 +00001766
Georg Brandlb926ebb2009-09-17 17:14:04 +00001767 A tuple of type names; in your subclass, simply define a new tuple
1768 :attr:`TYPES` that builds on the standard one.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001769
Georg Brandlb926ebb2009-09-17 17:14:04 +00001770.. attribute:: Option.TYPE_CHECKER
Georg Brandl8ec7f652007-08-15 14:28:01 +00001771
Georg Brandlb926ebb2009-09-17 17:14:04 +00001772 A dictionary mapping type names to type-checking functions. A type-checking
1773 function has the following signature::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001774
Georg Brandlb926ebb2009-09-17 17:14:04 +00001775 def check_mytype(option, opt, value)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001776
Georg Brandlb926ebb2009-09-17 17:14:04 +00001777 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
Éric Araujoa8132ec2010-12-16 03:53:53 +00001778 (e.g., ``-f``), and ``value`` is the string from the command line that must
Georg Brandlb926ebb2009-09-17 17:14:04 +00001779 be checked and converted to your desired type. ``check_mytype()`` should
1780 return an object of the hypothetical type ``mytype``. The value returned by
1781 a type-checking function will wind up in the OptionValues instance returned
1782 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1783 ``value`` parameter.
1784
1785 Your type-checking function should raise :exc:`OptionValueError` if it
1786 encounters any problems. :exc:`OptionValueError` takes a single string
1787 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1788 method, which in turn prepends the program name and the string ``"error:"``
1789 and prints everything to stderr before terminating the process.
1790
1791Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl8ec7f652007-08-15 14:28:01 +00001792parse Python-style complex numbers on the command line. (This is even sillier
1793than it used to be, because :mod:`optparse` 1.3 added built-in support for
1794complex numbers, but never mind.)
1795
1796First, the necessary imports::
1797
1798 from copy import copy
1799 from optparse import Option, OptionValueError
1800
1801You need to define your type-checker first, since it's referred to later (in the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001802:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001803
1804 def check_complex(option, opt, value):
1805 try:
1806 return complex(value)
1807 except ValueError:
1808 raise OptionValueError(
1809 "option %s: invalid complex value: %r" % (opt, value))
1810
1811Finally, the Option subclass::
1812
1813 class MyOption (Option):
1814 TYPES = Option.TYPES + ("complex",)
1815 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1816 TYPE_CHECKER["complex"] = check_complex
1817
1818(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandlb926ebb2009-09-17 17:14:04 +00001819up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1820Option class. This being Python, nothing stops you from doing that except good
1821manners and common sense.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001822
1823That's it! Now you can write a script that uses the new option type just like
1824any other :mod:`optparse`\ -based script, except you have to instruct your
1825OptionParser to use MyOption instead of Option::
1826
1827 parser = OptionParser(option_class=MyOption)
1828 parser.add_option("-c", type="complex")
1829
1830Alternately, you can build your own option list and pass it to OptionParser; if
1831you don't use :meth:`add_option` in the above way, you don't need to tell
1832OptionParser which option class to use::
1833
1834 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1835 parser = OptionParser(option_list=option_list)
1836
1837
1838.. _optparse-adding-new-actions:
1839
1840Adding new actions
1841^^^^^^^^^^^^^^^^^^
1842
1843Adding new actions is a bit trickier, because you have to understand that
1844:mod:`optparse` has a couple of classifications for actions:
1845
1846"store" actions
1847 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001848 current OptionValues instance; these options require a :attr:`~Option.dest`
1849 attribute to be supplied to the Option constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001850
1851"typed" actions
Georg Brandlb926ebb2009-09-17 17:14:04 +00001852 actions that take a value from the command line and expect it to be of a
1853 certain type; or rather, a string that can be converted to a certain type.
1854 These options require a :attr:`~Option.type` attribute to the Option
1855 constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001856
Georg Brandlb926ebb2009-09-17 17:14:04 +00001857These are overlapping sets: some default "store" actions are ``"store"``,
1858``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1859actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001860
1861When you add an action, you need to categorize it by listing it in at least one
1862of the following class attributes of Option (all are lists of strings):
1863
Georg Brandlb926ebb2009-09-17 17:14:04 +00001864.. attribute:: Option.ACTIONS
Georg Brandl8ec7f652007-08-15 14:28:01 +00001865
Georg Brandlb926ebb2009-09-17 17:14:04 +00001866 All actions must be listed in ACTIONS.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001867
Georg Brandlb926ebb2009-09-17 17:14:04 +00001868.. attribute:: Option.STORE_ACTIONS
Georg Brandl8ec7f652007-08-15 14:28:01 +00001869
Georg Brandlb926ebb2009-09-17 17:14:04 +00001870 "store" actions are additionally listed here.
1871
1872.. attribute:: Option.TYPED_ACTIONS
1873
1874 "typed" actions are additionally listed here.
1875
1876.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1877
1878 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl8ec7f652007-08-15 14:28:01 +00001879 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00001880 assigns the default type, ``"string"``, to options with no explicit type
1881 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001882
1883In order to actually implement your new action, you must override Option's
1884:meth:`take_action` method and add a case that recognizes your action.
1885
Georg Brandlb926ebb2009-09-17 17:14:04 +00001886For example, let's add an ``"extend"`` action. This is similar to the standard
1887``"append"`` action, but instead of taking a single value from the command-line
1888and appending it to an existing list, ``"extend"`` will take multiple values in
1889a single comma-delimited string, and extend an existing list with them. That
Éric Araujoa8132ec2010-12-16 03:53:53 +00001890is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
Georg Brandlb926ebb2009-09-17 17:14:04 +00001891line ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001892
1893 --names=foo,bar --names blah --names ding,dong
1894
1895would result in a list ::
1896
1897 ["foo", "bar", "blah", "ding", "dong"]
1898
1899Again we define a subclass of Option::
1900
Ezio Melotti5129ed32010-01-03 09:01:27 +00001901 class MyOption(Option):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001902
1903 ACTIONS = Option.ACTIONS + ("extend",)
1904 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1905 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1906 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1907
1908 def take_action(self, action, dest, opt, value, values, parser):
1909 if action == "extend":
1910 lvalue = value.split(",")
1911 values.ensure_value(dest, []).extend(lvalue)
1912 else:
1913 Option.take_action(
1914 self, action, dest, opt, value, values, parser)
1915
1916Features of note:
1917
Georg Brandlb926ebb2009-09-17 17:14:04 +00001918* ``"extend"`` both expects a value on the command-line and stores that value
1919 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1920 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001921
Georg Brandlb926ebb2009-09-17 17:14:04 +00001922* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1923 ``"extend"`` actions, we put the ``"extend"`` action in
1924 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001925
1926* :meth:`MyOption.take_action` implements just this one new action, and passes
1927 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00001928 actions.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001929
Georg Brandlb926ebb2009-09-17 17:14:04 +00001930* ``values`` is an instance of the optparse_parser.Values class, which provides
1931 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1932 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001933
1934 values.ensure_value(attr, value)
1935
1936 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandlb926ebb2009-09-17 17:14:04 +00001937 ensure_value() first sets it to ``value``, and then returns 'value. This is
1938 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
1939 of which accumulate data in a variable and expect that variable to be of a
1940 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl8ec7f652007-08-15 14:28:01 +00001941 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandlb926ebb2009-09-17 17:14:04 +00001942 about setting a default value for the option destinations in question; they
1943 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl8ec7f652007-08-15 14:28:01 +00001944 getting it right when it's needed.