blob: 37226c3846589e22a571286444d1ccc046c48f64 [file] [log] [blame]
Steven Bethard6d265692010-03-02 09:22:57 +00001:mod:`optparse` --- Parser for command line options
2===================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: optparse
Steven Bethard6d265692010-03-02 09:22:57 +00005 :synopsis: Command-line option parsing library.
Steven Bethard59710962010-05-24 03:21:08 +00006 :deprecated:
7
8.. 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
Georg Brandl116aa622007-08-15 14:28:22 +000012.. moduleauthor:: Greg Ward <gward@python.net>
Georg Brandl116aa622007-08-15 14:28:22 +000013.. sectionauthor:: Greg Ward <gward@python.net>
14
15
Georg Brandl15a515f2009-09-17 22:11:49 +000016:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
17command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
18more declarative style of command-line parsing: you create an instance of
19:class:`OptionParser`, populate it with options, and parse the command
20line. :mod:`optparse` allows users to specify options in the conventional
21GNU/POSIX syntax, and additionally generates usage and help messages for you.
Georg Brandl116aa622007-08-15 14:28:22 +000022
Georg Brandl15a515f2009-09-17 22:11:49 +000023Here's an example of using :mod:`optparse` in a simple script::
Georg Brandl116aa622007-08-15 14:28:22 +000024
25 from optparse import OptionParser
26 [...]
27 parser = OptionParser()
28 parser.add_option("-f", "--file", dest="filename",
29 help="write report to FILE", metavar="FILE")
30 parser.add_option("-q", "--quiet",
31 action="store_false", dest="verbose", default=True,
32 help="don't print status messages to stdout")
33
34 (options, args) = parser.parse_args()
35
36With these few lines of code, users of your script can now do the "usual thing"
37on the command-line, for example::
38
39 <yourscript> --file=outfile -q
40
Georg Brandl15a515f2009-09-17 22:11:49 +000041As it parses the command line, :mod:`optparse` sets attributes of the
42``options`` object returned by :meth:`parse_args` based on user-supplied
43command-line values. When :meth:`parse_args` returns from parsing this command
44line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
45``False``. :mod:`optparse` supports both long and short options, allows short
Georg Brandl116aa622007-08-15 14:28:22 +000046options to be merged together, and allows options to be associated with their
47arguments in a variety of ways. Thus, the following command lines are all
48equivalent to the above example::
49
50 <yourscript> -f outfile --quiet
51 <yourscript> --quiet --file outfile
52 <yourscript> -q -foutfile
53 <yourscript> -qfoutfile
54
55Additionally, users can run one of ::
56
57 <yourscript> -h
58 <yourscript> --help
59
Ezio Melotti383ae952010-01-03 09:06:02 +000060and :mod:`optparse` will print out a brief summary of your script's options:
61
62.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +000063
64 usage: <yourscript> [options]
65
66 options:
67 -h, --help show this help message and exit
68 -f FILE, --file=FILE write report to FILE
69 -q, --quiet don't print status messages to stdout
70
71where the value of *yourscript* is determined at runtime (normally from
72``sys.argv[0]``).
73
Georg Brandl116aa622007-08-15 14:28:22 +000074
75.. _optparse-background:
76
77Background
78----------
79
80:mod:`optparse` was explicitly designed to encourage the creation of programs
81with straightforward, conventional command-line interfaces. To that end, it
82supports only the most common command-line syntax and semantics conventionally
83used under Unix. If you are unfamiliar with these conventions, read this
84section to acquaint yourself with them.
85
86
87.. _optparse-terminology:
88
89Terminology
90^^^^^^^^^^^
91
92argument
Georg Brandl15a515f2009-09-17 22:11:49 +000093 a string entered on the command-line, and passed by the shell to ``execl()``
94 or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
95 (``sys.argv[0]`` is the name of the program being executed). Unix shells
96 also use the term "word".
Georg Brandl116aa622007-08-15 14:28:22 +000097
98 It is occasionally desirable to substitute an argument list other than
99 ``sys.argv[1:]``, so you should read "argument" as "an element of
100 ``sys.argv[1:]``, or of some other list provided as a substitute for
101 ``sys.argv[1:]``".
102
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000103option
Georg Brandl15a515f2009-09-17 22:11:49 +0000104 an argument used to supply extra information to guide or customize the
105 execution of a program. There are many different syntaxes for options; the
106 traditional Unix syntax is a hyphen ("-") followed by a single letter,
107 e.g. ``"-x"`` or ``"-F"``. Also, traditional Unix syntax allows multiple
108 options to be merged into a single argument, e.g. ``"-x -F"`` is equivalent
109 to ``"-xF"``. The GNU project introduced ``"--"`` followed by a series of
110 hyphen-separated words, e.g. ``"--file"`` or ``"--dry-run"``. These are the
111 only two option syntaxes provided by :mod:`optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113 Some other option syntaxes that the world has seen include:
114
115 * a hyphen followed by a few letters, e.g. ``"-pf"`` (this is *not* the same
116 as multiple options merged into a single argument)
117
118 * a hyphen followed by a whole word, e.g. ``"-file"`` (this is technically
119 equivalent to the previous syntax, but they aren't usually seen in the same
120 program)
121
122 * a plus sign followed by a single letter, or a few letters, or a word, e.g.
123 ``"+f"``, ``"+rgb"``
124
125 * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
126 ``"/file"``
127
Georg Brandl15a515f2009-09-17 22:11:49 +0000128 These option syntaxes are not supported by :mod:`optparse`, and they never
129 will be. This is deliberate: the first three are non-standard on any
130 environment, and the last only makes sense if you're exclusively targeting
131 VMS, MS-DOS, and/or Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133option argument
Georg Brandl15a515f2009-09-17 22:11:49 +0000134 an argument that follows an option, is closely associated with that option,
135 and is consumed from the argument list when that option is. With
136 :mod:`optparse`, option arguments may either be in a separate argument from
Ezio Melotti383ae952010-01-03 09:06:02 +0000137 their option:
138
139 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141 -f foo
142 --file foo
143
Ezio Melotti383ae952010-01-03 09:06:02 +0000144 or included in the same argument:
145
146 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148 -ffoo
149 --file=foo
150
Georg Brandl15a515f2009-09-17 22:11:49 +0000151 Typically, a given option either takes an argument or it doesn't. Lots of
152 people want an "optional option arguments" feature, meaning that some options
153 will take an argument if they see it, and won't if they don't. This is
154 somewhat controversial, because it makes parsing ambiguous: if ``"-a"`` takes
155 an optional argument and ``"-b"`` is another option entirely, how do we
156 interpret ``"-ab"``? Because of this ambiguity, :mod:`optparse` does not
157 support this feature.
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159positional argument
160 something leftover in the argument list after options have been parsed, i.e.
Georg Brandl15a515f2009-09-17 22:11:49 +0000161 after options and their arguments have been parsed and removed from the
162 argument list.
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164required option
165 an option that must be supplied on the command-line; note that the phrase
166 "required option" is self-contradictory in English. :mod:`optparse` doesn't
Georg Brandl15a515f2009-09-17 22:11:49 +0000167 prevent you from implementing required options, but doesn't give you much
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000168 help at it either.
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170For example, consider this hypothetical command-line::
171
172 prog -v --report /tmp/report.txt foo bar
173
174``"-v"`` and ``"--report"`` are both options. Assuming that :option:`--report`
175takes one argument, ``"/tmp/report.txt"`` is an option argument. ``"foo"`` and
176``"bar"`` are positional arguments.
177
178
179.. _optparse-what-options-for:
180
181What are options for?
182^^^^^^^^^^^^^^^^^^^^^
183
184Options are used to provide extra information to tune or customize the execution
185of a program. In case it wasn't clear, options are usually *optional*. A
186program should be able to run just fine with no options whatsoever. (Pick a
187random program from the Unix or GNU toolsets. Can it run without any options at
188all and still make sense? The main exceptions are ``find``, ``tar``, and
189``dd``\ ---all of which are mutant oddballs that have been rightly criticized
190for their non-standard syntax and confusing interfaces.)
191
192Lots of people want their programs to have "required options". Think about it.
193If it's required, then it's *not optional*! If there is a piece of information
194that your program absolutely requires in order to run successfully, that's what
195positional arguments are for.
196
197As an example of good command-line interface design, consider the humble ``cp``
198utility, for copying files. It doesn't make much sense to try to copy files
199without supplying a destination and at least one source. Hence, ``cp`` fails if
200you run it with no arguments. However, it has a flexible, useful syntax that
201does not require any options at all::
202
203 cp SOURCE DEST
204 cp SOURCE ... DEST-DIR
205
206You can get pretty far with just that. Most ``cp`` implementations provide a
207bunch of options to tweak exactly how the files are copied: you can preserve
208mode and modification time, avoid following symlinks, ask before clobbering
209existing files, etc. But none of this distracts from the core mission of
210``cp``, which is to copy either one file to another, or several files to another
211directory.
212
213
214.. _optparse-what-positional-arguments-for:
215
216What are positional arguments for?
217^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
218
219Positional arguments are for those pieces of information that your program
220absolutely, positively requires to run.
221
222A good user interface should have as few absolute requirements as possible. If
223your program requires 17 distinct pieces of information in order to run
224successfully, it doesn't much matter *how* you get that information from the
225user---most people will give up and walk away before they successfully run the
226program. This applies whether the user interface is a command-line, a
227configuration file, or a GUI: if you make that many demands on your users, most
228of them will simply give up.
229
230In short, try to minimize the amount of information that users are absolutely
231required to supply---use sensible defaults whenever possible. Of course, you
232also want to make your programs reasonably flexible. That's what options are
233for. Again, it doesn't matter if they are entries in a config file, widgets in
234the "Preferences" dialog of a GUI, or command-line options---the more options
235you implement, the more flexible your program is, and the more complicated its
236implementation becomes. Too much flexibility has drawbacks as well, of course;
237too many options can overwhelm users and make your code much harder to maintain.
238
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240.. _optparse-tutorial:
241
242Tutorial
243--------
244
245While :mod:`optparse` is quite flexible and powerful, it's also straightforward
246to use in most cases. This section covers the code patterns that are common to
247any :mod:`optparse`\ -based program.
248
249First, you need to import the OptionParser class; then, early in the main
250program, create an OptionParser instance::
251
252 from optparse import OptionParser
253 [...]
254 parser = OptionParser()
255
256Then you can start defining options. The basic syntax is::
257
258 parser.add_option(opt_str, ...,
259 attr=value, ...)
260
261Each option has one or more option strings, such as ``"-f"`` or ``"--file"``,
262and several option attributes that tell :mod:`optparse` what to expect and what
263to do when it encounters that option on the command line.
264
265Typically, each option will have one short option string and one long option
266string, e.g.::
267
268 parser.add_option("-f", "--file", ...)
269
270You're free to define as many short option strings and as many long option
271strings as you like (including zero), as long as there is at least one option
272string overall.
273
274The option strings passed to :meth:`add_option` are effectively labels for the
275option defined by that call. For brevity, we will frequently refer to
276*encountering an option* on the command line; in reality, :mod:`optparse`
277encounters *option strings* and looks up options from them.
278
279Once all of your options are defined, instruct :mod:`optparse` to parse your
280program's command line::
281
282 (options, args) = parser.parse_args()
283
284(If you like, you can pass a custom argument list to :meth:`parse_args`, but
285that's rarely necessary: by default it uses ``sys.argv[1:]``.)
286
287:meth:`parse_args` returns two values:
288
289* ``options``, an object containing values for all of your options---e.g. if
290 ``"--file"`` takes a single string argument, then ``options.file`` will be the
291 filename supplied by the user, or ``None`` if the user did not supply that
292 option
293
294* ``args``, the list of positional arguments leftover after parsing options
295
296This tutorial section only covers the four most important option attributes:
Georg Brandl15a515f2009-09-17 22:11:49 +0000297:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
298(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
299most fundamental.
Georg Brandl116aa622007-08-15 14:28:22 +0000300
301
302.. _optparse-understanding-option-actions:
303
304Understanding option actions
305^^^^^^^^^^^^^^^^^^^^^^^^^^^^
306
307Actions tell :mod:`optparse` what to do when it encounters an option on the
308command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
309adding new actions is an advanced topic covered in section
Georg Brandl15a515f2009-09-17 22:11:49 +0000310:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
311a value in some variable---for example, take a string from the command line and
312store it in an attribute of ``options``.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314If you don't specify an option action, :mod:`optparse` defaults to ``store``.
315
316
317.. _optparse-store-action:
318
319The store action
320^^^^^^^^^^^^^^^^
321
322The most common option action is ``store``, which tells :mod:`optparse` to take
323the next argument (or the remainder of the current argument), ensure that it is
324of the correct type, and store it to your chosen destination.
325
326For example::
327
328 parser.add_option("-f", "--file",
329 action="store", type="string", dest="filename")
330
331Now let's make up a fake command line and ask :mod:`optparse` to parse it::
332
333 args = ["-f", "foo.txt"]
334 (options, args) = parser.parse_args(args)
335
336When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
337argument, ``"foo.txt"``, and stores it in ``options.filename``. So, after this
338call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
339
340Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
341Here's an option that expects an integer argument::
342
343 parser.add_option("-n", type="int", dest="num")
344
345Note that this option has no long option string, which is perfectly acceptable.
346Also, there's no explicit action, since the default is ``store``.
347
348Let's parse another fake command-line. This time, we'll jam the option argument
349right up against the option: since ``"-n42"`` (one argument) is equivalent to
Georg Brandl15a515f2009-09-17 22:11:49 +0000350``"-n 42"`` (two arguments), the code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352 (options, args) = parser.parse_args(["-n42"])
Georg Brandl6911e3c2007-09-04 07:15:32 +0000353 print(options.num)
Georg Brandl116aa622007-08-15 14:28:22 +0000354
355will print ``"42"``.
356
357If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
358the fact that the default action is ``store``, that means our first example can
359be a lot shorter::
360
361 parser.add_option("-f", "--file", dest="filename")
362
363If you don't supply a destination, :mod:`optparse` figures out a sensible
364default from the option strings: if the first long option string is
365``"--foo-bar"``, then the default destination is ``foo_bar``. If there are no
366long option strings, :mod:`optparse` looks at the first short option string: the
367default destination for ``"-f"`` is ``f``.
368
Georg Brandl5c106642007-11-29 17:41:05 +0000369:mod:`optparse` also includes the built-in ``complex`` type. Adding
Georg Brandl116aa622007-08-15 14:28:22 +0000370types is covered in section :ref:`optparse-extending-optparse`.
371
372
373.. _optparse-handling-boolean-options:
374
375Handling boolean (flag) options
376^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
377
378Flag options---set a variable to true or false when a particular option is seen
379---are quite common. :mod:`optparse` supports them with two separate actions,
380``store_true`` and ``store_false``. For example, you might have a ``verbose``
381flag that is turned on with ``"-v"`` and off with ``"-q"``::
382
383 parser.add_option("-v", action="store_true", dest="verbose")
384 parser.add_option("-q", action="store_false", dest="verbose")
385
386Here we have two different options with the same destination, which is perfectly
387OK. (It just means you have to be a bit careful when setting default values---
388see below.)
389
390When :mod:`optparse` encounters ``"-v"`` on the command line, it sets
391``options.verbose`` to ``True``; when it encounters ``"-q"``,
392``options.verbose`` is set to ``False``.
393
394
395.. _optparse-other-actions:
396
397Other actions
398^^^^^^^^^^^^^
399
400Some other actions supported by :mod:`optparse` are:
401
Georg Brandl15a515f2009-09-17 22:11:49 +0000402``"store_const"``
Georg Brandl116aa622007-08-15 14:28:22 +0000403 store a constant value
404
Georg Brandl15a515f2009-09-17 22:11:49 +0000405``"append"``
Georg Brandl116aa622007-08-15 14:28:22 +0000406 append this option's argument to a list
407
Georg Brandl15a515f2009-09-17 22:11:49 +0000408``"count"``
Georg Brandl116aa622007-08-15 14:28:22 +0000409 increment a counter by one
410
Georg Brandl15a515f2009-09-17 22:11:49 +0000411``"callback"``
Georg Brandl116aa622007-08-15 14:28:22 +0000412 call a specified function
413
414These are covered in section :ref:`optparse-reference-guide`, Reference Guide
415and section :ref:`optparse-option-callbacks`.
416
417
418.. _optparse-default-values:
419
420Default values
421^^^^^^^^^^^^^^
422
423All of the above examples involve setting some variable (the "destination") when
424certain command-line options are seen. What happens if those options are never
425seen? Since we didn't supply any defaults, they are all set to ``None``. This
426is usually fine, but sometimes you want more control. :mod:`optparse` lets you
427supply a default value for each destination, which is assigned before the
428command line is parsed.
429
430First, consider the verbose/quiet example. If we want :mod:`optparse` to set
431``verbose`` to ``True`` unless ``"-q"`` is seen, then we can do this::
432
433 parser.add_option("-v", action="store_true", dest="verbose", default=True)
434 parser.add_option("-q", action="store_false", dest="verbose")
435
436Since default values apply to the *destination* rather than to any particular
437option, and these two options happen to have the same destination, this is
438exactly equivalent::
439
440 parser.add_option("-v", action="store_true", dest="verbose")
441 parser.add_option("-q", action="store_false", dest="verbose", default=True)
442
443Consider this::
444
445 parser.add_option("-v", action="store_true", dest="verbose", default=False)
446 parser.add_option("-q", action="store_false", dest="verbose", default=True)
447
448Again, the default value for ``verbose`` will be ``True``: the last default
449value supplied for any particular destination is the one that counts.
450
451A clearer way to specify default values is the :meth:`set_defaults` method of
452OptionParser, which you can call at any time before calling :meth:`parse_args`::
453
454 parser.set_defaults(verbose=True)
455 parser.add_option(...)
456 (options, args) = parser.parse_args()
457
458As before, the last value specified for a given option destination is the one
459that counts. For clarity, try to use one method or the other of setting default
460values, not both.
461
462
463.. _optparse-generating-help:
464
465Generating help
466^^^^^^^^^^^^^^^
467
468:mod:`optparse`'s ability to generate help and usage text automatically is
469useful for creating user-friendly command-line interfaces. All you have to do
Georg Brandl15a515f2009-09-17 22:11:49 +0000470is supply a :attr:`~Option.help` value for each option, and optionally a short
471usage message for your whole program. Here's an OptionParser populated with
Georg Brandl116aa622007-08-15 14:28:22 +0000472user-friendly (documented) options::
473
474 usage = "usage: %prog [options] arg1 arg2"
475 parser = OptionParser(usage=usage)
476 parser.add_option("-v", "--verbose",
477 action="store_true", dest="verbose", default=True,
478 help="make lots of noise [default]")
479 parser.add_option("-q", "--quiet",
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000480 action="store_false", dest="verbose",
Georg Brandl116aa622007-08-15 14:28:22 +0000481 help="be vewwy quiet (I'm hunting wabbits)")
482 parser.add_option("-f", "--filename",
Georg Brandlee8783d2009-09-16 16:00:31 +0000483 metavar="FILE", help="write output to FILE")
Georg Brandl116aa622007-08-15 14:28:22 +0000484 parser.add_option("-m", "--mode",
485 default="intermediate",
486 help="interaction mode: novice, intermediate, "
487 "or expert [default: %default]")
488
489If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
490command-line, or if you just call :meth:`parser.print_help`, it prints the
Ezio Melotti383ae952010-01-03 09:06:02 +0000491following to standard output:
492
493.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495 usage: <yourscript> [options] arg1 arg2
496
497 options:
498 -h, --help show this help message and exit
499 -v, --verbose make lots of noise [default]
500 -q, --quiet be vewwy quiet (I'm hunting wabbits)
501 -f FILE, --filename=FILE
502 write output to FILE
503 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
504 expert [default: intermediate]
505
506(If the help output is triggered by a help option, :mod:`optparse` exits after
507printing the help text.)
508
509There's a lot going on here to help :mod:`optparse` generate the best possible
510help message:
511
512* the script defines its own usage message::
513
514 usage = "usage: %prog [options] arg1 arg2"
515
516 :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
Georg Brandl15a515f2009-09-17 22:11:49 +0000517 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
518 is then printed before the detailed option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000519
520 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandl15a515f2009-09-17 22:11:49 +0000521 default: ``"usage: %prog [options]"``, which is fine if your script doesn't
522 take any positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524* every option defines a help string, and doesn't worry about line-wrapping---
525 :mod:`optparse` takes care of wrapping lines and making the help output look
526 good.
527
528* options that take a value indicate this fact in their automatically-generated
529 help message, e.g. for the "mode" option::
530
531 -m MODE, --mode=MODE
532
533 Here, "MODE" is called the meta-variable: it stands for the argument that the
534 user is expected to supply to :option:`-m`/:option:`--mode`. By default,
535 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandl15a515f2009-09-17 22:11:49 +0000536 that for the meta-variable. Sometimes, that's not what you want---for
537 example, the :option:`--filename` option explicitly sets ``metavar="FILE"``,
538 resulting in this automatically-generated option description::
Georg Brandl116aa622007-08-15 14:28:22 +0000539
540 -f FILE, --filename=FILE
541
Georg Brandl15a515f2009-09-17 22:11:49 +0000542 This is important for more than just saving space, though: the manually
543 written help text uses the meta-variable "FILE" to clue the user in that
544 there's a connection between the semi-formal syntax "-f FILE" and the informal
545 semantic description "write output to FILE". This is a simple but effective
546 way to make your help text a lot clearer and more useful for end users.
Georg Brandl116aa622007-08-15 14:28:22 +0000547
548* options that have a default value can include ``%default`` in the help
549 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
550 default value. If an option has no default value (or the default value is
551 ``None``), ``%default`` expands to ``none``.
552
Georg Brandl15a515f2009-09-17 22:11:49 +0000553When dealing with many options, it is convenient to group these options for
554better help output. An :class:`OptionParser` can contain several option groups,
555each of which can contain several options.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000556
Georg Brandl15a515f2009-09-17 22:11:49 +0000557Continuing with the parser defined above, adding an :class:`OptionGroup` to a
558parser is easy::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000559
560 group = OptionGroup(parser, "Dangerous Options",
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000561 "Caution: use these options at your own risk. "
562 "It is believed that some of them bite.")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000563 group.add_option("-g", action="store_true", help="Group option.")
564 parser.add_option_group(group)
565
Ezio Melotti383ae952010-01-03 09:06:02 +0000566This would result in the following help output:
567
568.. code-block:: text
Christian Heimesfdab48e2008-01-20 09:06:41 +0000569
570 usage: [options] arg1 arg2
571
572 options:
573 -h, --help show this help message and exit
574 -v, --verbose make lots of noise [default]
575 -q, --quiet be vewwy quiet (I'm hunting wabbits)
576 -fFILE, --file=FILE write output to FILE
577 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000578 [default], 'expert'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000579
580 Dangerous Options:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000581 Caution: use of these options is at your own risk. It is believed that
582 some of them bite.
583 -g Group option.
Georg Brandl116aa622007-08-15 14:28:22 +0000584
585.. _optparse-printing-version-string:
586
587Printing a version string
588^^^^^^^^^^^^^^^^^^^^^^^^^
589
590Similar to the brief usage string, :mod:`optparse` can also print a version
591string for your program. You have to supply the string as the ``version``
592argument to OptionParser::
593
594 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
595
596``"%prog"`` is expanded just like it is in ``usage``. Apart from that,
597``version`` can contain anything you like. When you supply it, :mod:`optparse`
598automatically adds a ``"--version"`` option to your parser. If it encounters
599this option on the command line, it expands your ``version`` string (by
600replacing ``"%prog"``), prints it to stdout, and exits.
601
602For example, if your script is called ``/usr/bin/foo``::
603
604 $ /usr/bin/foo --version
605 foo 1.0
606
Ezio Melotti1ce43192010-01-04 21:53:17 +0000607The following two methods can be used to print and get the ``version`` string:
608
609.. method:: OptionParser.print_version(file=None)
610
611 Print the version message for the current program (``self.version``) to
612 *file* (default stdout). As with :meth:`print_usage`, any occurrence
613 of ``"%prog"`` in ``self.version`` is replaced with the name of the current
614 program. Does nothing if ``self.version`` is empty or undefined.
615
616.. method:: OptionParser.get_version()
617
618 Same as :meth:`print_version` but returns the version string instead of
619 printing it.
620
Georg Brandl116aa622007-08-15 14:28:22 +0000621
622.. _optparse-how-optparse-handles-errors:
623
624How :mod:`optparse` handles errors
625^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
626
627There are two broad classes of errors that :mod:`optparse` has to worry about:
628programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandl15a515f2009-09-17 22:11:49 +0000629calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
630option attributes, missing option attributes, etc. These are dealt with in the
631usual way: raise an exception (either :exc:`optparse.OptionError` or
632:exc:`TypeError`) and let the program crash.
Georg Brandl116aa622007-08-15 14:28:22 +0000633
634Handling user errors is much more important, since they are guaranteed to happen
635no matter how stable your code is. :mod:`optparse` can automatically detect
636some user errors, such as bad option arguments (passing ``"-n 4x"`` where
637:option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
638of the command line, where :option:`-n` takes an argument of any type). Also,
Georg Brandl15a515f2009-09-17 22:11:49 +0000639you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl116aa622007-08-15 14:28:22 +0000640condition::
641
642 (options, args) = parser.parse_args()
643 [...]
644 if options.a and options.b:
645 parser.error("options -a and -b are mutually exclusive")
646
647In either case, :mod:`optparse` handles the error the same way: it prints the
648program's usage message and an error message to standard error and exits with
649error status 2.
650
651Consider the first example above, where the user passes ``"4x"`` to an option
652that takes an integer::
653
654 $ /usr/bin/foo -n 4x
655 usage: foo [options]
656
657 foo: error: option -n: invalid integer value: '4x'
658
659Or, where the user fails to pass a value at all::
660
661 $ /usr/bin/foo -n
662 usage: foo [options]
663
664 foo: error: -n option requires an argument
665
666:mod:`optparse`\ -generated error messages take care always to mention the
667option involved in the error; be sure to do the same when calling
Georg Brandl15a515f2009-09-17 22:11:49 +0000668:func:`OptionParser.error` from your application code.
Georg Brandl116aa622007-08-15 14:28:22 +0000669
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000670If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000671you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
672and/or :meth:`~OptionParser.error` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000673
674
675.. _optparse-putting-it-all-together:
676
677Putting it all together
678^^^^^^^^^^^^^^^^^^^^^^^
679
680Here's what :mod:`optparse`\ -based scripts usually look like::
681
682 from optparse import OptionParser
683 [...]
684 def main():
685 usage = "usage: %prog [options] arg"
686 parser = OptionParser(usage)
687 parser.add_option("-f", "--file", dest="filename",
688 help="read data from FILENAME")
689 parser.add_option("-v", "--verbose",
690 action="store_true", dest="verbose")
691 parser.add_option("-q", "--quiet",
692 action="store_false", dest="verbose")
693 [...]
694 (options, args) = parser.parse_args()
695 if len(args) != 1:
696 parser.error("incorrect number of arguments")
697 if options.verbose:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000698 print("reading %s..." % options.filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000699 [...]
700
701 if __name__ == "__main__":
702 main()
703
Georg Brandl116aa622007-08-15 14:28:22 +0000704
705.. _optparse-reference-guide:
706
707Reference Guide
708---------------
709
710
711.. _optparse-creating-parser:
712
713Creating the parser
714^^^^^^^^^^^^^^^^^^^
715
Georg Brandl15a515f2009-09-17 22:11:49 +0000716The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000717
Georg Brandl15a515f2009-09-17 22:11:49 +0000718.. class:: OptionParser(...)
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Georg Brandl15a515f2009-09-17 22:11:49 +0000720 The OptionParser constructor has no required arguments, but a number of
721 optional keyword arguments. You should always pass them as keyword
722 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl116aa622007-08-15 14:28:22 +0000723
724 ``usage`` (default: ``"%prog [options]"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000725 The usage summary to print when your program is run incorrectly or with a
726 help option. When :mod:`optparse` prints the usage string, it expands
727 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
728 passed that keyword argument). To suppress a usage message, pass the
729 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl116aa622007-08-15 14:28:22 +0000730
731 ``option_list`` (default: ``[]``)
732 A list of Option objects to populate the parser with. The options in
Georg Brandl15a515f2009-09-17 22:11:49 +0000733 ``option_list`` are added after any options in ``standard_option_list`` (a
734 class attribute that may be set by OptionParser subclasses), but before
735 any version or help options. Deprecated; use :meth:`add_option` after
736 creating the parser instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000737
738 ``option_class`` (default: optparse.Option)
739 Class to use when adding options to the parser in :meth:`add_option`.
740
741 ``version`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000742 A version string to print when the user supplies a version option. If you
743 supply a true value for ``version``, :mod:`optparse` automatically adds a
744 version option with the single option string ``"--version"``. The
745 substring ``"%prog"`` is expanded the same as for ``usage``.
Georg Brandl116aa622007-08-15 14:28:22 +0000746
747 ``conflict_handler`` (default: ``"error"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000748 Specifies what to do when options with conflicting option strings are
749 added to the parser; see section
750 :ref:`optparse-conflicts-between-options`.
Georg Brandl116aa622007-08-15 14:28:22 +0000751
752 ``description`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000753 A paragraph of text giving a brief overview of your program.
754 :mod:`optparse` reformats this paragraph to fit the current terminal width
755 and prints it when the user requests help (after ``usage``, but before the
756 list of options).
Georg Brandl116aa622007-08-15 14:28:22 +0000757
Georg Brandl15a515f2009-09-17 22:11:49 +0000758 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
759 An instance of optparse.HelpFormatter that will be used for printing help
760 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl116aa622007-08-15 14:28:22 +0000761 IndentedHelpFormatter and TitledHelpFormatter.
762
763 ``add_help_option`` (default: ``True``)
764 If true, :mod:`optparse` will add a help option (with option strings ``"-h"``
765 and ``"--help"``) to the parser.
766
767 ``prog``
768 The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
769 instead of ``os.path.basename(sys.argv[0])``.
770
Senthil Kumaran5b58f5e2010-03-23 11:00:53 +0000771 ``epilog`` (default: ``None``)
772 A paragraph of help text to print after the option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000773
774.. _optparse-populating-parser:
775
776Populating the parser
777^^^^^^^^^^^^^^^^^^^^^
778
779There are several ways to populate the parser with options. The preferred way
Georg Brandl15a515f2009-09-17 22:11:49 +0000780is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl116aa622007-08-15 14:28:22 +0000781:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
782
783* pass it an Option instance (as returned by :func:`make_option`)
784
785* pass it any combination of positional and keyword arguments that are
Georg Brandl15a515f2009-09-17 22:11:49 +0000786 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
787 will create the Option instance for you
Georg Brandl116aa622007-08-15 14:28:22 +0000788
789The other alternative is to pass a list of pre-constructed Option instances to
790the OptionParser constructor, as in::
791
792 option_list = [
793 make_option("-f", "--filename",
794 action="store", type="string", dest="filename"),
795 make_option("-q", "--quiet",
796 action="store_false", dest="verbose"),
797 ]
798 parser = OptionParser(option_list=option_list)
799
800(:func:`make_option` is a factory function for creating Option instances;
801currently it is an alias for the Option constructor. A future version of
802:mod:`optparse` may split Option into several classes, and :func:`make_option`
803will pick the right class to instantiate. Do not instantiate Option directly.)
804
805
806.. _optparse-defining-options:
807
808Defining options
809^^^^^^^^^^^^^^^^
810
811Each Option instance represents a set of synonymous command-line option strings,
812e.g. :option:`-f` and :option:`--file`. You can specify any number of short or
813long option strings, but you must specify at least one overall option string.
814
Georg Brandl15a515f2009-09-17 22:11:49 +0000815The canonical way to create an :class:`Option` instance is with the
816:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl116aa622007-08-15 14:28:22 +0000817
Georg Brandl15a515f2009-09-17 22:11:49 +0000818.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000819
Georg Brandl15a515f2009-09-17 22:11:49 +0000820 To define an option with only a short option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000821
Georg Brandl15a515f2009-09-17 22:11:49 +0000822 parser.add_option("-f", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000823
Georg Brandl15a515f2009-09-17 22:11:49 +0000824 And to define an option with only a long option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000825
Georg Brandl15a515f2009-09-17 22:11:49 +0000826 parser.add_option("--foo", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000827
Georg Brandl15a515f2009-09-17 22:11:49 +0000828 The keyword arguments define attributes of the new Option object. The most
829 important option attribute is :attr:`~Option.action`, and it largely
830 determines which other attributes are relevant or required. If you pass
831 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
832 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl116aa622007-08-15 14:28:22 +0000833
Georg Brandl15a515f2009-09-17 22:11:49 +0000834 An option's *action* determines what :mod:`optparse` does when it encounters
835 this option on the command-line. The standard option actions hard-coded into
836 :mod:`optparse` are:
Georg Brandl116aa622007-08-15 14:28:22 +0000837
Georg Brandl15a515f2009-09-17 22:11:49 +0000838 ``"store"``
839 store this option's argument (default)
Georg Brandl116aa622007-08-15 14:28:22 +0000840
Georg Brandl15a515f2009-09-17 22:11:49 +0000841 ``"store_const"``
842 store a constant value
Georg Brandl116aa622007-08-15 14:28:22 +0000843
Georg Brandl15a515f2009-09-17 22:11:49 +0000844 ``"store_true"``
845 store a true value
Georg Brandl116aa622007-08-15 14:28:22 +0000846
Georg Brandl15a515f2009-09-17 22:11:49 +0000847 ``"store_false"``
848 store a false value
Georg Brandl116aa622007-08-15 14:28:22 +0000849
Georg Brandl15a515f2009-09-17 22:11:49 +0000850 ``"append"``
851 append this option's argument to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000852
Georg Brandl15a515f2009-09-17 22:11:49 +0000853 ``"append_const"``
854 append a constant value to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000855
Georg Brandl15a515f2009-09-17 22:11:49 +0000856 ``"count"``
857 increment a counter by one
Georg Brandl116aa622007-08-15 14:28:22 +0000858
Georg Brandl15a515f2009-09-17 22:11:49 +0000859 ``"callback"``
860 call a specified function
Georg Brandl116aa622007-08-15 14:28:22 +0000861
Georg Brandl15a515f2009-09-17 22:11:49 +0000862 ``"help"``
863 print a usage message including all options and the documentation for them
Georg Brandl116aa622007-08-15 14:28:22 +0000864
Georg Brandl15a515f2009-09-17 22:11:49 +0000865 (If you don't supply an action, the default is ``"store"``. For this action,
866 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
867 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000868
869As you can see, most actions involve storing or updating a value somewhere.
870:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandl15a515f2009-09-17 22:11:49 +0000871``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl116aa622007-08-15 14:28:22 +0000872arguments (and various other values) are stored as attributes of this object,
Georg Brandl15a515f2009-09-17 22:11:49 +0000873according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000874
Georg Brandl15a515f2009-09-17 22:11:49 +0000875For example, when you call ::
Georg Brandl116aa622007-08-15 14:28:22 +0000876
877 parser.parse_args()
878
879one of the first things :mod:`optparse` does is create the ``options`` object::
880
881 options = Values()
882
Georg Brandl15a515f2009-09-17 22:11:49 +0000883If one of the options in this parser is defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +0000884
885 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
886
887and the command-line being parsed includes any of the following::
888
889 -ffoo
890 -f foo
891 --file=foo
892 --file foo
893
Georg Brandl15a515f2009-09-17 22:11:49 +0000894then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl116aa622007-08-15 14:28:22 +0000895
896 options.filename = "foo"
897
Georg Brandl15a515f2009-09-17 22:11:49 +0000898The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
899as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
900one that makes sense for *all* options.
901
902
903.. _optparse-option-attributes:
904
905Option attributes
906^^^^^^^^^^^^^^^^^
907
908The following option attributes may be passed as keyword arguments to
909:meth:`OptionParser.add_option`. If you pass an option attribute that is not
910relevant to a particular option, or fail to pass a required option attribute,
911:mod:`optparse` raises :exc:`OptionError`.
912
913.. attribute:: Option.action
914
915 (default: ``"store"``)
916
917 Determines :mod:`optparse`'s behaviour when this option is seen on the
918 command line; the available options are documented :ref:`here
919 <optparse-standard-option-actions>`.
920
921.. attribute:: Option.type
922
923 (default: ``"string"``)
924
925 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
926 the available option types are documented :ref:`here
927 <optparse-standard-option-types>`.
928
929.. attribute:: Option.dest
930
931 (default: derived from option strings)
932
933 If the option's action implies writing or modifying a value somewhere, this
934 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
935 attribute of the ``options`` object that :mod:`optparse` builds as it parses
936 the command line.
937
938.. attribute:: Option.default
939
940 The value to use for this option's destination if the option is not seen on
941 the command line. See also :meth:`OptionParser.set_defaults`.
942
943.. attribute:: Option.nargs
944
945 (default: 1)
946
947 How many arguments of type :attr:`~Option.type` should be consumed when this
948 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
949 :attr:`~Option.dest`.
950
951.. attribute:: Option.const
952
953 For actions that store a constant value, the constant value to store.
954
955.. attribute:: Option.choices
956
957 For options of type ``"choice"``, the list of strings the user may choose
958 from.
959
960.. attribute:: Option.callback
961
962 For options with action ``"callback"``, the callable to call when this option
963 is seen. See section :ref:`optparse-option-callbacks` for detail on the
964 arguments passed to the callable.
965
966.. attribute:: Option.callback_args
967 Option.callback_kwargs
968
969 Additional positional and keyword arguments to pass to ``callback`` after the
970 four standard callback arguments.
971
972.. attribute:: Option.help
973
974 Help text to print for this option when listing all available options after
975 the user supplies a :attr:`~Option.help` option (such as ``"--help"``). If
976 no help text is supplied, the option will be listed without help text. To
977 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
978
979.. attribute:: Option.metavar
980
981 (default: derived from option strings)
982
983 Stand-in for the option argument(s) to use when printing help text. See
984 section :ref:`optparse-tutorial` for an example.
Georg Brandl116aa622007-08-15 14:28:22 +0000985
986
987.. _optparse-standard-option-actions:
988
989Standard option actions
990^^^^^^^^^^^^^^^^^^^^^^^
991
992The various option actions all have slightly different requirements and effects.
993Most actions have several relevant option attributes which you may specify to
994guide :mod:`optparse`'s behaviour; a few have required attributes, which you
995must specify for any option using that action.
996
Georg Brandl15a515f2009-09-17 22:11:49 +0000997* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
998 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +0000999
1000 The option must be followed by an argument, which is converted to a value
Georg Brandl15a515f2009-09-17 22:11:49 +00001001 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
1002 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
1003 command line; all will be converted according to :attr:`~Option.type` and
1004 stored to :attr:`~Option.dest` as a tuple. See the
1005 :ref:`optparse-standard-option-types` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001006
Georg Brandl15a515f2009-09-17 22:11:49 +00001007 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1008 defaults to ``"choice"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001009
Georg Brandl15a515f2009-09-17 22:11:49 +00001010 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001011
Georg Brandl15a515f2009-09-17 22:11:49 +00001012 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
1013 from the first long option string (e.g., ``"--foo-bar"`` implies
1014 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
1015 destination from the first short option string (e.g., ``"-f"`` implies ``f``).
Georg Brandl116aa622007-08-15 14:28:22 +00001016
1017 Example::
1018
1019 parser.add_option("-f")
1020 parser.add_option("-p", type="float", nargs=3, dest="point")
1021
Georg Brandl15a515f2009-09-17 22:11:49 +00001022 As it parses the command line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001023
1024 -f foo.txt -p 1 -3.5 4 -fbar.txt
1025
Georg Brandl15a515f2009-09-17 22:11:49 +00001026 :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +00001027
1028 options.f = "foo.txt"
1029 options.point = (1.0, -3.5, 4.0)
1030 options.f = "bar.txt"
1031
Georg Brandl15a515f2009-09-17 22:11:49 +00001032* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1033 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001034
Georg Brandl15a515f2009-09-17 22:11:49 +00001035 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001036
1037 Example::
1038
1039 parser.add_option("-q", "--quiet",
1040 action="store_const", const=0, dest="verbose")
1041 parser.add_option("-v", "--verbose",
1042 action="store_const", const=1, dest="verbose")
1043 parser.add_option("--noisy",
1044 action="store_const", const=2, dest="verbose")
1045
1046 If ``"--noisy"`` is seen, :mod:`optparse` will set ::
1047
1048 options.verbose = 2
1049
Georg Brandl15a515f2009-09-17 22:11:49 +00001050* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001051
Georg Brandl15a515f2009-09-17 22:11:49 +00001052 A special case of ``"store_const"`` that stores a true value to
1053 :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001054
Georg Brandl15a515f2009-09-17 22:11:49 +00001055* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001056
Georg Brandl15a515f2009-09-17 22:11:49 +00001057 Like ``"store_true"``, but stores a false value.
Georg Brandl116aa622007-08-15 14:28:22 +00001058
1059 Example::
1060
1061 parser.add_option("--clobber", action="store_true", dest="clobber")
1062 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1063
Georg Brandl15a515f2009-09-17 22:11:49 +00001064* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1065 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001066
1067 The option must be followed by an argument, which is appended to the list in
Georg Brandl15a515f2009-09-17 22:11:49 +00001068 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1069 supplied, an empty list is automatically created when :mod:`optparse` first
1070 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1071 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1072 is appended to :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001073
Georg Brandl15a515f2009-09-17 22:11:49 +00001074 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1075 for the ``"store"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001076
1077 Example::
1078
1079 parser.add_option("-t", "--tracks", action="append", type="int")
1080
1081 If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
1082 of::
1083
1084 options.tracks = []
1085 options.tracks.append(int("3"))
1086
1087 If, a little later on, ``"--tracks=4"`` is seen, it does::
1088
1089 options.tracks.append(int("4"))
1090
Georg Brandl15a515f2009-09-17 22:11:49 +00001091* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1092 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001093
Georg Brandl15a515f2009-09-17 22:11:49 +00001094 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1095 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1096 ``None``, and an empty list is automatically created the first time the option
1097 is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +00001098
Georg Brandl15a515f2009-09-17 22:11:49 +00001099* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001100
Georg Brandl15a515f2009-09-17 22:11:49 +00001101 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1102 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1103 first time.
Georg Brandl116aa622007-08-15 14:28:22 +00001104
1105 Example::
1106
1107 parser.add_option("-v", action="count", dest="verbosity")
1108
1109 The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
1110 equivalent of::
1111
1112 options.verbosity = 0
1113 options.verbosity += 1
1114
1115 Every subsequent occurrence of ``"-v"`` results in ::
1116
1117 options.verbosity += 1
1118
Georg Brandl15a515f2009-09-17 22:11:49 +00001119* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1120 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1121 :attr:`~Option.callback_kwargs`]
Georg Brandl116aa622007-08-15 14:28:22 +00001122
Georg Brandl15a515f2009-09-17 22:11:49 +00001123 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001124
1125 func(option, opt_str, value, parser, *args, **kwargs)
1126
1127 See section :ref:`optparse-option-callbacks` for more detail.
1128
Georg Brandl15a515f2009-09-17 22:11:49 +00001129* ``"help"``
Georg Brandl116aa622007-08-15 14:28:22 +00001130
Georg Brandl15a515f2009-09-17 22:11:49 +00001131 Prints a complete help message for all the options in the current option
1132 parser. The help message is constructed from the ``usage`` string passed to
1133 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1134 option.
Georg Brandl116aa622007-08-15 14:28:22 +00001135
Georg Brandl15a515f2009-09-17 22:11:49 +00001136 If no :attr:`~Option.help` string is supplied for an option, it will still be
1137 listed in the help message. To omit an option entirely, use the special value
1138 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl116aa622007-08-15 14:28:22 +00001139
Georg Brandl15a515f2009-09-17 22:11:49 +00001140 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1141 OptionParsers, so you do not normally need to create one.
Georg Brandl116aa622007-08-15 14:28:22 +00001142
1143 Example::
1144
1145 from optparse import OptionParser, SUPPRESS_HELP
1146
Georg Brandlee8783d2009-09-16 16:00:31 +00001147 # usually, a help option is added automatically, but that can
1148 # be suppressed using the add_help_option argument
1149 parser = OptionParser(add_help_option=False)
1150
1151 parser.add_option("-h", "--help", action="help")
Georg Brandl116aa622007-08-15 14:28:22 +00001152 parser.add_option("-v", action="store_true", dest="verbose",
1153 help="Be moderately verbose")
1154 parser.add_option("--file", dest="filename",
Georg Brandlee8783d2009-09-16 16:00:31 +00001155 help="Input file to read data from")
Georg Brandl116aa622007-08-15 14:28:22 +00001156 parser.add_option("--secret", help=SUPPRESS_HELP)
1157
Georg Brandl15a515f2009-09-17 22:11:49 +00001158 If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line,
1159 it will print something like the following help message to stdout (assuming
Ezio Melotti383ae952010-01-03 09:06:02 +00001160 ``sys.argv[0]`` is ``"foo.py"``):
1161
1162 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +00001163
1164 usage: foo.py [options]
1165
1166 options:
1167 -h, --help Show this help message and exit
1168 -v Be moderately verbose
1169 --file=FILENAME Input file to read data from
1170
1171 After printing the help message, :mod:`optparse` terminates your process with
1172 ``sys.exit(0)``.
1173
Georg Brandl15a515f2009-09-17 22:11:49 +00001174* ``"version"``
Georg Brandl116aa622007-08-15 14:28:22 +00001175
Georg Brandl15a515f2009-09-17 22:11:49 +00001176 Prints the version number supplied to the OptionParser to stdout and exits.
1177 The version number is actually formatted and printed by the
1178 ``print_version()`` method of OptionParser. Generally only relevant if the
1179 ``version`` argument is supplied to the OptionParser constructor. As with
1180 :attr:`~Option.help` options, you will rarely create ``version`` options,
1181 since :mod:`optparse` automatically adds them when needed.
Georg Brandl116aa622007-08-15 14:28:22 +00001182
1183
1184.. _optparse-standard-option-types:
1185
1186Standard option types
1187^^^^^^^^^^^^^^^^^^^^^
1188
Georg Brandl15a515f2009-09-17 22:11:49 +00001189:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1190``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1191option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +00001192
1193Arguments to string options are not checked or converted in any way: the text on
1194the command line is stored in the destination (or passed to the callback) as-is.
1195
Georg Brandl15a515f2009-09-17 22:11:49 +00001196Integer arguments (type ``"int"``) are parsed as follows:
Georg Brandl116aa622007-08-15 14:28:22 +00001197
1198* if the number starts with ``0x``, it is parsed as a hexadecimal number
1199
1200* if the number starts with ``0``, it is parsed as an octal number
1201
Georg Brandl9afde1c2007-11-01 20:32:30 +00001202* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl116aa622007-08-15 14:28:22 +00001203
1204* otherwise, the number is parsed as a decimal number
1205
1206
Georg Brandl15a515f2009-09-17 22:11:49 +00001207The conversion is done by calling :func:`int` with the appropriate base (2, 8,
120810, or 16). If this fails, so will :mod:`optparse`, although with a more useful
Georg Brandl5c106642007-11-29 17:41:05 +00001209error message.
Georg Brandl116aa622007-08-15 14:28:22 +00001210
Georg Brandl15a515f2009-09-17 22:11:49 +00001211``"float"`` and ``"complex"`` option arguments are converted directly with
1212:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl116aa622007-08-15 14:28:22 +00001213
Georg Brandl15a515f2009-09-17 22:11:49 +00001214``"choice"`` options are a subtype of ``"string"`` options. The
1215:attr:`~Option.choices`` option attribute (a sequence of strings) defines the
1216set of allowed option arguments. :func:`optparse.check_choice` compares
1217user-supplied option arguments against this master list and raises
1218:exc:`OptionValueError` if an invalid string is given.
Georg Brandl116aa622007-08-15 14:28:22 +00001219
1220
1221.. _optparse-parsing-arguments:
1222
1223Parsing arguments
1224^^^^^^^^^^^^^^^^^
1225
1226The whole point of creating and populating an OptionParser is to call its
1227:meth:`parse_args` method::
1228
1229 (options, args) = parser.parse_args(args=None, values=None)
1230
1231where the input parameters are
1232
1233``args``
1234 the list of arguments to process (default: ``sys.argv[1:]``)
1235
1236``values``
Georg Brandl09410122010-08-01 06:53:28 +00001237 a :class:`optparse.Values` object to store option arguments in (default: a
1238 new instance of :class:`Values`) -- if you give an existing object, the
1239 option defaults will not be initialized on it
Georg Brandl116aa622007-08-15 14:28:22 +00001240
1241and the return values are
1242
1243``options``
Georg Brandla6053b42009-09-01 08:11:14 +00001244 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl116aa622007-08-15 14:28:22 +00001245 instance created by :mod:`optparse`
1246
1247``args``
1248 the leftover positional arguments after all options have been processed
1249
1250The most common usage is to supply neither keyword argument. If you supply
Georg Brandl15a515f2009-09-17 22:11:49 +00001251``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl116aa622007-08-15 14:28:22 +00001252for every option argument stored to an option destination) and returned by
1253:meth:`parse_args`.
1254
1255If :meth:`parse_args` encounters any errors in the argument list, it calls the
1256OptionParser's :meth:`error` method with an appropriate end-user error message.
1257This ultimately terminates your process with an exit status of 2 (the
1258traditional Unix exit status for command-line errors).
1259
1260
1261.. _optparse-querying-manipulating-option-parser:
1262
1263Querying and manipulating your option parser
1264^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1265
Georg Brandl15a515f2009-09-17 22:11:49 +00001266The default behavior of the option parser can be customized slightly, and you
1267can also poke around your option parser and see what's there. OptionParser
1268provides several methods to help you out:
Georg Brandl116aa622007-08-15 14:28:22 +00001269
Georg Brandl15a515f2009-09-17 22:11:49 +00001270.. method:: OptionParser.disable_interspersed_args()
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001271
Georg Brandl15a515f2009-09-17 22:11:49 +00001272 Set parsing to stop on the first non-option. For example, if ``"-a"`` and
1273 ``"-b"`` are both simple options that take no arguments, :mod:`optparse`
1274 normally accepts this syntax::
Georg Brandl116aa622007-08-15 14:28:22 +00001275
Georg Brandl15a515f2009-09-17 22:11:49 +00001276 prog -a arg1 -b arg2
1277
1278 and treats it as equivalent to ::
1279
1280 prog -a -b arg1 arg2
1281
1282 To disable this feature, call :meth:`disable_interspersed_args`. This
1283 restores traditional Unix syntax, where option parsing stops with the first
1284 non-option argument.
1285
1286 Use this if you have a command processor which runs another command which has
1287 options of its own and you want to make sure these options don't get
1288 confused. For example, each command might have a different set of options.
1289
1290.. method:: OptionParser.enable_interspersed_args()
1291
1292 Set parsing to not stop on the first non-option, allowing interspersing
1293 switches with command arguments. This is the default behavior.
1294
1295.. method:: OptionParser.get_option(opt_str)
1296
1297 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl116aa622007-08-15 14:28:22 +00001298 no options have that option string.
1299
Georg Brandl15a515f2009-09-17 22:11:49 +00001300.. method:: OptionParser.has_option(opt_str)
1301
1302 Return true if the OptionParser has an option with option string *opt_str*
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001303 (e.g., ``"-q"`` or ``"--verbose"``).
1304
Georg Brandl15a515f2009-09-17 22:11:49 +00001305.. method:: OptionParser.remove_option(opt_str)
1306
1307 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1308 option is removed. If that option provided any other option strings, all of
1309 those option strings become invalid. If *opt_str* does not occur in any
1310 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001311
1312
1313.. _optparse-conflicts-between-options:
1314
1315Conflicts between options
1316^^^^^^^^^^^^^^^^^^^^^^^^^
1317
1318If you're not careful, it's easy to define options with conflicting option
1319strings::
1320
1321 parser.add_option("-n", "--dry-run", ...)
1322 [...]
1323 parser.add_option("-n", "--noisy", ...)
1324
1325(This is particularly true if you've defined your own OptionParser subclass with
1326some standard options.)
1327
1328Every time you add an option, :mod:`optparse` checks for conflicts with existing
1329options. If it finds any, it invokes the current conflict-handling mechanism.
1330You can set the conflict-handling mechanism either in the constructor::
1331
1332 parser = OptionParser(..., conflict_handler=handler)
1333
1334or with a separate call::
1335
1336 parser.set_conflict_handler(handler)
1337
1338The available conflict handlers are:
1339
Georg Brandl15a515f2009-09-17 22:11:49 +00001340 ``"error"`` (default)
1341 assume option conflicts are a programming error and raise
1342 :exc:`OptionConflictError`
Georg Brandl116aa622007-08-15 14:28:22 +00001343
Georg Brandl15a515f2009-09-17 22:11:49 +00001344 ``"resolve"``
Georg Brandl116aa622007-08-15 14:28:22 +00001345 resolve option conflicts intelligently (see below)
1346
1347
Benjamin Petersone5384b02008-10-04 22:00:42 +00001348As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl116aa622007-08-15 14:28:22 +00001349intelligently and add conflicting options to it::
1350
1351 parser = OptionParser(conflict_handler="resolve")
1352 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1353 parser.add_option("-n", "--noisy", ..., help="be noisy")
1354
1355At this point, :mod:`optparse` detects that a previously-added option is already
1356using the ``"-n"`` option string. Since ``conflict_handler`` is ``"resolve"``,
1357it resolves the situation by removing ``"-n"`` from the earlier option's list of
1358option strings. Now ``"--dry-run"`` is the only way for the user to activate
1359that option. If the user asks for help, the help message will reflect that::
1360
1361 options:
1362 --dry-run do no harm
1363 [...]
1364 -n, --noisy be noisy
1365
1366It's possible to whittle away the option strings for a previously-added option
1367until there are none left, and the user has no way of invoking that option from
1368the command-line. In that case, :mod:`optparse` removes that option completely,
1369so it doesn't show up in help text or anywhere else. Carrying on with our
1370existing OptionParser::
1371
1372 parser.add_option("--dry-run", ..., help="new dry-run option")
1373
1374At this point, the original :option:`-n/--dry-run` option is no longer
1375accessible, so :mod:`optparse` removes it, leaving this help text::
1376
1377 options:
1378 [...]
1379 -n, --noisy be noisy
1380 --dry-run new dry-run option
1381
1382
1383.. _optparse-cleanup:
1384
1385Cleanup
1386^^^^^^^
1387
1388OptionParser instances have several cyclic references. This should not be a
1389problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandl15a515f2009-09-17 22:11:49 +00001390references explicitly by calling :meth:`~OptionParser.destroy` on your
1391OptionParser once you are done with it. This is particularly useful in
1392long-running applications where large object graphs are reachable from your
1393OptionParser.
Georg Brandl116aa622007-08-15 14:28:22 +00001394
1395
1396.. _optparse-other-methods:
1397
1398Other methods
1399^^^^^^^^^^^^^
1400
1401OptionParser supports several other public methods:
1402
Georg Brandl15a515f2009-09-17 22:11:49 +00001403.. method:: OptionParser.set_usage(usage)
Georg Brandl116aa622007-08-15 14:28:22 +00001404
Georg Brandl15a515f2009-09-17 22:11:49 +00001405 Set the usage string according to the rules described above for the ``usage``
1406 constructor keyword argument. Passing ``None`` sets the default usage
1407 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl116aa622007-08-15 14:28:22 +00001408
Ezio Melotti1ce43192010-01-04 21:53:17 +00001409.. method:: OptionParser.print_usage(file=None)
1410
1411 Print the usage message for the current program (``self.usage``) to *file*
1412 (default stdout). Any occurrence of the string ``"%prog"`` in ``self.usage``
1413 is replaced with the name of the current program. Does nothing if
1414 ``self.usage`` is empty or not defined.
1415
1416.. method:: OptionParser.get_usage()
1417
1418 Same as :meth:`print_usage` but returns the usage string instead of
1419 printing it.
1420
Georg Brandl15a515f2009-09-17 22:11:49 +00001421.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +00001422
Georg Brandl15a515f2009-09-17 22:11:49 +00001423 Set default values for several option destinations at once. Using
1424 :meth:`set_defaults` is the preferred way to set default values for options,
1425 since multiple options can share the same destination. For example, if
1426 several "mode" options all set the same destination, any one of them can set
1427 the default, and the last one wins::
Georg Brandl116aa622007-08-15 14:28:22 +00001428
Georg Brandl15a515f2009-09-17 22:11:49 +00001429 parser.add_option("--advanced", action="store_const",
1430 dest="mode", const="advanced",
1431 default="novice") # overridden below
1432 parser.add_option("--novice", action="store_const",
1433 dest="mode", const="novice",
1434 default="advanced") # overrides above setting
Georg Brandl116aa622007-08-15 14:28:22 +00001435
Georg Brandl15a515f2009-09-17 22:11:49 +00001436 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl116aa622007-08-15 14:28:22 +00001437
Georg Brandl15a515f2009-09-17 22:11:49 +00001438 parser.set_defaults(mode="advanced")
1439 parser.add_option("--advanced", action="store_const",
1440 dest="mode", const="advanced")
1441 parser.add_option("--novice", action="store_const",
1442 dest="mode", const="novice")
Georg Brandl116aa622007-08-15 14:28:22 +00001443
Georg Brandl116aa622007-08-15 14:28:22 +00001444
1445.. _optparse-option-callbacks:
1446
1447Option Callbacks
1448----------------
1449
1450When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1451needs, you have two choices: extend :mod:`optparse` or define a callback option.
1452Extending :mod:`optparse` is more general, but overkill for a lot of simple
1453cases. Quite often a simple callback is all you need.
1454
1455There are two steps to defining a callback option:
1456
Georg Brandl15a515f2009-09-17 22:11:49 +00001457* define the option itself using the ``"callback"`` action
Georg Brandl116aa622007-08-15 14:28:22 +00001458
1459* write the callback; this is a function (or method) that takes at least four
1460 arguments, as described below
1461
1462
1463.. _optparse-defining-callback-option:
1464
1465Defining a callback option
1466^^^^^^^^^^^^^^^^^^^^^^^^^^
1467
1468As always, the easiest way to define a callback option is by using the
Georg Brandl15a515f2009-09-17 22:11:49 +00001469:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1470only option attribute you must specify is ``callback``, the function to call::
Georg Brandl116aa622007-08-15 14:28:22 +00001471
1472 parser.add_option("-c", action="callback", callback=my_callback)
1473
1474``callback`` is a function (or other callable object), so you must have already
1475defined ``my_callback()`` when you create this callback option. In this simple
1476case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,
1477which usually means that the option takes no arguments---the mere presence of
1478:option:`-c` on the command-line is all it needs to know. In some
1479circumstances, though, you might want your callback to consume an arbitrary
1480number of command-line arguments. This is where writing callbacks gets tricky;
1481it's covered later in this section.
1482
1483:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandl15a515f2009-09-17 22:11:49 +00001484will only pass additional arguments if you specify them via
1485:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1486minimal callback function signature is::
Georg Brandl116aa622007-08-15 14:28:22 +00001487
1488 def my_callback(option, opt, value, parser):
1489
1490The four arguments to a callback are described below.
1491
1492There are several other option attributes that you can supply when you define a
1493callback option:
1494
Georg Brandl15a515f2009-09-17 22:11:49 +00001495:attr:`~Option.type`
1496 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1497 instructs :mod:`optparse` to consume one argument and convert it to
1498 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1499 though, :mod:`optparse` passes it to your callback function.
Georg Brandl116aa622007-08-15 14:28:22 +00001500
Georg Brandl15a515f2009-09-17 22:11:49 +00001501:attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001502 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001503 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1504 :attr:`~Option.type`. It then passes a tuple of converted values to your
1505 callback.
Georg Brandl116aa622007-08-15 14:28:22 +00001506
Georg Brandl15a515f2009-09-17 22:11:49 +00001507:attr:`~Option.callback_args`
Georg Brandl116aa622007-08-15 14:28:22 +00001508 a tuple of extra positional arguments to pass to the callback
1509
Georg Brandl15a515f2009-09-17 22:11:49 +00001510:attr:`~Option.callback_kwargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001511 a dictionary of extra keyword arguments to pass to the callback
1512
1513
1514.. _optparse-how-callbacks-called:
1515
1516How callbacks are called
1517^^^^^^^^^^^^^^^^^^^^^^^^
1518
1519All callbacks are called as follows::
1520
1521 func(option, opt_str, value, parser, *args, **kwargs)
1522
1523where
1524
1525``option``
1526 is the Option instance that's calling the callback
1527
1528``opt_str``
1529 is the option string seen on the command-line that's triggering the callback.
Georg Brandl15a515f2009-09-17 22:11:49 +00001530 (If an abbreviated long option was used, ``opt_str`` will be the full,
1531 canonical option string---e.g. if the user puts ``"--foo"`` on the
1532 command-line as an abbreviation for ``"--foobar"``, then ``opt_str`` will be
1533 ``"--foobar"``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001534
1535``value``
1536 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001537 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1538 the type implied by the option's type. If :attr:`~Option.type` for this option is
1539 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001540 > 1, ``value`` will be a tuple of values of the appropriate type.
1541
1542``parser``
Georg Brandl15a515f2009-09-17 22:11:49 +00001543 is the OptionParser instance driving the whole thing, mainly useful because
1544 you can access some other interesting data through its instance attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001545
1546 ``parser.largs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001547 the current list of leftover arguments, ie. arguments that have been
1548 consumed but are neither options nor option arguments. Feel free to modify
1549 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1550 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001551
1552 ``parser.rargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001553 the current list of remaining arguments, ie. with ``opt_str`` and
1554 ``value`` (if applicable) removed, and only the arguments following them
1555 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1556 arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001557
1558 ``parser.values``
1559 the object where option values are by default stored (an instance of
Georg Brandl15a515f2009-09-17 22:11:49 +00001560 optparse.OptionValues). This lets callbacks use the same mechanism as the
1561 rest of :mod:`optparse` for storing option values; you don't need to mess
1562 around with globals or closures. You can also access or modify the
1563 value(s) of any options already encountered on the command-line.
Georg Brandl116aa622007-08-15 14:28:22 +00001564
1565``args``
Georg Brandl15a515f2009-09-17 22:11:49 +00001566 is a tuple of arbitrary positional arguments supplied via the
1567 :attr:`~Option.callback_args` option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001568
1569``kwargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001570 is a dictionary of arbitrary keyword arguments supplied via
1571 :attr:`~Option.callback_kwargs`.
Georg Brandl116aa622007-08-15 14:28:22 +00001572
1573
1574.. _optparse-raising-errors-in-callback:
1575
1576Raising errors in a callback
1577^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1578
Georg Brandl15a515f2009-09-17 22:11:49 +00001579The callback function should raise :exc:`OptionValueError` if there are any
1580problems with the option or its argument(s). :mod:`optparse` catches this and
1581terminates the program, printing the error message you supply to stderr. Your
1582message should be clear, concise, accurate, and mention the option at fault.
1583Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl116aa622007-08-15 14:28:22 +00001584
1585
1586.. _optparse-callback-example-1:
1587
1588Callback example 1: trivial callback
1589^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1590
1591Here's an example of a callback option that takes no arguments, and simply
1592records that the option was seen::
1593
1594 def record_foo_seen(option, opt_str, value, parser):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001595 parser.values.saw_foo = True
Georg Brandl116aa622007-08-15 14:28:22 +00001596
1597 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1598
Georg Brandl15a515f2009-09-17 22:11:49 +00001599Of course, you could do that with the ``"store_true"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001600
1601
1602.. _optparse-callback-example-2:
1603
1604Callback example 2: check option order
1605^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1606
1607Here's a slightly more interesting example: record the fact that ``"-a"`` is
1608seen, but blow up if it comes after ``"-b"`` in the command-line. ::
1609
1610 def check_order(option, opt_str, value, parser):
1611 if parser.values.b:
1612 raise OptionValueError("can't use -a after -b")
1613 parser.values.a = 1
1614 [...]
1615 parser.add_option("-a", action="callback", callback=check_order)
1616 parser.add_option("-b", action="store_true", dest="b")
1617
1618
1619.. _optparse-callback-example-3:
1620
1621Callback example 3: check option order (generalized)
1622^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1623
1624If you want to re-use this callback for several similar options (set a flag, but
1625blow up if ``"-b"`` has already been seen), it needs a bit of work: the error
1626message and the flag that it sets must be generalized. ::
1627
1628 def check_order(option, opt_str, value, parser):
1629 if parser.values.b:
1630 raise OptionValueError("can't use %s after -b" % opt_str)
1631 setattr(parser.values, option.dest, 1)
1632 [...]
1633 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1634 parser.add_option("-b", action="store_true", dest="b")
1635 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1636
1637
1638.. _optparse-callback-example-4:
1639
1640Callback example 4: check arbitrary condition
1641^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1642
1643Of course, you could put any condition in there---you're not limited to checking
1644the values of already-defined options. For example, if you have options that
1645should not be called when the moon is full, all you have to do is this::
1646
1647 def check_moon(option, opt_str, value, parser):
1648 if is_moon_full():
1649 raise OptionValueError("%s option invalid when moon is full"
1650 % opt_str)
1651 setattr(parser.values, option.dest, 1)
1652 [...]
1653 parser.add_option("--foo",
1654 action="callback", callback=check_moon, dest="foo")
1655
1656(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1657
1658
1659.. _optparse-callback-example-5:
1660
1661Callback example 5: fixed arguments
1662^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1663
1664Things get slightly more interesting when you define callback options that take
1665a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandl15a515f2009-09-17 22:11:49 +00001666is similar to defining a ``"store"`` or ``"append"`` option: if you define
1667:attr:`~Option.type`, then the option takes one argument that must be
1668convertible to that type; if you further define :attr:`~Option.nargs`, then the
1669option takes :attr:`~Option.nargs` arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001670
Georg Brandl15a515f2009-09-17 22:11:49 +00001671Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl116aa622007-08-15 14:28:22 +00001672
1673 def store_value(option, opt_str, value, parser):
1674 setattr(parser.values, option.dest, value)
1675 [...]
1676 parser.add_option("--foo",
1677 action="callback", callback=store_value,
1678 type="int", nargs=3, dest="foo")
1679
1680Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1681them to integers for you; all you have to do is store them. (Or whatever;
1682obviously you don't need a callback for this example.)
1683
1684
1685.. _optparse-callback-example-6:
1686
1687Callback example 6: variable arguments
1688^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1689
1690Things get hairy when you want an option to take a variable number of arguments.
1691For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1692built-in capabilities for it. And you have to deal with certain intricacies of
1693conventional Unix command-line parsing that :mod:`optparse` normally handles for
1694you. In particular, callbacks should implement the conventional rules for bare
1695``"--"`` and ``"-"`` arguments:
1696
1697* either ``"--"`` or ``"-"`` can be option arguments
1698
1699* bare ``"--"`` (if not the argument to some option): halt command-line
1700 processing and discard the ``"--"``
1701
1702* bare ``"-"`` (if not the argument to some option): halt command-line
1703 processing but keep the ``"-"`` (append it to ``parser.largs``)
1704
1705If you want an option that takes a variable number of arguments, there are
1706several subtle, tricky issues to worry about. The exact implementation you
1707choose will be based on which trade-offs you're willing to make for your
1708application (which is why :mod:`optparse` doesn't support this sort of thing
1709directly).
1710
1711Nevertheless, here's a stab at a callback for an option with variable
1712arguments::
1713
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001714 def vararg_callback(option, opt_str, value, parser):
1715 assert value is None
1716 value = []
Georg Brandl116aa622007-08-15 14:28:22 +00001717
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001718 def floatable(str):
1719 try:
1720 float(str)
1721 return True
1722 except ValueError:
1723 return False
Georg Brandl116aa622007-08-15 14:28:22 +00001724
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001725 for arg in parser.rargs:
1726 # stop on --foo like options
1727 if arg[:2] == "--" and len(arg) > 2:
1728 break
1729 # stop on -a, but not on -3 or -3.0
1730 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1731 break
1732 value.append(arg)
1733
1734 del parser.rargs[:len(value)]
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001735 setattr(parser.values, option.dest, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001736
1737 [...]
Benjamin Petersonae5360b2008-09-08 23:05:23 +00001738 parser.add_option("-c", "--callback", dest="vararg_attr",
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001739 action="callback", callback=vararg_callback)
Georg Brandl116aa622007-08-15 14:28:22 +00001740
Georg Brandl116aa622007-08-15 14:28:22 +00001741
1742.. _optparse-extending-optparse:
1743
1744Extending :mod:`optparse`
1745-------------------------
1746
1747Since the two major controlling factors in how :mod:`optparse` interprets
1748command-line options are the action and type of each option, the most likely
1749direction of extension is to add new actions and new types.
1750
1751
1752.. _optparse-adding-new-types:
1753
1754Adding new types
1755^^^^^^^^^^^^^^^^
1756
1757To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandl15a515f2009-09-17 22:11:49 +00001758:class:`Option` class. This class has a couple of attributes that define
1759:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl116aa622007-08-15 14:28:22 +00001760
Georg Brandl15a515f2009-09-17 22:11:49 +00001761.. attribute:: Option.TYPES
Georg Brandl116aa622007-08-15 14:28:22 +00001762
Georg Brandl15a515f2009-09-17 22:11:49 +00001763 A tuple of type names; in your subclass, simply define a new tuple
1764 :attr:`TYPES` that builds on the standard one.
Georg Brandl116aa622007-08-15 14:28:22 +00001765
Georg Brandl15a515f2009-09-17 22:11:49 +00001766.. attribute:: Option.TYPE_CHECKER
Georg Brandl116aa622007-08-15 14:28:22 +00001767
Georg Brandl15a515f2009-09-17 22:11:49 +00001768 A dictionary mapping type names to type-checking functions. A type-checking
1769 function has the following signature::
Georg Brandl116aa622007-08-15 14:28:22 +00001770
Georg Brandl15a515f2009-09-17 22:11:49 +00001771 def check_mytype(option, opt, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001772
Georg Brandl15a515f2009-09-17 22:11:49 +00001773 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1774 (e.g., ``"-f"``), and ``value`` is the string from the command line that must
1775 be checked and converted to your desired type. ``check_mytype()`` should
1776 return an object of the hypothetical type ``mytype``. The value returned by
1777 a type-checking function will wind up in the OptionValues instance returned
1778 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1779 ``value`` parameter.
1780
1781 Your type-checking function should raise :exc:`OptionValueError` if it
1782 encounters any problems. :exc:`OptionValueError` takes a single string
1783 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1784 method, which in turn prepends the program name and the string ``"error:"``
1785 and prints everything to stderr before terminating the process.
1786
1787Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl116aa622007-08-15 14:28:22 +00001788parse Python-style complex numbers on the command line. (This is even sillier
1789than it used to be, because :mod:`optparse` 1.3 added built-in support for
1790complex numbers, but never mind.)
1791
1792First, the necessary imports::
1793
1794 from copy import copy
1795 from optparse import Option, OptionValueError
1796
1797You need to define your type-checker first, since it's referred to later (in the
Georg Brandl15a515f2009-09-17 22:11:49 +00001798:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl116aa622007-08-15 14:28:22 +00001799
1800 def check_complex(option, opt, value):
1801 try:
1802 return complex(value)
1803 except ValueError:
1804 raise OptionValueError(
1805 "option %s: invalid complex value: %r" % (opt, value))
1806
1807Finally, the Option subclass::
1808
1809 class MyOption (Option):
1810 TYPES = Option.TYPES + ("complex",)
1811 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1812 TYPE_CHECKER["complex"] = check_complex
1813
1814(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandl15a515f2009-09-17 22:11:49 +00001815up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1816Option class. This being Python, nothing stops you from doing that except good
1817manners and common sense.)
Georg Brandl116aa622007-08-15 14:28:22 +00001818
1819That's it! Now you can write a script that uses the new option type just like
1820any other :mod:`optparse`\ -based script, except you have to instruct your
1821OptionParser to use MyOption instead of Option::
1822
1823 parser = OptionParser(option_class=MyOption)
1824 parser.add_option("-c", type="complex")
1825
1826Alternately, you can build your own option list and pass it to OptionParser; if
1827you don't use :meth:`add_option` in the above way, you don't need to tell
1828OptionParser which option class to use::
1829
1830 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1831 parser = OptionParser(option_list=option_list)
1832
1833
1834.. _optparse-adding-new-actions:
1835
1836Adding new actions
1837^^^^^^^^^^^^^^^^^^
1838
1839Adding new actions is a bit trickier, because you have to understand that
1840:mod:`optparse` has a couple of classifications for actions:
1841
1842"store" actions
1843 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandl15a515f2009-09-17 22:11:49 +00001844 current OptionValues instance; these options require a :attr:`~Option.dest`
1845 attribute to be supplied to the Option constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001846
1847"typed" actions
Georg Brandl15a515f2009-09-17 22:11:49 +00001848 actions that take a value from the command line and expect it to be of a
1849 certain type; or rather, a string that can be converted to a certain type.
1850 These options require a :attr:`~Option.type` attribute to the Option
1851 constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001852
Georg Brandl15a515f2009-09-17 22:11:49 +00001853These are overlapping sets: some default "store" actions are ``"store"``,
1854``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1855actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001856
1857When you add an action, you need to categorize it by listing it in at least one
1858of the following class attributes of Option (all are lists of strings):
1859
Georg Brandl15a515f2009-09-17 22:11:49 +00001860.. attribute:: Option.ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001861
Georg Brandl15a515f2009-09-17 22:11:49 +00001862 All actions must be listed in ACTIONS.
Georg Brandl116aa622007-08-15 14:28:22 +00001863
Georg Brandl15a515f2009-09-17 22:11:49 +00001864.. attribute:: Option.STORE_ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001865
Georg Brandl15a515f2009-09-17 22:11:49 +00001866 "store" actions are additionally listed here.
1867
1868.. attribute:: Option.TYPED_ACTIONS
1869
1870 "typed" actions are additionally listed here.
1871
1872.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1873
1874 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl116aa622007-08-15 14:28:22 +00001875 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001876 assigns the default type, ``"string"``, to options with no explicit type
1877 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001878
1879In order to actually implement your new action, you must override Option's
1880:meth:`take_action` method and add a case that recognizes your action.
1881
Georg Brandl15a515f2009-09-17 22:11:49 +00001882For example, let's add an ``"extend"`` action. This is similar to the standard
1883``"append"`` action, but instead of taking a single value from the command-line
1884and appending it to an existing list, ``"extend"`` will take multiple values in
1885a single comma-delimited string, and extend an existing list with them. That
1886is, if ``"--names"`` is an ``"extend"`` option of type ``"string"``, the command
1887line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001888
1889 --names=foo,bar --names blah --names ding,dong
1890
1891would result in a list ::
1892
1893 ["foo", "bar", "blah", "ding", "dong"]
1894
1895Again we define a subclass of Option::
1896
Ezio Melotti383ae952010-01-03 09:06:02 +00001897 class MyOption(Option):
Georg Brandl116aa622007-08-15 14:28:22 +00001898
1899 ACTIONS = Option.ACTIONS + ("extend",)
1900 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1901 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1902 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1903
1904 def take_action(self, action, dest, opt, value, values, parser):
1905 if action == "extend":
1906 lvalue = value.split(",")
1907 values.ensure_value(dest, []).extend(lvalue)
1908 else:
1909 Option.take_action(
1910 self, action, dest, opt, value, values, parser)
1911
1912Features of note:
1913
Georg Brandl15a515f2009-09-17 22:11:49 +00001914* ``"extend"`` both expects a value on the command-line and stores that value
1915 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1916 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001917
Georg Brandl15a515f2009-09-17 22:11:49 +00001918* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1919 ``"extend"`` actions, we put the ``"extend"`` action in
1920 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001921
1922* :meth:`MyOption.take_action` implements just this one new action, and passes
1923 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001924 actions.
Georg Brandl116aa622007-08-15 14:28:22 +00001925
Georg Brandl15a515f2009-09-17 22:11:49 +00001926* ``values`` is an instance of the optparse_parser.Values class, which provides
1927 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1928 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001929
1930 values.ensure_value(attr, value)
1931
1932 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandl15a515f2009-09-17 22:11:49 +00001933 ensure_value() first sets it to ``value``, and then returns 'value. This is
1934 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
1935 of which accumulate data in a variable and expect that variable to be of a
1936 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl116aa622007-08-15 14:28:22 +00001937 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandl15a515f2009-09-17 22:11:49 +00001938 about setting a default value for the option destinations in question; they
1939 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl116aa622007-08-15 14:28:22 +00001940 getting it right when it's needed.