blob: d4b121bc8dc59a6704161b13f0305563ba73abae [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
Georg Brandl28046022011-02-25 11:01:04 +000067 Usage: <yourscript> [options]
Georg Brandl8ec7f652007-08-15 14:28:01 +000068
Georg Brandl28046022011-02-25 11:01:04 +000069 Options:
Georg Brandl8ec7f652007-08-15 14:28:01 +000070 -h, --help show this help message and exit
71 -f FILE, --file=FILE write report to FILE
72 -q, --quiet don't print status messages to stdout
73
74where the value of *yourscript* is determined at runtime (normally from
75``sys.argv[0]``).
76
Georg 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
Georg Brandl28046022011-02-25 11:01:04 +0000498 Usage: <yourscript> [options] arg1 arg2
Georg Brandl8ec7f652007-08-15 14:28:01 +0000499
Georg Brandl28046022011-02-25 11:01:04 +0000500 Options:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000501 -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 Brandl28046022011-02-25 11:01:04 +0000524 default: ``"Usage: %prog [options]"``, which is fine if your script doesn't
Georg Brandlb926ebb2009-09-17 17:14:04 +0000525 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 Brandl28046022011-02-25 11:01:04 +0000557Grouping Options
558++++++++++++++++
559
Georg Brandlb926ebb2009-09-17 17:14:04 +0000560When dealing with many options, it is convenient to group these options for
561better help output. An :class:`OptionParser` can contain several option groups,
562each of which can contain several options.
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000563
Georg Brandl28046022011-02-25 11:01:04 +0000564An option group is obtained using the class :class:`OptionGroup`:
565
566.. class:: OptionGroup(parser, title, description=None)
567
568 where
569
570 * parser is the :class:`OptionParser` instance the group will be insterted in
571 to
572 * title is the group title
573 * description, optional, is a long description of the group
574
575:class:`OptionGroup` inherits from :class:`OptionContainer` (like
576:class:`OptionParser`) and so the :meth:`add_option` method can be used to add
577an option to the group.
578
579Once all the options are declared, using the :class:`OptionParser` method
580:meth:`add_option_group` the group is added to the previously defined parser.
581
582Continuing with the parser defined in the previous section, adding an
583:class:`OptionGroup` to a parser is easy::
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000584
585 group = OptionGroup(parser, "Dangerous Options",
Georg Brandl7044b112009-01-03 21:04:55 +0000586 "Caution: use these options at your own risk. "
587 "It is believed that some of them bite.")
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000588 group.add_option("-g", action="store_true", help="Group option.")
589 parser.add_option_group(group)
590
Ezio Melotti5129ed32010-01-03 09:01:27 +0000591This would result in the following help output:
592
593.. code-block:: text
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000594
Georg Brandl28046022011-02-25 11:01:04 +0000595 Usage: <yourscript> [options] arg1 arg2
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000596
Georg Brandl28046022011-02-25 11:01:04 +0000597 Options:
598 -h, --help show this help message and exit
599 -v, --verbose make lots of noise [default]
600 -q, --quiet be vewwy quiet (I'm hunting wabbits)
601 -f FILE, --filename=FILE
602 write output to FILE
603 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
604 expert [default: intermediate]
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000605
Georg Brandl28046022011-02-25 11:01:04 +0000606 Dangerous Options:
607 Caution: use these options at your own risk. It is believed that some
608 of them bite.
609
610 -g Group option.
611
612A bit more complete example might invole using more than one group: still
613extendind the previous example::
614
615 group = OptionGroup(parser, "Dangerous Options",
616 "Caution: use these options at your own risk. "
617 "It is believed that some of them bite.")
618 group.add_option("-g", action="store_true", help="Group option.")
619 parser.add_option_group(group)
620
621 group = OptionGroup(parser, "Debug Options")
622 group.add_option("-d", "--debug", action="store_true",
623 help="Print debug information")
624 group.add_option("-s", "--sql", action="store_true",
625 help="Print all SQL statements executed")
626 group.add_option("-e", action="store_true", help="Print every action done")
627 parser.add_option_group(group)
628
629that results in the following output:
630
631.. code-block:: text
632
633 Usage: <yourscript> [options] arg1 arg2
634
635 Options:
636 -h, --help show this help message and exit
637 -v, --verbose make lots of noise [default]
638 -q, --quiet be vewwy quiet (I'm hunting wabbits)
639 -f FILE, --filename=FILE
640 write output to FILE
641 -m MODE, --mode=MODE interaction mode: novice, intermediate, or expert
642 [default: intermediate]
643
644 Dangerous Options:
645 Caution: use these options at your own risk. It is believed that some
646 of them bite.
647
648 -g Group option.
649
650 Debug Options:
651 -d, --debug Print debug information
652 -s, --sql Print all SQL statements executed
653 -e Print every action done
654
655Another interesting method, in particular when working programmatically with
656option groups is:
657
658.. method:: OptionParser.get_option_group(opt_str)
659
660 Return, if defined, the :class:`OptionGroup` that has the title or the long
661 description equals to *opt_str*
Georg Brandl8ec7f652007-08-15 14:28:01 +0000662
663.. _optparse-printing-version-string:
664
665Printing a version string
666^^^^^^^^^^^^^^^^^^^^^^^^^
667
668Similar to the brief usage string, :mod:`optparse` can also print a version
669string for your program. You have to supply the string as the ``version``
670argument to OptionParser::
671
672 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
673
Éric Araujoa8132ec2010-12-16 03:53:53 +0000674``%prog`` is expanded just like it is in ``usage``. Apart from that,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000675``version`` can contain anything you like. When you supply it, :mod:`optparse`
Éric Araujoa8132ec2010-12-16 03:53:53 +0000676automatically adds a ``--version`` option to your parser. If it encounters
Georg Brandl8ec7f652007-08-15 14:28:01 +0000677this option on the command line, it expands your ``version`` string (by
Éric Araujoa8132ec2010-12-16 03:53:53 +0000678replacing ``%prog``), prints it to stdout, and exits.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000679
680For example, if your script is called ``/usr/bin/foo``::
681
682 $ /usr/bin/foo --version
683 foo 1.0
684
Ezio Melottib9c3ed42010-01-04 21:43:02 +0000685The following two methods can be used to print and get the ``version`` string:
686
687.. method:: OptionParser.print_version(file=None)
688
689 Print the version message for the current program (``self.version``) to
690 *file* (default stdout). As with :meth:`print_usage`, any occurrence
Éric Araujoa8132ec2010-12-16 03:53:53 +0000691 of ``%prog`` in ``self.version`` is replaced with the name of the current
Ezio Melottib9c3ed42010-01-04 21:43:02 +0000692 program. Does nothing if ``self.version`` is empty or undefined.
693
694.. method:: OptionParser.get_version()
695
696 Same as :meth:`print_version` but returns the version string instead of
697 printing it.
698
Georg Brandl8ec7f652007-08-15 14:28:01 +0000699
700.. _optparse-how-optparse-handles-errors:
701
702How :mod:`optparse` handles errors
703^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
704
705There are two broad classes of errors that :mod:`optparse` has to worry about:
706programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandlb926ebb2009-09-17 17:14:04 +0000707calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
708option attributes, missing option attributes, etc. These are dealt with in the
709usual way: raise an exception (either :exc:`optparse.OptionError` or
710:exc:`TypeError`) and let the program crash.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000711
712Handling user errors is much more important, since they are guaranteed to happen
713no matter how stable your code is. :mod:`optparse` can automatically detect
Éric Araujoa8132ec2010-12-16 03:53:53 +0000714some user errors, such as bad option arguments (passing ``-n 4x`` where
715``-n`` takes an integer argument), missing arguments (``-n`` at the end
716of the command line, where ``-n`` takes an argument of any type). Also,
Georg Brandlb926ebb2009-09-17 17:14:04 +0000717you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl8ec7f652007-08-15 14:28:01 +0000718condition::
719
720 (options, args) = parser.parse_args()
721 [...]
722 if options.a and options.b:
723 parser.error("options -a and -b are mutually exclusive")
724
725In either case, :mod:`optparse` handles the error the same way: it prints the
726program's usage message and an error message to standard error and exits with
727error status 2.
728
Éric Araujoa8132ec2010-12-16 03:53:53 +0000729Consider the first example above, where the user passes ``4x`` to an option
Georg Brandl8ec7f652007-08-15 14:28:01 +0000730that takes an integer::
731
732 $ /usr/bin/foo -n 4x
Georg Brandl28046022011-02-25 11:01:04 +0000733 Usage: foo [options]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000734
735 foo: error: option -n: invalid integer value: '4x'
736
737Or, where the user fails to pass a value at all::
738
739 $ /usr/bin/foo -n
Georg Brandl28046022011-02-25 11:01:04 +0000740 Usage: foo [options]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000741
742 foo: error: -n option requires an argument
743
744:mod:`optparse`\ -generated error messages take care always to mention the
745option involved in the error; be sure to do the same when calling
Georg Brandlb926ebb2009-09-17 17:14:04 +0000746:func:`OptionParser.error` from your application code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000747
Georg Brandl60c0be32008-06-13 13:26:54 +0000748If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Georg Brandl0c9eb432009-06-30 16:35:11 +0000749you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
750and/or :meth:`~OptionParser.error` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000751
752
753.. _optparse-putting-it-all-together:
754
755Putting it all together
756^^^^^^^^^^^^^^^^^^^^^^^
757
758Here's what :mod:`optparse`\ -based scripts usually look like::
759
760 from optparse import OptionParser
761 [...]
762 def main():
763 usage = "usage: %prog [options] arg"
764 parser = OptionParser(usage)
765 parser.add_option("-f", "--file", dest="filename",
766 help="read data from FILENAME")
767 parser.add_option("-v", "--verbose",
768 action="store_true", dest="verbose")
769 parser.add_option("-q", "--quiet",
770 action="store_false", dest="verbose")
771 [...]
772 (options, args) = parser.parse_args()
773 if len(args) != 1:
774 parser.error("incorrect number of arguments")
775 if options.verbose:
776 print "reading %s..." % options.filename
777 [...]
778
779 if __name__ == "__main__":
780 main()
781
Georg Brandl8ec7f652007-08-15 14:28:01 +0000782
783.. _optparse-reference-guide:
784
785Reference Guide
786---------------
787
788
789.. _optparse-creating-parser:
790
791Creating the parser
792^^^^^^^^^^^^^^^^^^^
793
Georg Brandlb926ebb2009-09-17 17:14:04 +0000794The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000795
Georg Brandlb926ebb2009-09-17 17:14:04 +0000796.. class:: OptionParser(...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000797
Georg Brandlb926ebb2009-09-17 17:14:04 +0000798 The OptionParser constructor has no required arguments, but a number of
799 optional keyword arguments. You should always pass them as keyword
800 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000801
802 ``usage`` (default: ``"%prog [options]"``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000803 The usage summary to print when your program is run incorrectly or with a
804 help option. When :mod:`optparse` prints the usage string, it expands
805 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
806 passed that keyword argument). To suppress a usage message, pass the
807 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000808
809 ``option_list`` (default: ``[]``)
810 A list of Option objects to populate the parser with. The options in
Georg Brandlb926ebb2009-09-17 17:14:04 +0000811 ``option_list`` are added after any options in ``standard_option_list`` (a
812 class attribute that may be set by OptionParser subclasses), but before
813 any version or help options. Deprecated; use :meth:`add_option` after
814 creating the parser instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000815
816 ``option_class`` (default: optparse.Option)
817 Class to use when adding options to the parser in :meth:`add_option`.
818
819 ``version`` (default: ``None``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000820 A version string to print when the user supplies a version option. If you
821 supply a true value for ``version``, :mod:`optparse` automatically adds a
Éric Araujoa8132ec2010-12-16 03:53:53 +0000822 version option with the single option string ``--version``. The
823 substring ``%prog`` is expanded the same as for ``usage``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000824
825 ``conflict_handler`` (default: ``"error"``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000826 Specifies what to do when options with conflicting option strings are
827 added to the parser; see section
828 :ref:`optparse-conflicts-between-options`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000829
830 ``description`` (default: ``None``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000831 A paragraph of text giving a brief overview of your program.
832 :mod:`optparse` reformats this paragraph to fit the current terminal width
833 and prints it when the user requests help (after ``usage``, but before the
834 list of options).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000835
Georg Brandlb926ebb2009-09-17 17:14:04 +0000836 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
837 An instance of optparse.HelpFormatter that will be used for printing help
838 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000839 IndentedHelpFormatter and TitledHelpFormatter.
840
841 ``add_help_option`` (default: ``True``)
Éric Araujoa8132ec2010-12-16 03:53:53 +0000842 If true, :mod:`optparse` will add a help option (with option strings ``-h``
843 and ``--help``) to the parser.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000844
845 ``prog``
Éric Araujoa8132ec2010-12-16 03:53:53 +0000846 The string to use when expanding ``%prog`` in ``usage`` and ``version``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000847 instead of ``os.path.basename(sys.argv[0])``.
848
Senthil Kumaran67b4e182010-03-23 08:46:31 +0000849 ``epilog`` (default: ``None``)
850 A paragraph of help text to print after the option help.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000851
852.. _optparse-populating-parser:
853
854Populating the parser
855^^^^^^^^^^^^^^^^^^^^^
856
857There are several ways to populate the parser with options. The preferred way
Georg Brandlb926ebb2009-09-17 17:14:04 +0000858is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl8ec7f652007-08-15 14:28:01 +0000859:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
860
861* pass it an Option instance (as returned by :func:`make_option`)
862
863* pass it any combination of positional and keyword arguments that are
Georg Brandlb926ebb2009-09-17 17:14:04 +0000864 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
865 will create the Option instance for you
Georg Brandl8ec7f652007-08-15 14:28:01 +0000866
867The other alternative is to pass a list of pre-constructed Option instances to
868the OptionParser constructor, as in::
869
870 option_list = [
871 make_option("-f", "--filename",
872 action="store", type="string", dest="filename"),
873 make_option("-q", "--quiet",
874 action="store_false", dest="verbose"),
875 ]
876 parser = OptionParser(option_list=option_list)
877
878(:func:`make_option` is a factory function for creating Option instances;
879currently it is an alias for the Option constructor. A future version of
880:mod:`optparse` may split Option into several classes, and :func:`make_option`
881will pick the right class to instantiate. Do not instantiate Option directly.)
882
883
884.. _optparse-defining-options:
885
886Defining options
887^^^^^^^^^^^^^^^^
888
889Each Option instance represents a set of synonymous command-line option strings,
Éric Araujoa8132ec2010-12-16 03:53:53 +0000890e.g. ``-f`` and ``--file``. You can specify any number of short or
Georg Brandl8ec7f652007-08-15 14:28:01 +0000891long option strings, but you must specify at least one overall option string.
892
Georg Brandlb926ebb2009-09-17 17:14:04 +0000893The canonical way to create an :class:`Option` instance is with the
894:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000895
Georg Brandlb926ebb2009-09-17 17:14:04 +0000896.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000897
Georg Brandlb926ebb2009-09-17 17:14:04 +0000898 To define an option with only a short option string::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000899
Georg Brandlb926ebb2009-09-17 17:14:04 +0000900 parser.add_option("-f", attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000901
Georg Brandlb926ebb2009-09-17 17:14:04 +0000902 And to define an option with only a long option string::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000903
Georg Brandlb926ebb2009-09-17 17:14:04 +0000904 parser.add_option("--foo", attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000905
Georg Brandlb926ebb2009-09-17 17:14:04 +0000906 The keyword arguments define attributes of the new Option object. The most
907 important option attribute is :attr:`~Option.action`, and it largely
908 determines which other attributes are relevant or required. If you pass
909 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
910 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000911
Georg Brandlb926ebb2009-09-17 17:14:04 +0000912 An option's *action* determines what :mod:`optparse` does when it encounters
913 this option on the command-line. The standard option actions hard-coded into
914 :mod:`optparse` are:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000915
Georg Brandlb926ebb2009-09-17 17:14:04 +0000916 ``"store"``
917 store this option's argument (default)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000918
Georg Brandlb926ebb2009-09-17 17:14:04 +0000919 ``"store_const"``
920 store a constant value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000921
Georg Brandlb926ebb2009-09-17 17:14:04 +0000922 ``"store_true"``
923 store a true value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000924
Georg Brandlb926ebb2009-09-17 17:14:04 +0000925 ``"store_false"``
926 store a false value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000927
Georg Brandlb926ebb2009-09-17 17:14:04 +0000928 ``"append"``
929 append this option's argument to a list
Georg Brandl8ec7f652007-08-15 14:28:01 +0000930
Georg Brandlb926ebb2009-09-17 17:14:04 +0000931 ``"append_const"``
932 append a constant value to a list
Georg Brandl8ec7f652007-08-15 14:28:01 +0000933
Georg Brandlb926ebb2009-09-17 17:14:04 +0000934 ``"count"``
935 increment a counter by one
Georg Brandl8ec7f652007-08-15 14:28:01 +0000936
Georg Brandlb926ebb2009-09-17 17:14:04 +0000937 ``"callback"``
938 call a specified function
Georg Brandl8ec7f652007-08-15 14:28:01 +0000939
Georg Brandlb926ebb2009-09-17 17:14:04 +0000940 ``"help"``
941 print a usage message including all options and the documentation for them
Georg Brandl8ec7f652007-08-15 14:28:01 +0000942
Georg Brandlb926ebb2009-09-17 17:14:04 +0000943 (If you don't supply an action, the default is ``"store"``. For this action,
944 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
945 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000946
947As you can see, most actions involve storing or updating a value somewhere.
948:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandlb926ebb2009-09-17 17:14:04 +0000949``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl8ec7f652007-08-15 14:28:01 +0000950arguments (and various other values) are stored as attributes of this object,
Georg Brandlb926ebb2009-09-17 17:14:04 +0000951according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000952
Georg Brandlb926ebb2009-09-17 17:14:04 +0000953For example, when you call ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000954
955 parser.parse_args()
956
957one of the first things :mod:`optparse` does is create the ``options`` object::
958
959 options = Values()
960
Georg Brandlb926ebb2009-09-17 17:14:04 +0000961If one of the options in this parser is defined with ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000962
963 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
964
965and the command-line being parsed includes any of the following::
966
967 -ffoo
968 -f foo
969 --file=foo
970 --file foo
971
Georg Brandlb926ebb2009-09-17 17:14:04 +0000972then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000973
974 options.filename = "foo"
975
Georg Brandlb926ebb2009-09-17 17:14:04 +0000976The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
977as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
978one that makes sense for *all* options.
979
980
981.. _optparse-option-attributes:
982
983Option attributes
984^^^^^^^^^^^^^^^^^
985
986The following option attributes may be passed as keyword arguments to
987:meth:`OptionParser.add_option`. If you pass an option attribute that is not
988relevant to a particular option, or fail to pass a required option attribute,
989:mod:`optparse` raises :exc:`OptionError`.
990
991.. attribute:: Option.action
992
993 (default: ``"store"``)
994
995 Determines :mod:`optparse`'s behaviour when this option is seen on the
996 command line; the available options are documented :ref:`here
997 <optparse-standard-option-actions>`.
998
999.. attribute:: Option.type
1000
1001 (default: ``"string"``)
1002
1003 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
1004 the available option types are documented :ref:`here
1005 <optparse-standard-option-types>`.
1006
1007.. attribute:: Option.dest
1008
1009 (default: derived from option strings)
1010
1011 If the option's action implies writing or modifying a value somewhere, this
1012 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
1013 attribute of the ``options`` object that :mod:`optparse` builds as it parses
1014 the command line.
1015
1016.. attribute:: Option.default
1017
1018 The value to use for this option's destination if the option is not seen on
1019 the command line. See also :meth:`OptionParser.set_defaults`.
1020
1021.. attribute:: Option.nargs
1022
1023 (default: 1)
1024
1025 How many arguments of type :attr:`~Option.type` should be consumed when this
1026 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
1027 :attr:`~Option.dest`.
1028
1029.. attribute:: Option.const
1030
1031 For actions that store a constant value, the constant value to store.
1032
1033.. attribute:: Option.choices
1034
1035 For options of type ``"choice"``, the list of strings the user may choose
1036 from.
1037
1038.. attribute:: Option.callback
1039
1040 For options with action ``"callback"``, the callable to call when this option
1041 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1042 arguments passed to the callable.
1043
1044.. attribute:: Option.callback_args
1045 Option.callback_kwargs
1046
1047 Additional positional and keyword arguments to pass to ``callback`` after the
1048 four standard callback arguments.
1049
1050.. attribute:: Option.help
1051
1052 Help text to print for this option when listing all available options after
Éric Araujoa8132ec2010-12-16 03:53:53 +00001053 the user supplies a :attr:`~Option.help` option (such as ``--help``). If
Georg Brandlb926ebb2009-09-17 17:14:04 +00001054 no help text is supplied, the option will be listed without help text. To
1055 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
1056
1057.. attribute:: Option.metavar
1058
1059 (default: derived from option strings)
1060
1061 Stand-in for the option argument(s) to use when printing help text. See
1062 section :ref:`optparse-tutorial` for an example.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001063
1064
1065.. _optparse-standard-option-actions:
1066
1067Standard option actions
1068^^^^^^^^^^^^^^^^^^^^^^^
1069
1070The various option actions all have slightly different requirements and effects.
1071Most actions have several relevant option attributes which you may specify to
1072guide :mod:`optparse`'s behaviour; a few have required attributes, which you
1073must specify for any option using that action.
1074
Georg Brandlb926ebb2009-09-17 17:14:04 +00001075* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1076 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001077
1078 The option must be followed by an argument, which is converted to a value
Georg Brandlb926ebb2009-09-17 17:14:04 +00001079 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1080 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1081 command line; all will be converted according to :attr:`~Option.type` and
1082 stored to :attr:`~Option.dest` as a tuple. See the
1083 :ref:`optparse-standard-option-types` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001084
Georg Brandlb926ebb2009-09-17 17:14:04 +00001085 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1086 defaults to ``"choice"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001087
Georg Brandlb926ebb2009-09-17 17:14:04 +00001088 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001089
Georg Brandlb926ebb2009-09-17 17:14:04 +00001090 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
Éric Araujoa8132ec2010-12-16 03:53:53 +00001091 from the first long option string (e.g., ``--foo-bar`` implies
Georg Brandlb926ebb2009-09-17 17:14:04 +00001092 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
Éric Araujoa8132ec2010-12-16 03:53:53 +00001093 destination from the first short option string (e.g., ``-f`` implies ``f``).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001094
1095 Example::
1096
1097 parser.add_option("-f")
1098 parser.add_option("-p", type="float", nargs=3, dest="point")
1099
Georg Brandlb926ebb2009-09-17 17:14:04 +00001100 As it parses the command line ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001101
1102 -f foo.txt -p 1 -3.5 4 -fbar.txt
1103
Georg Brandlb926ebb2009-09-17 17:14:04 +00001104 :mod:`optparse` will set ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001105
1106 options.f = "foo.txt"
1107 options.point = (1.0, -3.5, 4.0)
1108 options.f = "bar.txt"
1109
Georg Brandlb926ebb2009-09-17 17:14:04 +00001110* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1111 :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001112
Georg Brandlb926ebb2009-09-17 17:14:04 +00001113 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001114
1115 Example::
1116
1117 parser.add_option("-q", "--quiet",
1118 action="store_const", const=0, dest="verbose")
1119 parser.add_option("-v", "--verbose",
1120 action="store_const", const=1, dest="verbose")
1121 parser.add_option("--noisy",
1122 action="store_const", const=2, dest="verbose")
1123
Éric Araujoa8132ec2010-12-16 03:53:53 +00001124 If ``--noisy`` is seen, :mod:`optparse` will set ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001125
1126 options.verbose = 2
1127
Georg Brandlb926ebb2009-09-17 17:14:04 +00001128* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001129
Georg Brandlb926ebb2009-09-17 17:14:04 +00001130 A special case of ``"store_const"`` that stores a true value to
1131 :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001132
Georg Brandlb926ebb2009-09-17 17:14:04 +00001133* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001134
Georg Brandlb926ebb2009-09-17 17:14:04 +00001135 Like ``"store_true"``, but stores a false value.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001136
1137 Example::
1138
1139 parser.add_option("--clobber", action="store_true", dest="clobber")
1140 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1141
Georg Brandlb926ebb2009-09-17 17:14:04 +00001142* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1143 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001144
1145 The option must be followed by an argument, which is appended to the list in
Georg Brandlb926ebb2009-09-17 17:14:04 +00001146 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1147 supplied, an empty list is automatically created when :mod:`optparse` first
1148 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1149 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1150 is appended to :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001151
Georg Brandlb926ebb2009-09-17 17:14:04 +00001152 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1153 for the ``"store"`` action.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001154
1155 Example::
1156
1157 parser.add_option("-t", "--tracks", action="append", type="int")
1158
Éric Araujoa8132ec2010-12-16 03:53:53 +00001159 If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
Georg Brandl8ec7f652007-08-15 14:28:01 +00001160 of::
1161
1162 options.tracks = []
1163 options.tracks.append(int("3"))
1164
Éric Araujoa8132ec2010-12-16 03:53:53 +00001165 If, a little later on, ``--tracks=4`` is seen, it does::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001166
1167 options.tracks.append(int("4"))
1168
Georg Brandlb926ebb2009-09-17 17:14:04 +00001169* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1170 :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001171
Georg Brandlb926ebb2009-09-17 17:14:04 +00001172 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1173 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1174 ``None``, and an empty list is automatically created the first time the option
1175 is encountered.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001176
Georg Brandlb926ebb2009-09-17 17:14:04 +00001177* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001178
Georg Brandlb926ebb2009-09-17 17:14:04 +00001179 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1180 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1181 first time.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001182
1183 Example::
1184
1185 parser.add_option("-v", action="count", dest="verbosity")
1186
Éric Araujoa8132ec2010-12-16 03:53:53 +00001187 The first time ``-v`` is seen on the command line, :mod:`optparse` does the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001188 equivalent of::
1189
1190 options.verbosity = 0
1191 options.verbosity += 1
1192
Éric Araujoa8132ec2010-12-16 03:53:53 +00001193 Every subsequent occurrence of ``-v`` results in ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001194
1195 options.verbosity += 1
1196
Georg Brandlb926ebb2009-09-17 17:14:04 +00001197* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1198 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1199 :attr:`~Option.callback_kwargs`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001200
Georg Brandlb926ebb2009-09-17 17:14:04 +00001201 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001202
1203 func(option, opt_str, value, parser, *args, **kwargs)
1204
1205 See section :ref:`optparse-option-callbacks` for more detail.
1206
Georg Brandlb926ebb2009-09-17 17:14:04 +00001207* ``"help"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001208
Georg Brandlb926ebb2009-09-17 17:14:04 +00001209 Prints a complete help message for all the options in the current option
1210 parser. The help message is constructed from the ``usage`` string passed to
1211 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1212 option.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001213
Georg Brandlb926ebb2009-09-17 17:14:04 +00001214 If no :attr:`~Option.help` string is supplied for an option, it will still be
1215 listed in the help message. To omit an option entirely, use the special value
1216 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001217
Georg Brandlb926ebb2009-09-17 17:14:04 +00001218 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1219 OptionParsers, so you do not normally need to create one.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001220
1221 Example::
1222
1223 from optparse import OptionParser, SUPPRESS_HELP
1224
Georg Brandl718b2212009-09-16 13:11:06 +00001225 # usually, a help option is added automatically, but that can
1226 # be suppressed using the add_help_option argument
1227 parser = OptionParser(add_help_option=False)
1228
Georg Brandld7226ff2009-09-16 13:06:22 +00001229 parser.add_option("-h", "--help", action="help")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001230 parser.add_option("-v", action="store_true", dest="verbose",
1231 help="Be moderately verbose")
1232 parser.add_option("--file", dest="filename",
Georg Brandld7226ff2009-09-16 13:06:22 +00001233 help="Input file to read data from")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001234 parser.add_option("--secret", help=SUPPRESS_HELP)
1235
Éric Araujoa8132ec2010-12-16 03:53:53 +00001236 If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
Georg Brandlb926ebb2009-09-17 17:14:04 +00001237 it will print something like the following help message to stdout (assuming
Ezio Melotti5129ed32010-01-03 09:01:27 +00001238 ``sys.argv[0]`` is ``"foo.py"``):
1239
1240 .. code-block:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +00001241
Georg Brandl28046022011-02-25 11:01:04 +00001242 Usage: foo.py [options]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001243
Georg Brandl28046022011-02-25 11:01:04 +00001244 Options:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001245 -h, --help Show this help message and exit
1246 -v Be moderately verbose
1247 --file=FILENAME Input file to read data from
1248
1249 After printing the help message, :mod:`optparse` terminates your process with
1250 ``sys.exit(0)``.
1251
Georg Brandlb926ebb2009-09-17 17:14:04 +00001252* ``"version"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001253
Georg Brandlb926ebb2009-09-17 17:14:04 +00001254 Prints the version number supplied to the OptionParser to stdout and exits.
1255 The version number is actually formatted and printed by the
1256 ``print_version()`` method of OptionParser. Generally only relevant if the
1257 ``version`` argument is supplied to the OptionParser constructor. As with
1258 :attr:`~Option.help` options, you will rarely create ``version`` options,
1259 since :mod:`optparse` automatically adds them when needed.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001260
1261
1262.. _optparse-standard-option-types:
1263
1264Standard option types
1265^^^^^^^^^^^^^^^^^^^^^
1266
Georg Brandlb926ebb2009-09-17 17:14:04 +00001267:mod:`optparse` has six built-in option types: ``"string"``, ``"int"``,
1268``"long"``, ``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1269option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001270
1271Arguments to string options are not checked or converted in any way: the text on
1272the command line is stored in the destination (or passed to the callback) as-is.
1273
Georg Brandlb926ebb2009-09-17 17:14:04 +00001274Integer arguments (type ``"int"`` or ``"long"``) are parsed as follows:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001275
1276* if the number starts with ``0x``, it is parsed as a hexadecimal number
1277
1278* if the number starts with ``0``, it is parsed as an octal number
1279
Georg Brandl97ca5832007-09-24 17:55:47 +00001280* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl8ec7f652007-08-15 14:28:01 +00001281
1282* otherwise, the number is parsed as a decimal number
1283
1284
Georg Brandlb926ebb2009-09-17 17:14:04 +00001285The conversion is done by calling either :func:`int` or :func:`long` with the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001286appropriate base (2, 8, 10, or 16). If this fails, so will :mod:`optparse`,
1287although with a more useful error message.
1288
Georg Brandlb926ebb2009-09-17 17:14:04 +00001289``"float"`` and ``"complex"`` option arguments are converted directly with
1290:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001291
Georg Brandlb926ebb2009-09-17 17:14:04 +00001292``"choice"`` options are a subtype of ``"string"`` options. The
Georg Brandl35e7a8f2010-10-06 10:41:31 +00001293:attr:`~Option.choices` option attribute (a sequence of strings) defines the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001294set of allowed option arguments. :func:`optparse.check_choice` compares
1295user-supplied option arguments against this master list and raises
1296:exc:`OptionValueError` if an invalid string is given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001297
1298
1299.. _optparse-parsing-arguments:
1300
1301Parsing arguments
1302^^^^^^^^^^^^^^^^^
1303
1304The whole point of creating and populating an OptionParser is to call its
1305:meth:`parse_args` method::
1306
1307 (options, args) = parser.parse_args(args=None, values=None)
1308
1309where the input parameters are
1310
1311``args``
1312 the list of arguments to process (default: ``sys.argv[1:]``)
1313
1314``values``
Georg Brandl0347c712010-08-01 19:02:09 +00001315 a :class:`optparse.Values` object to store option arguments in (default: a
1316 new instance of :class:`Values`) -- if you give an existing object, the
1317 option defaults will not be initialized on it
Georg Brandl8ec7f652007-08-15 14:28:01 +00001318
1319and the return values are
1320
1321``options``
Georg Brandl8514b852009-09-01 08:06:03 +00001322 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl8ec7f652007-08-15 14:28:01 +00001323 instance created by :mod:`optparse`
1324
1325``args``
1326 the leftover positional arguments after all options have been processed
1327
1328The most common usage is to supply neither keyword argument. If you supply
Georg Brandlb926ebb2009-09-17 17:14:04 +00001329``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl8ec7f652007-08-15 14:28:01 +00001330for every option argument stored to an option destination) and returned by
1331:meth:`parse_args`.
1332
1333If :meth:`parse_args` encounters any errors in the argument list, it calls the
1334OptionParser's :meth:`error` method with an appropriate end-user error message.
1335This ultimately terminates your process with an exit status of 2 (the
1336traditional Unix exit status for command-line errors).
1337
1338
1339.. _optparse-querying-manipulating-option-parser:
1340
1341Querying and manipulating your option parser
1342^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1343
Georg Brandlb926ebb2009-09-17 17:14:04 +00001344The default behavior of the option parser can be customized slightly, and you
1345can also poke around your option parser and see what's there. OptionParser
1346provides several methods to help you out:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001347
Georg Brandlb926ebb2009-09-17 17:14:04 +00001348.. method:: OptionParser.disable_interspersed_args()
Georg Brandl7842a412009-09-17 16:26:06 +00001349
Éric Araujoa8132ec2010-12-16 03:53:53 +00001350 Set parsing to stop on the first non-option. For example, if ``-a`` and
1351 ``-b`` are both simple options that take no arguments, :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00001352 normally accepts this syntax::
Georg Brandl7842a412009-09-17 16:26:06 +00001353
Georg Brandlb926ebb2009-09-17 17:14:04 +00001354 prog -a arg1 -b arg2
Georg Brandl7842a412009-09-17 16:26:06 +00001355
Georg Brandlb926ebb2009-09-17 17:14:04 +00001356 and treats it as equivalent to ::
Georg Brandl7842a412009-09-17 16:26:06 +00001357
Georg Brandlb926ebb2009-09-17 17:14:04 +00001358 prog -a -b arg1 arg2
Georg Brandl7842a412009-09-17 16:26:06 +00001359
Georg Brandlb926ebb2009-09-17 17:14:04 +00001360 To disable this feature, call :meth:`disable_interspersed_args`. This
1361 restores traditional Unix syntax, where option parsing stops with the first
1362 non-option argument.
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001363
Georg Brandlb926ebb2009-09-17 17:14:04 +00001364 Use this if you have a command processor which runs another command which has
1365 options of its own and you want to make sure these options don't get
1366 confused. For example, each command might have a different set of options.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001367
Georg Brandlb926ebb2009-09-17 17:14:04 +00001368.. method:: OptionParser.enable_interspersed_args()
1369
1370 Set parsing to not stop on the first non-option, allowing interspersing
1371 switches with command arguments. This is the default behavior.
1372
1373.. method:: OptionParser.get_option(opt_str)
1374
1375 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl8ec7f652007-08-15 14:28:01 +00001376 no options have that option string.
1377
Georg Brandlb926ebb2009-09-17 17:14:04 +00001378.. method:: OptionParser.has_option(opt_str)
1379
1380 Return true if the OptionParser has an option with option string *opt_str*
Éric Araujoa8132ec2010-12-16 03:53:53 +00001381 (e.g., ``-q`` or ``--verbose``).
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001382
Georg Brandlb926ebb2009-09-17 17:14:04 +00001383.. method:: OptionParser.remove_option(opt_str)
1384
1385 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1386 option is removed. If that option provided any other option strings, all of
1387 those option strings become invalid. If *opt_str* does not occur in any
1388 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001389
1390
1391.. _optparse-conflicts-between-options:
1392
1393Conflicts between options
1394^^^^^^^^^^^^^^^^^^^^^^^^^
1395
1396If you're not careful, it's easy to define options with conflicting option
1397strings::
1398
1399 parser.add_option("-n", "--dry-run", ...)
1400 [...]
1401 parser.add_option("-n", "--noisy", ...)
1402
1403(This is particularly true if you've defined your own OptionParser subclass with
1404some standard options.)
1405
1406Every time you add an option, :mod:`optparse` checks for conflicts with existing
1407options. If it finds any, it invokes the current conflict-handling mechanism.
1408You can set the conflict-handling mechanism either in the constructor::
1409
1410 parser = OptionParser(..., conflict_handler=handler)
1411
1412or with a separate call::
1413
1414 parser.set_conflict_handler(handler)
1415
1416The available conflict handlers are:
1417
Georg Brandlb926ebb2009-09-17 17:14:04 +00001418 ``"error"`` (default)
1419 assume option conflicts are a programming error and raise
1420 :exc:`OptionConflictError`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001421
Georg Brandlb926ebb2009-09-17 17:14:04 +00001422 ``"resolve"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001423 resolve option conflicts intelligently (see below)
1424
1425
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001426As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl8ec7f652007-08-15 14:28:01 +00001427intelligently and add conflicting options to it::
1428
1429 parser = OptionParser(conflict_handler="resolve")
1430 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1431 parser.add_option("-n", "--noisy", ..., help="be noisy")
1432
1433At this point, :mod:`optparse` detects that a previously-added option is already
Éric Araujoa8132ec2010-12-16 03:53:53 +00001434using the ``-n`` option string. Since ``conflict_handler`` is ``"resolve"``,
1435it resolves the situation by removing ``-n`` from the earlier option's list of
1436option strings. Now ``--dry-run`` is the only way for the user to activate
Georg Brandl8ec7f652007-08-15 14:28:01 +00001437that option. If the user asks for help, the help message will reflect that::
1438
Georg Brandl28046022011-02-25 11:01:04 +00001439 Options:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001440 --dry-run do no harm
1441 [...]
1442 -n, --noisy be noisy
1443
1444It's possible to whittle away the option strings for a previously-added option
1445until there are none left, and the user has no way of invoking that option from
1446the command-line. In that case, :mod:`optparse` removes that option completely,
1447so it doesn't show up in help text or anywhere else. Carrying on with our
1448existing OptionParser::
1449
1450 parser.add_option("--dry-run", ..., help="new dry-run option")
1451
Éric Araujoa8132ec2010-12-16 03:53:53 +00001452At this point, the original ``-n``/``--dry-run`` option is no longer
Georg Brandl8ec7f652007-08-15 14:28:01 +00001453accessible, so :mod:`optparse` removes it, leaving this help text::
1454
Georg Brandl28046022011-02-25 11:01:04 +00001455 Options:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001456 [...]
1457 -n, --noisy be noisy
1458 --dry-run new dry-run option
1459
1460
1461.. _optparse-cleanup:
1462
1463Cleanup
1464^^^^^^^
1465
1466OptionParser instances have several cyclic references. This should not be a
1467problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandlb926ebb2009-09-17 17:14:04 +00001468references explicitly by calling :meth:`~OptionParser.destroy` on your
1469OptionParser once you are done with it. This is particularly useful in
1470long-running applications where large object graphs are reachable from your
1471OptionParser.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001472
1473
1474.. _optparse-other-methods:
1475
1476Other methods
1477^^^^^^^^^^^^^
1478
1479OptionParser supports several other public methods:
1480
Georg Brandlb926ebb2009-09-17 17:14:04 +00001481.. method:: OptionParser.set_usage(usage)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001482
Georg Brandlb926ebb2009-09-17 17:14:04 +00001483 Set the usage string according to the rules described above for the ``usage``
1484 constructor keyword argument. Passing ``None`` sets the default usage
1485 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001486
Ezio Melottib9c3ed42010-01-04 21:43:02 +00001487.. method:: OptionParser.print_usage(file=None)
1488
1489 Print the usage message for the current program (``self.usage``) to *file*
Éric Araujoa8132ec2010-12-16 03:53:53 +00001490 (default stdout). Any occurrence of the string ``%prog`` in ``self.usage``
Ezio Melottib9c3ed42010-01-04 21:43:02 +00001491 is replaced with the name of the current program. Does nothing if
1492 ``self.usage`` is empty or not defined.
1493
1494.. method:: OptionParser.get_usage()
1495
1496 Same as :meth:`print_usage` but returns the usage string instead of
1497 printing it.
1498
Georg Brandlb926ebb2009-09-17 17:14:04 +00001499.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001500
Georg Brandlb926ebb2009-09-17 17:14:04 +00001501 Set default values for several option destinations at once. Using
1502 :meth:`set_defaults` is the preferred way to set default values for options,
1503 since multiple options can share the same destination. For example, if
1504 several "mode" options all set the same destination, any one of them can set
1505 the default, and the last one wins::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001506
Georg Brandlb926ebb2009-09-17 17:14:04 +00001507 parser.add_option("--advanced", action="store_const",
1508 dest="mode", const="advanced",
1509 default="novice") # overridden below
1510 parser.add_option("--novice", action="store_const",
1511 dest="mode", const="novice",
1512 default="advanced") # overrides above setting
Georg Brandl8ec7f652007-08-15 14:28:01 +00001513
Georg Brandlb926ebb2009-09-17 17:14:04 +00001514 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001515
Georg Brandlb926ebb2009-09-17 17:14:04 +00001516 parser.set_defaults(mode="advanced")
1517 parser.add_option("--advanced", action="store_const",
1518 dest="mode", const="advanced")
1519 parser.add_option("--novice", action="store_const",
1520 dest="mode", const="novice")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001521
Georg Brandl8ec7f652007-08-15 14:28:01 +00001522
1523.. _optparse-option-callbacks:
1524
1525Option Callbacks
1526----------------
1527
1528When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1529needs, you have two choices: extend :mod:`optparse` or define a callback option.
1530Extending :mod:`optparse` is more general, but overkill for a lot of simple
1531cases. Quite often a simple callback is all you need.
1532
1533There are two steps to defining a callback option:
1534
Georg Brandlb926ebb2009-09-17 17:14:04 +00001535* define the option itself using the ``"callback"`` action
Georg Brandl8ec7f652007-08-15 14:28:01 +00001536
1537* write the callback; this is a function (or method) that takes at least four
1538 arguments, as described below
1539
1540
1541.. _optparse-defining-callback-option:
1542
1543Defining a callback option
1544^^^^^^^^^^^^^^^^^^^^^^^^^^
1545
1546As always, the easiest way to define a callback option is by using the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001547:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1548only option attribute you must specify is ``callback``, the function to call::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001549
1550 parser.add_option("-c", action="callback", callback=my_callback)
1551
1552``callback`` is a function (or other callable object), so you must have already
1553defined ``my_callback()`` when you create this callback option. In this simple
Éric Araujoa8132ec2010-12-16 03:53:53 +00001554case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001555which usually means that the option takes no arguments---the mere presence of
Éric Araujoa8132ec2010-12-16 03:53:53 +00001556``-c`` on the command-line is all it needs to know. In some
Georg Brandl8ec7f652007-08-15 14:28:01 +00001557circumstances, though, you might want your callback to consume an arbitrary
1558number of command-line arguments. This is where writing callbacks gets tricky;
1559it's covered later in this section.
1560
1561:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandlb926ebb2009-09-17 17:14:04 +00001562will only pass additional arguments if you specify them via
1563:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1564minimal callback function signature is::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001565
1566 def my_callback(option, opt, value, parser):
1567
1568The four arguments to a callback are described below.
1569
1570There are several other option attributes that you can supply when you define a
1571callback option:
1572
Georg Brandlb926ebb2009-09-17 17:14:04 +00001573:attr:`~Option.type`
1574 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1575 instructs :mod:`optparse` to consume one argument and convert it to
1576 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1577 though, :mod:`optparse` passes it to your callback function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001578
Georg Brandlb926ebb2009-09-17 17:14:04 +00001579:attr:`~Option.nargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001580 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandlb926ebb2009-09-17 17:14:04 +00001581 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1582 :attr:`~Option.type`. It then passes a tuple of converted values to your
1583 callback.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001584
Georg Brandlb926ebb2009-09-17 17:14:04 +00001585:attr:`~Option.callback_args`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001586 a tuple of extra positional arguments to pass to the callback
1587
Georg Brandlb926ebb2009-09-17 17:14:04 +00001588:attr:`~Option.callback_kwargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001589 a dictionary of extra keyword arguments to pass to the callback
1590
1591
1592.. _optparse-how-callbacks-called:
1593
1594How callbacks are called
1595^^^^^^^^^^^^^^^^^^^^^^^^
1596
1597All callbacks are called as follows::
1598
1599 func(option, opt_str, value, parser, *args, **kwargs)
1600
1601where
1602
1603``option``
1604 is the Option instance that's calling the callback
1605
1606``opt_str``
1607 is the option string seen on the command-line that's triggering the callback.
Georg Brandlb926ebb2009-09-17 17:14:04 +00001608 (If an abbreviated long option was used, ``opt_str`` will be the full,
Éric Araujoa8132ec2010-12-16 03:53:53 +00001609 canonical option string---e.g. if the user puts ``--foo`` on the
1610 command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
Georg Brandlb926ebb2009-09-17 17:14:04 +00001611 ``"--foobar"``.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001612
1613``value``
1614 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandlb926ebb2009-09-17 17:14:04 +00001615 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1616 the type implied by the option's type. If :attr:`~Option.type` for this option is
1617 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001618 > 1, ``value`` will be a tuple of values of the appropriate type.
1619
1620``parser``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001621 is the OptionParser instance driving the whole thing, mainly useful because
1622 you can access some other interesting data through its instance attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001623
1624 ``parser.largs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001625 the current list of leftover arguments, ie. arguments that have been
1626 consumed but are neither options nor option arguments. Feel free to modify
1627 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1628 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001629
1630 ``parser.rargs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001631 the current list of remaining arguments, ie. with ``opt_str`` and
1632 ``value`` (if applicable) removed, and only the arguments following them
1633 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1634 arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001635
1636 ``parser.values``
1637 the object where option values are by default stored (an instance of
Georg Brandlb926ebb2009-09-17 17:14:04 +00001638 optparse.OptionValues). This lets callbacks use the same mechanism as the
1639 rest of :mod:`optparse` for storing option values; you don't need to mess
1640 around with globals or closures. You can also access or modify the
1641 value(s) of any options already encountered on the command-line.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001642
1643``args``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001644 is a tuple of arbitrary positional arguments supplied via the
1645 :attr:`~Option.callback_args` option attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001646
1647``kwargs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001648 is a dictionary of arbitrary keyword arguments supplied via
1649 :attr:`~Option.callback_kwargs`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001650
1651
1652.. _optparse-raising-errors-in-callback:
1653
1654Raising errors in a callback
1655^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1656
Georg Brandlb926ebb2009-09-17 17:14:04 +00001657The callback function should raise :exc:`OptionValueError` if there are any
1658problems with the option or its argument(s). :mod:`optparse` catches this and
1659terminates the program, printing the error message you supply to stderr. Your
1660message should be clear, concise, accurate, and mention the option at fault.
1661Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001662
1663
1664.. _optparse-callback-example-1:
1665
1666Callback example 1: trivial callback
1667^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1668
1669Here's an example of a callback option that takes no arguments, and simply
1670records that the option was seen::
1671
1672 def record_foo_seen(option, opt_str, value, parser):
Georg Brandl253a29f2009-02-05 11:33:21 +00001673 parser.values.saw_foo = True
Georg Brandl8ec7f652007-08-15 14:28:01 +00001674
1675 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1676
Georg Brandlb926ebb2009-09-17 17:14:04 +00001677Of course, you could do that with the ``"store_true"`` action.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001678
1679
1680.. _optparse-callback-example-2:
1681
1682Callback example 2: check option order
1683^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1684
Éric Araujoa8132ec2010-12-16 03:53:53 +00001685Here's a slightly more interesting example: record the fact that ``-a`` is
1686seen, but blow up if it comes after ``-b`` in the command-line. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001687
1688 def check_order(option, opt_str, value, parser):
1689 if parser.values.b:
1690 raise OptionValueError("can't use -a after -b")
1691 parser.values.a = 1
1692 [...]
1693 parser.add_option("-a", action="callback", callback=check_order)
1694 parser.add_option("-b", action="store_true", dest="b")
1695
1696
1697.. _optparse-callback-example-3:
1698
1699Callback example 3: check option order (generalized)
1700^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1701
1702If you want to re-use this callback for several similar options (set a flag, but
Éric Araujoa8132ec2010-12-16 03:53:53 +00001703blow up if ``-b`` has already been seen), it needs a bit of work: the error
Georg Brandl8ec7f652007-08-15 14:28:01 +00001704message and the flag that it sets must be generalized. ::
1705
1706 def check_order(option, opt_str, value, parser):
1707 if parser.values.b:
1708 raise OptionValueError("can't use %s after -b" % opt_str)
1709 setattr(parser.values, option.dest, 1)
1710 [...]
1711 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1712 parser.add_option("-b", action="store_true", dest="b")
1713 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1714
1715
1716.. _optparse-callback-example-4:
1717
1718Callback example 4: check arbitrary condition
1719^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1720
1721Of course, you could put any condition in there---you're not limited to checking
1722the values of already-defined options. For example, if you have options that
1723should not be called when the moon is full, all you have to do is this::
1724
1725 def check_moon(option, opt_str, value, parser):
1726 if is_moon_full():
1727 raise OptionValueError("%s option invalid when moon is full"
1728 % opt_str)
1729 setattr(parser.values, option.dest, 1)
1730 [...]
1731 parser.add_option("--foo",
1732 action="callback", callback=check_moon, dest="foo")
1733
1734(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1735
1736
1737.. _optparse-callback-example-5:
1738
1739Callback example 5: fixed arguments
1740^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1741
1742Things get slightly more interesting when you define callback options that take
1743a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandlb926ebb2009-09-17 17:14:04 +00001744is similar to defining a ``"store"`` or ``"append"`` option: if you define
1745:attr:`~Option.type`, then the option takes one argument that must be
1746convertible to that type; if you further define :attr:`~Option.nargs`, then the
1747option takes :attr:`~Option.nargs` arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001748
Georg Brandlb926ebb2009-09-17 17:14:04 +00001749Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001750
1751 def store_value(option, opt_str, value, parser):
1752 setattr(parser.values, option.dest, value)
1753 [...]
1754 parser.add_option("--foo",
1755 action="callback", callback=store_value,
1756 type="int", nargs=3, dest="foo")
1757
1758Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1759them to integers for you; all you have to do is store them. (Or whatever;
1760obviously you don't need a callback for this example.)
1761
1762
1763.. _optparse-callback-example-6:
1764
1765Callback example 6: variable arguments
1766^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1767
1768Things get hairy when you want an option to take a variable number of arguments.
1769For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1770built-in capabilities for it. And you have to deal with certain intricacies of
1771conventional Unix command-line parsing that :mod:`optparse` normally handles for
1772you. In particular, callbacks should implement the conventional rules for bare
Éric Araujoa8132ec2010-12-16 03:53:53 +00001773``--`` and ``-`` arguments:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001774
Éric Araujoa8132ec2010-12-16 03:53:53 +00001775* either ``--`` or ``-`` can be option arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +00001776
Éric Araujoa8132ec2010-12-16 03:53:53 +00001777* bare ``--`` (if not the argument to some option): halt command-line
1778 processing and discard the ``--``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001779
Éric Araujoa8132ec2010-12-16 03:53:53 +00001780* bare ``-`` (if not the argument to some option): halt command-line
1781 processing but keep the ``-`` (append it to ``parser.largs``)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001782
1783If you want an option that takes a variable number of arguments, there are
1784several subtle, tricky issues to worry about. The exact implementation you
1785choose will be based on which trade-offs you're willing to make for your
1786application (which is why :mod:`optparse` doesn't support this sort of thing
1787directly).
1788
1789Nevertheless, here's a stab at a callback for an option with variable
1790arguments::
1791
Georg Brandl60b2e382008-12-15 09:07:39 +00001792 def vararg_callback(option, opt_str, value, parser):
1793 assert value is None
1794 value = []
Georg Brandl8ec7f652007-08-15 14:28:01 +00001795
Georg Brandl60b2e382008-12-15 09:07:39 +00001796 def floatable(str):
1797 try:
1798 float(str)
1799 return True
1800 except ValueError:
1801 return False
Georg Brandl8ec7f652007-08-15 14:28:01 +00001802
Georg Brandl60b2e382008-12-15 09:07:39 +00001803 for arg in parser.rargs:
1804 # stop on --foo like options
1805 if arg[:2] == "--" and len(arg) > 2:
1806 break
1807 # stop on -a, but not on -3 or -3.0
1808 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1809 break
1810 value.append(arg)
1811
1812 del parser.rargs[:len(value)]
Georg Brandl174fbe72009-02-05 10:30:57 +00001813 setattr(parser.values, option.dest, value)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001814
1815 [...]
Andrew M. Kuchling810f8072008-09-06 13:04:02 +00001816 parser.add_option("-c", "--callback", dest="vararg_attr",
Benjamin Petersonc8590942008-04-23 20:38:06 +00001817 action="callback", callback=vararg_callback)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001818
Georg Brandl8ec7f652007-08-15 14:28:01 +00001819
1820.. _optparse-extending-optparse:
1821
1822Extending :mod:`optparse`
1823-------------------------
1824
1825Since the two major controlling factors in how :mod:`optparse` interprets
1826command-line options are the action and type of each option, the most likely
1827direction of extension is to add new actions and new types.
1828
1829
1830.. _optparse-adding-new-types:
1831
1832Adding new types
1833^^^^^^^^^^^^^^^^
1834
1835To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandlb926ebb2009-09-17 17:14:04 +00001836:class:`Option` class. This class has a couple of attributes that define
1837:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001838
Georg Brandlb926ebb2009-09-17 17:14:04 +00001839.. attribute:: Option.TYPES
Georg Brandl8ec7f652007-08-15 14:28:01 +00001840
Georg Brandlb926ebb2009-09-17 17:14:04 +00001841 A tuple of type names; in your subclass, simply define a new tuple
1842 :attr:`TYPES` that builds on the standard one.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001843
Georg Brandlb926ebb2009-09-17 17:14:04 +00001844.. attribute:: Option.TYPE_CHECKER
Georg Brandl8ec7f652007-08-15 14:28:01 +00001845
Georg Brandlb926ebb2009-09-17 17:14:04 +00001846 A dictionary mapping type names to type-checking functions. A type-checking
1847 function has the following signature::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001848
Georg Brandlb926ebb2009-09-17 17:14:04 +00001849 def check_mytype(option, opt, value)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001850
Georg Brandlb926ebb2009-09-17 17:14:04 +00001851 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
Éric Araujoa8132ec2010-12-16 03:53:53 +00001852 (e.g., ``-f``), and ``value`` is the string from the command line that must
Georg Brandlb926ebb2009-09-17 17:14:04 +00001853 be checked and converted to your desired type. ``check_mytype()`` should
1854 return an object of the hypothetical type ``mytype``. The value returned by
1855 a type-checking function will wind up in the OptionValues instance returned
1856 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1857 ``value`` parameter.
1858
1859 Your type-checking function should raise :exc:`OptionValueError` if it
1860 encounters any problems. :exc:`OptionValueError` takes a single string
1861 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1862 method, which in turn prepends the program name and the string ``"error:"``
1863 and prints everything to stderr before terminating the process.
1864
1865Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl8ec7f652007-08-15 14:28:01 +00001866parse Python-style complex numbers on the command line. (This is even sillier
1867than it used to be, because :mod:`optparse` 1.3 added built-in support for
1868complex numbers, but never mind.)
1869
1870First, the necessary imports::
1871
1872 from copy import copy
1873 from optparse import Option, OptionValueError
1874
1875You need to define your type-checker first, since it's referred to later (in the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001876:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001877
1878 def check_complex(option, opt, value):
1879 try:
1880 return complex(value)
1881 except ValueError:
1882 raise OptionValueError(
1883 "option %s: invalid complex value: %r" % (opt, value))
1884
1885Finally, the Option subclass::
1886
1887 class MyOption (Option):
1888 TYPES = Option.TYPES + ("complex",)
1889 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1890 TYPE_CHECKER["complex"] = check_complex
1891
1892(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandlb926ebb2009-09-17 17:14:04 +00001893up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1894Option class. This being Python, nothing stops you from doing that except good
1895manners and common sense.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001896
1897That's it! Now you can write a script that uses the new option type just like
1898any other :mod:`optparse`\ -based script, except you have to instruct your
1899OptionParser to use MyOption instead of Option::
1900
1901 parser = OptionParser(option_class=MyOption)
1902 parser.add_option("-c", type="complex")
1903
1904Alternately, you can build your own option list and pass it to OptionParser; if
1905you don't use :meth:`add_option` in the above way, you don't need to tell
1906OptionParser which option class to use::
1907
1908 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1909 parser = OptionParser(option_list=option_list)
1910
1911
1912.. _optparse-adding-new-actions:
1913
1914Adding new actions
1915^^^^^^^^^^^^^^^^^^
1916
1917Adding new actions is a bit trickier, because you have to understand that
1918:mod:`optparse` has a couple of classifications for actions:
1919
1920"store" actions
1921 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001922 current OptionValues instance; these options require a :attr:`~Option.dest`
1923 attribute to be supplied to the Option constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001924
1925"typed" actions
Georg Brandlb926ebb2009-09-17 17:14:04 +00001926 actions that take a value from the command line and expect it to be of a
1927 certain type; or rather, a string that can be converted to a certain type.
1928 These options require a :attr:`~Option.type` attribute to the Option
1929 constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001930
Georg Brandlb926ebb2009-09-17 17:14:04 +00001931These are overlapping sets: some default "store" actions are ``"store"``,
1932``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1933actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001934
1935When you add an action, you need to categorize it by listing it in at least one
1936of the following class attributes of Option (all are lists of strings):
1937
Georg Brandlb926ebb2009-09-17 17:14:04 +00001938.. attribute:: Option.ACTIONS
Georg Brandl8ec7f652007-08-15 14:28:01 +00001939
Georg Brandlb926ebb2009-09-17 17:14:04 +00001940 All actions must be listed in ACTIONS.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001941
Georg Brandlb926ebb2009-09-17 17:14:04 +00001942.. attribute:: Option.STORE_ACTIONS
Georg Brandl8ec7f652007-08-15 14:28:01 +00001943
Georg Brandlb926ebb2009-09-17 17:14:04 +00001944 "store" actions are additionally listed here.
1945
1946.. attribute:: Option.TYPED_ACTIONS
1947
1948 "typed" actions are additionally listed here.
1949
1950.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1951
1952 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl8ec7f652007-08-15 14:28:01 +00001953 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00001954 assigns the default type, ``"string"``, to options with no explicit type
1955 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001956
1957In order to actually implement your new action, you must override Option's
1958:meth:`take_action` method and add a case that recognizes your action.
1959
Georg Brandlb926ebb2009-09-17 17:14:04 +00001960For example, let's add an ``"extend"`` action. This is similar to the standard
1961``"append"`` action, but instead of taking a single value from the command-line
1962and appending it to an existing list, ``"extend"`` will take multiple values in
1963a single comma-delimited string, and extend an existing list with them. That
Éric Araujoa8132ec2010-12-16 03:53:53 +00001964is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
Georg Brandlb926ebb2009-09-17 17:14:04 +00001965line ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001966
1967 --names=foo,bar --names blah --names ding,dong
1968
1969would result in a list ::
1970
1971 ["foo", "bar", "blah", "ding", "dong"]
1972
1973Again we define a subclass of Option::
1974
Ezio Melotti5129ed32010-01-03 09:01:27 +00001975 class MyOption(Option):
Georg Brandl8ec7f652007-08-15 14:28:01 +00001976
1977 ACTIONS = Option.ACTIONS + ("extend",)
1978 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1979 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1980 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1981
1982 def take_action(self, action, dest, opt, value, values, parser):
1983 if action == "extend":
1984 lvalue = value.split(",")
1985 values.ensure_value(dest, []).extend(lvalue)
1986 else:
1987 Option.take_action(
1988 self, action, dest, opt, value, values, parser)
1989
1990Features of note:
1991
Georg Brandlb926ebb2009-09-17 17:14:04 +00001992* ``"extend"`` both expects a value on the command-line and stores that value
1993 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1994 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001995
Georg Brandlb926ebb2009-09-17 17:14:04 +00001996* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1997 ``"extend"`` actions, we put the ``"extend"`` action in
1998 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001999
2000* :meth:`MyOption.take_action` implements just this one new action, and passes
2001 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00002002 actions.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002003
Georg Brandlb926ebb2009-09-17 17:14:04 +00002004* ``values`` is an instance of the optparse_parser.Values class, which provides
2005 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
2006 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00002007
2008 values.ensure_value(attr, value)
2009
2010 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandlb926ebb2009-09-17 17:14:04 +00002011 ensure_value() first sets it to ``value``, and then returns 'value. This is
2012 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
2013 of which accumulate data in a variable and expect that variable to be of a
2014 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl8ec7f652007-08-15 14:28:01 +00002015 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandlb926ebb2009-09-17 17:14:04 +00002016 about setting a default value for the option destinations in question; they
2017 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl8ec7f652007-08-15 14:28:01 +00002018 getting it right when it's needed.