blob: 9b39869669810af34d9736d24065c8873977613c [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`optparse` --- More powerful command line option parser
2============================================================
3
4.. module:: optparse
5 :synopsis: More convenient, flexible, and powerful command-line parsing library.
6.. moduleauthor:: Greg Ward <gward@python.net>
7
8
9.. versionadded:: 2.3
10
11.. sectionauthor:: Greg Ward <gward@python.net>
12
13
Georg Brandlb926ebb2009-09-17 17:14:04 +000014:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
15command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
16more declarative style of command-line parsing: you create an instance of
17:class:`OptionParser`, populate it with options, and parse the command
18line. :mod:`optparse` allows users to specify options in the conventional
19GNU/POSIX syntax, and additionally generates usage and help messages for you.
Georg Brandl8ec7f652007-08-15 14:28:01 +000020
Georg Brandlb926ebb2009-09-17 17:14:04 +000021Here's an example of using :mod:`optparse` in a simple script::
Georg Brandl8ec7f652007-08-15 14:28:01 +000022
23 from optparse import OptionParser
24 [...]
25 parser = OptionParser()
26 parser.add_option("-f", "--file", dest="filename",
27 help="write report to FILE", metavar="FILE")
28 parser.add_option("-q", "--quiet",
29 action="store_false", dest="verbose", default=True,
30 help="don't print status messages to stdout")
31
32 (options, args) = parser.parse_args()
33
34With these few lines of code, users of your script can now do the "usual thing"
35on the command-line, for example::
36
37 <yourscript> --file=outfile -q
38
Georg Brandlb926ebb2009-09-17 17:14:04 +000039As it parses the command line, :mod:`optparse` sets attributes of the
40``options`` object returned by :meth:`parse_args` based on user-supplied
41command-line values. When :meth:`parse_args` returns from parsing this command
42line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
43``False``. :mod:`optparse` supports both long and short options, allows short
Georg Brandl8ec7f652007-08-15 14:28:01 +000044options to be merged together, and allows options to be associated with their
45arguments in a variety of ways. Thus, the following command lines are all
46equivalent to the above example::
47
48 <yourscript> -f outfile --quiet
49 <yourscript> --quiet --file outfile
50 <yourscript> -q -foutfile
51 <yourscript> -qfoutfile
52
53Additionally, users can run one of ::
54
55 <yourscript> -h
56 <yourscript> --help
57
Georg Brandlb926ebb2009-09-17 17:14:04 +000058and :mod:`optparse` will print out a brief summary of your script's options::
Georg Brandl8ec7f652007-08-15 14:28:01 +000059
60 usage: <yourscript> [options]
61
62 options:
63 -h, --help show this help message and exit
64 -f FILE, --file=FILE write report to FILE
65 -q, --quiet don't print status messages to stdout
66
67where the value of *yourscript* is determined at runtime (normally from
68``sys.argv[0]``).
69
Georg Brandl8ec7f652007-08-15 14:28:01 +000070
71.. _optparse-background:
72
73Background
74----------
75
76:mod:`optparse` was explicitly designed to encourage the creation of programs
77with straightforward, conventional command-line interfaces. To that end, it
78supports only the most common command-line syntax and semantics conventionally
79used under Unix. If you are unfamiliar with these conventions, read this
80section to acquaint yourself with them.
81
82
83.. _optparse-terminology:
84
85Terminology
86^^^^^^^^^^^
87
88argument
Georg Brandlb926ebb2009-09-17 17:14:04 +000089 a string entered on the command-line, and passed by the shell to ``execl()``
90 or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
91 (``sys.argv[0]`` is the name of the program being executed). Unix shells
92 also use the term "word".
Georg Brandl8ec7f652007-08-15 14:28:01 +000093
94 It is occasionally desirable to substitute an argument list other than
95 ``sys.argv[1:]``, so you should read "argument" as "an element of
96 ``sys.argv[1:]``, or of some other list provided as a substitute for
97 ``sys.argv[1:]``".
98
Andrew M. Kuchling810f8072008-09-06 13:04:02 +000099option
Georg Brandlb926ebb2009-09-17 17:14:04 +0000100 an argument used to supply extra information to guide or customize the
101 execution of a program. There are many different syntaxes for options; the
102 traditional Unix syntax is a hyphen ("-") followed by a single letter,
103 e.g. ``"-x"`` or ``"-F"``. Also, traditional Unix syntax allows multiple
104 options to be merged into a single argument, e.g. ``"-x -F"`` is equivalent
105 to ``"-xF"``. The GNU project introduced ``"--"`` followed by a series of
106 hyphen-separated words, e.g. ``"--file"`` or ``"--dry-run"``. These are the
107 only two option syntaxes provided by :mod:`optparse`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108
109 Some other option syntaxes that the world has seen include:
110
111 * a hyphen followed by a few letters, e.g. ``"-pf"`` (this is *not* the same
112 as multiple options merged into a single argument)
113
114 * a hyphen followed by a whole word, e.g. ``"-file"`` (this is technically
115 equivalent to the previous syntax, but they aren't usually seen in the same
116 program)
117
118 * a plus sign followed by a single letter, or a few letters, or a word, e.g.
119 ``"+f"``, ``"+rgb"``
120
121 * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
122 ``"/file"``
123
Georg Brandlb926ebb2009-09-17 17:14:04 +0000124 These option syntaxes are not supported by :mod:`optparse`, and they never
125 will be. This is deliberate: the first three are non-standard on any
126 environment, and the last only makes sense if you're exclusively targeting
127 VMS, MS-DOS, and/or Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000128
129option argument
Georg Brandlb926ebb2009-09-17 17:14:04 +0000130 an argument that follows an option, is closely associated with that option,
131 and is consumed from the argument list when that option is. With
132 :mod:`optparse`, option arguments may either be in a separate argument from
133 their option::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000134
135 -f foo
136 --file foo
137
138 or included in the same argument::
139
140 -ffoo
141 --file=foo
142
Georg Brandlb926ebb2009-09-17 17:14:04 +0000143 Typically, a given option either takes an argument or it doesn't. Lots of
144 people want an "optional option arguments" feature, meaning that some options
145 will take an argument if they see it, and won't if they don't. This is
146 somewhat controversial, because it makes parsing ambiguous: if ``"-a"`` takes
147 an optional argument and ``"-b"`` is another option entirely, how do we
148 interpret ``"-ab"``? Because of this ambiguity, :mod:`optparse` does not
149 support this feature.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000150
151positional argument
152 something leftover in the argument list after options have been parsed, i.e.
Georg Brandlb926ebb2009-09-17 17:14:04 +0000153 after options and their arguments have been parsed and removed from the
154 argument list.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000155
156required option
157 an option that must be supplied on the command-line; note that the phrase
158 "required option" is self-contradictory in English. :mod:`optparse` doesn't
Georg Brandlb926ebb2009-09-17 17:14:04 +0000159 prevent you from implementing required options, but doesn't give you much
Georg Brandl66d8d692009-12-28 08:48:24 +0000160 help at it either.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161
162For example, consider this hypothetical command-line::
163
164 prog -v --report /tmp/report.txt foo bar
165
166``"-v"`` and ``"--report"`` are both options. Assuming that :option:`--report`
167takes one argument, ``"/tmp/report.txt"`` is an option argument. ``"foo"`` and
168``"bar"`` are positional arguments.
169
170
171.. _optparse-what-options-for:
172
173What are options for?
174^^^^^^^^^^^^^^^^^^^^^
175
176Options are used to provide extra information to tune or customize the execution
177of a program. In case it wasn't clear, options are usually *optional*. A
178program should be able to run just fine with no options whatsoever. (Pick a
179random program from the Unix or GNU toolsets. Can it run without any options at
180all and still make sense? The main exceptions are ``find``, ``tar``, and
181``dd``\ ---all of which are mutant oddballs that have been rightly criticized
182for their non-standard syntax and confusing interfaces.)
183
184Lots of people want their programs to have "required options". Think about it.
185If it's required, then it's *not optional*! If there is a piece of information
186that your program absolutely requires in order to run successfully, that's what
187positional arguments are for.
188
189As an example of good command-line interface design, consider the humble ``cp``
190utility, for copying files. It doesn't make much sense to try to copy files
191without supplying a destination and at least one source. Hence, ``cp`` fails if
192you run it with no arguments. However, it has a flexible, useful syntax that
193does not require any options at all::
194
195 cp SOURCE DEST
196 cp SOURCE ... DEST-DIR
197
198You can get pretty far with just that. Most ``cp`` implementations provide a
199bunch of options to tweak exactly how the files are copied: you can preserve
200mode and modification time, avoid following symlinks, ask before clobbering
201existing files, etc. But none of this distracts from the core mission of
202``cp``, which is to copy either one file to another, or several files to another
203directory.
204
205
206.. _optparse-what-positional-arguments-for:
207
208What are positional arguments for?
209^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
210
211Positional arguments are for those pieces of information that your program
212absolutely, positively requires to run.
213
214A good user interface should have as few absolute requirements as possible. If
215your program requires 17 distinct pieces of information in order to run
216successfully, it doesn't much matter *how* you get that information from the
217user---most people will give up and walk away before they successfully run the
218program. This applies whether the user interface is a command-line, a
219configuration file, or a GUI: if you make that many demands on your users, most
220of them will simply give up.
221
222In short, try to minimize the amount of information that users are absolutely
223required to supply---use sensible defaults whenever possible. Of course, you
224also want to make your programs reasonably flexible. That's what options are
225for. Again, it doesn't matter if they are entries in a config file, widgets in
226the "Preferences" dialog of a GUI, or command-line options---the more options
227you implement, the more flexible your program is, and the more complicated its
228implementation becomes. Too much flexibility has drawbacks as well, of course;
229too many options can overwhelm users and make your code much harder to maintain.
230
Georg Brandl8ec7f652007-08-15 14:28:01 +0000231
232.. _optparse-tutorial:
233
234Tutorial
235--------
236
237While :mod:`optparse` is quite flexible and powerful, it's also straightforward
238to use in most cases. This section covers the code patterns that are common to
239any :mod:`optparse`\ -based program.
240
241First, you need to import the OptionParser class; then, early in the main
242program, create an OptionParser instance::
243
244 from optparse import OptionParser
245 [...]
246 parser = OptionParser()
247
248Then you can start defining options. The basic syntax is::
249
250 parser.add_option(opt_str, ...,
251 attr=value, ...)
252
253Each option has one or more option strings, such as ``"-f"`` or ``"--file"``,
254and several option attributes that tell :mod:`optparse` what to expect and what
255to do when it encounters that option on the command line.
256
257Typically, each option will have one short option string and one long option
258string, e.g.::
259
260 parser.add_option("-f", "--file", ...)
261
262You're free to define as many short option strings and as many long option
263strings as you like (including zero), as long as there is at least one option
264string overall.
265
266The option strings passed to :meth:`add_option` are effectively labels for the
267option defined by that call. For brevity, we will frequently refer to
268*encountering an option* on the command line; in reality, :mod:`optparse`
269encounters *option strings* and looks up options from them.
270
271Once all of your options are defined, instruct :mod:`optparse` to parse your
272program's command line::
273
274 (options, args) = parser.parse_args()
275
276(If you like, you can pass a custom argument list to :meth:`parse_args`, but
277that's rarely necessary: by default it uses ``sys.argv[1:]``.)
278
279:meth:`parse_args` returns two values:
280
281* ``options``, an object containing values for all of your options---e.g. if
282 ``"--file"`` takes a single string argument, then ``options.file`` will be the
283 filename supplied by the user, or ``None`` if the user did not supply that
284 option
285
286* ``args``, the list of positional arguments leftover after parsing options
287
288This tutorial section only covers the four most important option attributes:
Georg Brandlb926ebb2009-09-17 17:14:04 +0000289:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
290(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
291most fundamental.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000292
293
294.. _optparse-understanding-option-actions:
295
296Understanding option actions
297^^^^^^^^^^^^^^^^^^^^^^^^^^^^
298
299Actions tell :mod:`optparse` what to do when it encounters an option on the
300command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
301adding new actions is an advanced topic covered in section
Georg Brandlb926ebb2009-09-17 17:14:04 +0000302:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
303a value in some variable---for example, take a string from the command line and
304store it in an attribute of ``options``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000305
306If you don't specify an option action, :mod:`optparse` defaults to ``store``.
307
308
309.. _optparse-store-action:
310
311The store action
312^^^^^^^^^^^^^^^^
313
314The most common option action is ``store``, which tells :mod:`optparse` to take
315the next argument (or the remainder of the current argument), ensure that it is
316of the correct type, and store it to your chosen destination.
317
318For example::
319
320 parser.add_option("-f", "--file",
321 action="store", type="string", dest="filename")
322
323Now let's make up a fake command line and ask :mod:`optparse` to parse it::
324
325 args = ["-f", "foo.txt"]
326 (options, args) = parser.parse_args(args)
327
328When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
329argument, ``"foo.txt"``, and stores it in ``options.filename``. So, after this
330call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
331
332Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
333Here's an option that expects an integer argument::
334
335 parser.add_option("-n", type="int", dest="num")
336
337Note that this option has no long option string, which is perfectly acceptable.
338Also, there's no explicit action, since the default is ``store``.
339
340Let's parse another fake command-line. This time, we'll jam the option argument
341right up against the option: since ``"-n42"`` (one argument) is equivalent to
Georg Brandlb926ebb2009-09-17 17:14:04 +0000342``"-n 42"`` (two arguments), the code ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343
344 (options, args) = parser.parse_args(["-n42"])
345 print options.num
346
347will print ``"42"``.
348
349If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
350the fact that the default action is ``store``, that means our first example can
351be a lot shorter::
352
353 parser.add_option("-f", "--file", dest="filename")
354
355If you don't supply a destination, :mod:`optparse` figures out a sensible
356default from the option strings: if the first long option string is
357``"--foo-bar"``, then the default destination is ``foo_bar``. If there are no
358long option strings, :mod:`optparse` looks at the first short option string: the
359default destination for ``"-f"`` is ``f``.
360
361:mod:`optparse` also includes built-in ``long`` and ``complex`` types. Adding
362types is covered in section :ref:`optparse-extending-optparse`.
363
364
365.. _optparse-handling-boolean-options:
366
367Handling boolean (flag) options
368^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
369
370Flag options---set a variable to true or false when a particular option is seen
371---are quite common. :mod:`optparse` supports them with two separate actions,
372``store_true`` and ``store_false``. For example, you might have a ``verbose``
373flag that is turned on with ``"-v"`` and off with ``"-q"``::
374
375 parser.add_option("-v", action="store_true", dest="verbose")
376 parser.add_option("-q", action="store_false", dest="verbose")
377
378Here we have two different options with the same destination, which is perfectly
379OK. (It just means you have to be a bit careful when setting default values---
380see below.)
381
382When :mod:`optparse` encounters ``"-v"`` on the command line, it sets
383``options.verbose`` to ``True``; when it encounters ``"-q"``,
384``options.verbose`` is set to ``False``.
385
386
387.. _optparse-other-actions:
388
389Other actions
390^^^^^^^^^^^^^
391
392Some other actions supported by :mod:`optparse` are:
393
Georg Brandlb926ebb2009-09-17 17:14:04 +0000394``"store_const"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000395 store a constant value
396
Georg Brandlb926ebb2009-09-17 17:14:04 +0000397``"append"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000398 append this option's argument to a list
399
Georg Brandlb926ebb2009-09-17 17:14:04 +0000400``"count"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000401 increment a counter by one
402
Georg Brandlb926ebb2009-09-17 17:14:04 +0000403``"callback"``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000404 call a specified function
405
406These are covered in section :ref:`optparse-reference-guide`, Reference Guide
407and section :ref:`optparse-option-callbacks`.
408
409
410.. _optparse-default-values:
411
412Default values
413^^^^^^^^^^^^^^
414
415All of the above examples involve setting some variable (the "destination") when
416certain command-line options are seen. What happens if those options are never
417seen? Since we didn't supply any defaults, they are all set to ``None``. This
418is usually fine, but sometimes you want more control. :mod:`optparse` lets you
419supply a default value for each destination, which is assigned before the
420command line is parsed.
421
422First, consider the verbose/quiet example. If we want :mod:`optparse` to set
423``verbose`` to ``True`` unless ``"-q"`` is seen, then we can do this::
424
425 parser.add_option("-v", action="store_true", dest="verbose", default=True)
426 parser.add_option("-q", action="store_false", dest="verbose")
427
428Since default values apply to the *destination* rather than to any particular
429option, and these two options happen to have the same destination, this is
430exactly equivalent::
431
432 parser.add_option("-v", action="store_true", dest="verbose")
433 parser.add_option("-q", action="store_false", dest="verbose", default=True)
434
435Consider this::
436
437 parser.add_option("-v", action="store_true", dest="verbose", default=False)
438 parser.add_option("-q", action="store_false", dest="verbose", default=True)
439
440Again, the default value for ``verbose`` will be ``True``: the last default
441value supplied for any particular destination is the one that counts.
442
443A clearer way to specify default values is the :meth:`set_defaults` method of
444OptionParser, which you can call at any time before calling :meth:`parse_args`::
445
446 parser.set_defaults(verbose=True)
447 parser.add_option(...)
448 (options, args) = parser.parse_args()
449
450As before, the last value specified for a given option destination is the one
451that counts. For clarity, try to use one method or the other of setting default
452values, not both.
453
454
455.. _optparse-generating-help:
456
457Generating help
458^^^^^^^^^^^^^^^
459
460:mod:`optparse`'s ability to generate help and usage text automatically is
461useful for creating user-friendly command-line interfaces. All you have to do
Georg Brandlb926ebb2009-09-17 17:14:04 +0000462is supply a :attr:`~Option.help` value for each option, and optionally a short
463usage message for your whole program. Here's an OptionParser populated with
Georg Brandl8ec7f652007-08-15 14:28:01 +0000464user-friendly (documented) options::
465
466 usage = "usage: %prog [options] arg1 arg2"
467 parser = OptionParser(usage=usage)
468 parser.add_option("-v", "--verbose",
469 action="store_true", dest="verbose", default=True,
470 help="make lots of noise [default]")
471 parser.add_option("-q", "--quiet",
Andrew M. Kuchling810f8072008-09-06 13:04:02 +0000472 action="store_false", dest="verbose",
Georg Brandl8ec7f652007-08-15 14:28:01 +0000473 help="be vewwy quiet (I'm hunting wabbits)")
474 parser.add_option("-f", "--filename",
Georg Brandld7226ff2009-09-16 13:06:22 +0000475 metavar="FILE", help="write output to FILE")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000476 parser.add_option("-m", "--mode",
477 default="intermediate",
478 help="interaction mode: novice, intermediate, "
479 "or expert [default: %default]")
480
481If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
482command-line, or if you just call :meth:`parser.print_help`, it prints the
483following to standard output::
484
485 usage: <yourscript> [options] arg1 arg2
486
487 options:
488 -h, --help show this help message and exit
489 -v, --verbose make lots of noise [default]
490 -q, --quiet be vewwy quiet (I'm hunting wabbits)
491 -f FILE, --filename=FILE
492 write output to FILE
493 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
494 expert [default: intermediate]
495
496(If the help output is triggered by a help option, :mod:`optparse` exits after
497printing the help text.)
498
499There's a lot going on here to help :mod:`optparse` generate the best possible
500help message:
501
502* the script defines its own usage message::
503
504 usage = "usage: %prog [options] arg1 arg2"
505
506 :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
Georg Brandlb926ebb2009-09-17 17:14:04 +0000507 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
508 is then printed before the detailed option help.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000509
510 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandlb926ebb2009-09-17 17:14:04 +0000511 default: ``"usage: %prog [options]"``, which is fine if your script doesn't
512 take any positional arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000513
514* every option defines a help string, and doesn't worry about line-wrapping---
515 :mod:`optparse` takes care of wrapping lines and making the help output look
516 good.
517
518* options that take a value indicate this fact in their automatically-generated
519 help message, e.g. for the "mode" option::
520
521 -m MODE, --mode=MODE
522
523 Here, "MODE" is called the meta-variable: it stands for the argument that the
524 user is expected to supply to :option:`-m`/:option:`--mode`. By default,
525 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandlb926ebb2009-09-17 17:14:04 +0000526 that for the meta-variable. Sometimes, that's not what you want---for
527 example, the :option:`--filename` option explicitly sets ``metavar="FILE"``,
528 resulting in this automatically-generated option description::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000529
530 -f FILE, --filename=FILE
531
Georg Brandlb926ebb2009-09-17 17:14:04 +0000532 This is important for more than just saving space, though: the manually
533 written help text uses the meta-variable "FILE" to clue the user in that
534 there's a connection between the semi-formal syntax "-f FILE" and the informal
535 semantic description "write output to FILE". This is a simple but effective
536 way to make your help text a lot clearer and more useful for end users.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000537
Georg Brandl799b3722008-03-25 08:39:10 +0000538.. versionadded:: 2.4
539 Options that have a default value can include ``%default`` in the help
540 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
541 default value. If an option has no default value (or the default value is
542 ``None``), ``%default`` expands to ``none``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000543
Georg Brandlb926ebb2009-09-17 17:14:04 +0000544When dealing with many options, it is convenient to group these options for
545better help output. An :class:`OptionParser` can contain several option groups,
546each of which can contain several options.
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000547
Georg Brandlb926ebb2009-09-17 17:14:04 +0000548Continuing with the parser defined above, adding an :class:`OptionGroup` to a
549parser is easy::
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000550
551 group = OptionGroup(parser, "Dangerous Options",
Georg Brandl7044b112009-01-03 21:04:55 +0000552 "Caution: use these options at your own risk. "
553 "It is believed that some of them bite.")
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000554 group.add_option("-g", action="store_true", help="Group option.")
555 parser.add_option_group(group)
556
557This would result in the following help output::
558
559 usage: [options] arg1 arg2
560
561 options:
562 -h, --help show this help message and exit
563 -v, --verbose make lots of noise [default]
564 -q, --quiet be vewwy quiet (I'm hunting wabbits)
565 -fFILE, --file=FILE write output to FILE
566 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
Georg Brandl7044b112009-01-03 21:04:55 +0000567 [default], 'expert'
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000568
569 Dangerous Options:
Georg Brandl7044b112009-01-03 21:04:55 +0000570 Caution: use of these options is at your own risk. It is believed that
571 some of them bite.
572 -g Group option.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000573
574.. _optparse-printing-version-string:
575
576Printing a version string
577^^^^^^^^^^^^^^^^^^^^^^^^^
578
579Similar to the brief usage string, :mod:`optparse` can also print a version
580string for your program. You have to supply the string as the ``version``
581argument to OptionParser::
582
583 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
584
585``"%prog"`` is expanded just like it is in ``usage``. Apart from that,
586``version`` can contain anything you like. When you supply it, :mod:`optparse`
587automatically adds a ``"--version"`` option to your parser. If it encounters
588this option on the command line, it expands your ``version`` string (by
589replacing ``"%prog"``), prints it to stdout, and exits.
590
591For example, if your script is called ``/usr/bin/foo``::
592
593 $ /usr/bin/foo --version
594 foo 1.0
595
596
597.. _optparse-how-optparse-handles-errors:
598
599How :mod:`optparse` handles errors
600^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
601
602There are two broad classes of errors that :mod:`optparse` has to worry about:
603programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandlb926ebb2009-09-17 17:14:04 +0000604calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
605option attributes, missing option attributes, etc. These are dealt with in the
606usual way: raise an exception (either :exc:`optparse.OptionError` or
607:exc:`TypeError`) and let the program crash.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000608
609Handling user errors is much more important, since they are guaranteed to happen
610no matter how stable your code is. :mod:`optparse` can automatically detect
611some user errors, such as bad option arguments (passing ``"-n 4x"`` where
612:option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
613of the command line, where :option:`-n` takes an argument of any type). Also,
Georg Brandlb926ebb2009-09-17 17:14:04 +0000614you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl8ec7f652007-08-15 14:28:01 +0000615condition::
616
617 (options, args) = parser.parse_args()
618 [...]
619 if options.a and options.b:
620 parser.error("options -a and -b are mutually exclusive")
621
622In either case, :mod:`optparse` handles the error the same way: it prints the
623program's usage message and an error message to standard error and exits with
624error status 2.
625
626Consider the first example above, where the user passes ``"4x"`` to an option
627that takes an integer::
628
629 $ /usr/bin/foo -n 4x
630 usage: foo [options]
631
632 foo: error: option -n: invalid integer value: '4x'
633
634Or, where the user fails to pass a value at all::
635
636 $ /usr/bin/foo -n
637 usage: foo [options]
638
639 foo: error: -n option requires an argument
640
641:mod:`optparse`\ -generated error messages take care always to mention the
642option involved in the error; be sure to do the same when calling
Georg Brandlb926ebb2009-09-17 17:14:04 +0000643:func:`OptionParser.error` from your application code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000644
Georg Brandl60c0be32008-06-13 13:26:54 +0000645If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Georg Brandl0c9eb432009-06-30 16:35:11 +0000646you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
647and/or :meth:`~OptionParser.error` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000648
649
650.. _optparse-putting-it-all-together:
651
652Putting it all together
653^^^^^^^^^^^^^^^^^^^^^^^
654
655Here's what :mod:`optparse`\ -based scripts usually look like::
656
657 from optparse import OptionParser
658 [...]
659 def main():
660 usage = "usage: %prog [options] arg"
661 parser = OptionParser(usage)
662 parser.add_option("-f", "--file", dest="filename",
663 help="read data from FILENAME")
664 parser.add_option("-v", "--verbose",
665 action="store_true", dest="verbose")
666 parser.add_option("-q", "--quiet",
667 action="store_false", dest="verbose")
668 [...]
669 (options, args) = parser.parse_args()
670 if len(args) != 1:
671 parser.error("incorrect number of arguments")
672 if options.verbose:
673 print "reading %s..." % options.filename
674 [...]
675
676 if __name__ == "__main__":
677 main()
678
Georg Brandl8ec7f652007-08-15 14:28:01 +0000679
680.. _optparse-reference-guide:
681
682Reference Guide
683---------------
684
685
686.. _optparse-creating-parser:
687
688Creating the parser
689^^^^^^^^^^^^^^^^^^^
690
Georg Brandlb926ebb2009-09-17 17:14:04 +0000691The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000692
Georg Brandlb926ebb2009-09-17 17:14:04 +0000693.. class:: OptionParser(...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694
Georg Brandlb926ebb2009-09-17 17:14:04 +0000695 The OptionParser constructor has no required arguments, but a number of
696 optional keyword arguments. You should always pass them as keyword
697 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000698
699 ``usage`` (default: ``"%prog [options]"``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000700 The usage summary to print when your program is run incorrectly or with a
701 help option. When :mod:`optparse` prints the usage string, it expands
702 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
703 passed that keyword argument). To suppress a usage message, pass the
704 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000705
706 ``option_list`` (default: ``[]``)
707 A list of Option objects to populate the parser with. The options in
Georg Brandlb926ebb2009-09-17 17:14:04 +0000708 ``option_list`` are added after any options in ``standard_option_list`` (a
709 class attribute that may be set by OptionParser subclasses), but before
710 any version or help options. Deprecated; use :meth:`add_option` after
711 creating the parser instead.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000712
713 ``option_class`` (default: optparse.Option)
714 Class to use when adding options to the parser in :meth:`add_option`.
715
716 ``version`` (default: ``None``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000717 A version string to print when the user supplies a version option. If you
718 supply a true value for ``version``, :mod:`optparse` automatically adds a
719 version option with the single option string ``"--version"``. The
720 substring ``"%prog"`` is expanded the same as for ``usage``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000721
722 ``conflict_handler`` (default: ``"error"``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000723 Specifies what to do when options with conflicting option strings are
724 added to the parser; see section
725 :ref:`optparse-conflicts-between-options`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000726
727 ``description`` (default: ``None``)
Georg Brandlb926ebb2009-09-17 17:14:04 +0000728 A paragraph of text giving a brief overview of your program.
729 :mod:`optparse` reformats this paragraph to fit the current terminal width
730 and prints it when the user requests help (after ``usage``, but before the
731 list of options).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000732
Georg Brandlb926ebb2009-09-17 17:14:04 +0000733 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
734 An instance of optparse.HelpFormatter that will be used for printing help
735 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000736 IndentedHelpFormatter and TitledHelpFormatter.
737
738 ``add_help_option`` (default: ``True``)
739 If true, :mod:`optparse` will add a help option (with option strings ``"-h"``
740 and ``"--help"``) to the parser.
741
742 ``prog``
743 The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
744 instead of ``os.path.basename(sys.argv[0])``.
745
746
747
748.. _optparse-populating-parser:
749
750Populating the parser
751^^^^^^^^^^^^^^^^^^^^^
752
753There are several ways to populate the parser with options. The preferred way
Georg Brandlb926ebb2009-09-17 17:14:04 +0000754is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl8ec7f652007-08-15 14:28:01 +0000755:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
756
757* pass it an Option instance (as returned by :func:`make_option`)
758
759* pass it any combination of positional and keyword arguments that are
Georg Brandlb926ebb2009-09-17 17:14:04 +0000760 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
761 will create the Option instance for you
Georg Brandl8ec7f652007-08-15 14:28:01 +0000762
763The other alternative is to pass a list of pre-constructed Option instances to
764the OptionParser constructor, as in::
765
766 option_list = [
767 make_option("-f", "--filename",
768 action="store", type="string", dest="filename"),
769 make_option("-q", "--quiet",
770 action="store_false", dest="verbose"),
771 ]
772 parser = OptionParser(option_list=option_list)
773
774(:func:`make_option` is a factory function for creating Option instances;
775currently it is an alias for the Option constructor. A future version of
776:mod:`optparse` may split Option into several classes, and :func:`make_option`
777will pick the right class to instantiate. Do not instantiate Option directly.)
778
779
780.. _optparse-defining-options:
781
782Defining options
783^^^^^^^^^^^^^^^^
784
785Each Option instance represents a set of synonymous command-line option strings,
786e.g. :option:`-f` and :option:`--file`. You can specify any number of short or
787long option strings, but you must specify at least one overall option string.
788
Georg Brandlb926ebb2009-09-17 17:14:04 +0000789The canonical way to create an :class:`Option` instance is with the
790:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000791
Georg Brandlb926ebb2009-09-17 17:14:04 +0000792.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000793
Georg Brandlb926ebb2009-09-17 17:14:04 +0000794 To define an option with only a short option string::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000795
Georg Brandlb926ebb2009-09-17 17:14:04 +0000796 parser.add_option("-f", attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000797
Georg Brandlb926ebb2009-09-17 17:14:04 +0000798 And to define an option with only a long option string::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000799
Georg Brandlb926ebb2009-09-17 17:14:04 +0000800 parser.add_option("--foo", attr=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000801
Georg Brandlb926ebb2009-09-17 17:14:04 +0000802 The keyword arguments define attributes of the new Option object. The most
803 important option attribute is :attr:`~Option.action`, and it largely
804 determines which other attributes are relevant or required. If you pass
805 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
806 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000807
Georg Brandlb926ebb2009-09-17 17:14:04 +0000808 An option's *action* determines what :mod:`optparse` does when it encounters
809 this option on the command-line. The standard option actions hard-coded into
810 :mod:`optparse` are:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000811
Georg Brandlb926ebb2009-09-17 17:14:04 +0000812 ``"store"``
813 store this option's argument (default)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000814
Georg Brandlb926ebb2009-09-17 17:14:04 +0000815 ``"store_const"``
816 store a constant value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000817
Georg Brandlb926ebb2009-09-17 17:14:04 +0000818 ``"store_true"``
819 store a true value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000820
Georg Brandlb926ebb2009-09-17 17:14:04 +0000821 ``"store_false"``
822 store a false value
Georg Brandl8ec7f652007-08-15 14:28:01 +0000823
Georg Brandlb926ebb2009-09-17 17:14:04 +0000824 ``"append"``
825 append this option's argument to a list
Georg Brandl8ec7f652007-08-15 14:28:01 +0000826
Georg Brandlb926ebb2009-09-17 17:14:04 +0000827 ``"append_const"``
828 append a constant value to a list
Georg Brandl8ec7f652007-08-15 14:28:01 +0000829
Georg Brandlb926ebb2009-09-17 17:14:04 +0000830 ``"count"``
831 increment a counter by one
Georg Brandl8ec7f652007-08-15 14:28:01 +0000832
Georg Brandlb926ebb2009-09-17 17:14:04 +0000833 ``"callback"``
834 call a specified function
Georg Brandl8ec7f652007-08-15 14:28:01 +0000835
Georg Brandlb926ebb2009-09-17 17:14:04 +0000836 ``"help"``
837 print a usage message including all options and the documentation for them
Georg Brandl8ec7f652007-08-15 14:28:01 +0000838
Georg Brandlb926ebb2009-09-17 17:14:04 +0000839 (If you don't supply an action, the default is ``"store"``. For this action,
840 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
841 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000842
843As you can see, most actions involve storing or updating a value somewhere.
844:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandlb926ebb2009-09-17 17:14:04 +0000845``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl8ec7f652007-08-15 14:28:01 +0000846arguments (and various other values) are stored as attributes of this object,
Georg Brandlb926ebb2009-09-17 17:14:04 +0000847according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000848
Georg Brandlb926ebb2009-09-17 17:14:04 +0000849For example, when you call ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000850
851 parser.parse_args()
852
853one of the first things :mod:`optparse` does is create the ``options`` object::
854
855 options = Values()
856
Georg Brandlb926ebb2009-09-17 17:14:04 +0000857If one of the options in this parser is defined with ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000858
859 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
860
861and the command-line being parsed includes any of the following::
862
863 -ffoo
864 -f foo
865 --file=foo
866 --file foo
867
Georg Brandlb926ebb2009-09-17 17:14:04 +0000868then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000869
870 options.filename = "foo"
871
Georg Brandlb926ebb2009-09-17 17:14:04 +0000872The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
873as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
874one that makes sense for *all* options.
875
876
877.. _optparse-option-attributes:
878
879Option attributes
880^^^^^^^^^^^^^^^^^
881
882The following option attributes may be passed as keyword arguments to
883:meth:`OptionParser.add_option`. If you pass an option attribute that is not
884relevant to a particular option, or fail to pass a required option attribute,
885:mod:`optparse` raises :exc:`OptionError`.
886
887.. attribute:: Option.action
888
889 (default: ``"store"``)
890
891 Determines :mod:`optparse`'s behaviour when this option is seen on the
892 command line; the available options are documented :ref:`here
893 <optparse-standard-option-actions>`.
894
895.. attribute:: Option.type
896
897 (default: ``"string"``)
898
899 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
900 the available option types are documented :ref:`here
901 <optparse-standard-option-types>`.
902
903.. attribute:: Option.dest
904
905 (default: derived from option strings)
906
907 If the option's action implies writing or modifying a value somewhere, this
908 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
909 attribute of the ``options`` object that :mod:`optparse` builds as it parses
910 the command line.
911
912.. attribute:: Option.default
913
914 The value to use for this option's destination if the option is not seen on
915 the command line. See also :meth:`OptionParser.set_defaults`.
916
917.. attribute:: Option.nargs
918
919 (default: 1)
920
921 How many arguments of type :attr:`~Option.type` should be consumed when this
922 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
923 :attr:`~Option.dest`.
924
925.. attribute:: Option.const
926
927 For actions that store a constant value, the constant value to store.
928
929.. attribute:: Option.choices
930
931 For options of type ``"choice"``, the list of strings the user may choose
932 from.
933
934.. attribute:: Option.callback
935
936 For options with action ``"callback"``, the callable to call when this option
937 is seen. See section :ref:`optparse-option-callbacks` for detail on the
938 arguments passed to the callable.
939
940.. attribute:: Option.callback_args
941 Option.callback_kwargs
942
943 Additional positional and keyword arguments to pass to ``callback`` after the
944 four standard callback arguments.
945
946.. attribute:: Option.help
947
948 Help text to print for this option when listing all available options after
949 the user supplies a :attr:`~Option.help` option (such as ``"--help"``). If
950 no help text is supplied, the option will be listed without help text. To
951 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
952
953.. attribute:: Option.metavar
954
955 (default: derived from option strings)
956
957 Stand-in for the option argument(s) to use when printing help text. See
958 section :ref:`optparse-tutorial` for an example.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000959
960
961.. _optparse-standard-option-actions:
962
963Standard option actions
964^^^^^^^^^^^^^^^^^^^^^^^
965
966The various option actions all have slightly different requirements and effects.
967Most actions have several relevant option attributes which you may specify to
968guide :mod:`optparse`'s behaviour; a few have required attributes, which you
969must specify for any option using that action.
970
Georg Brandlb926ebb2009-09-17 17:14:04 +0000971* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
972 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000973
974 The option must be followed by an argument, which is converted to a value
Georg Brandlb926ebb2009-09-17 17:14:04 +0000975 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
976 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
977 command line; all will be converted according to :attr:`~Option.type` and
978 stored to :attr:`~Option.dest` as a tuple. See the
979 :ref:`optparse-standard-option-types` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000980
Georg Brandlb926ebb2009-09-17 17:14:04 +0000981 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
982 defaults to ``"choice"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000983
Georg Brandlb926ebb2009-09-17 17:14:04 +0000984 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000985
Georg Brandlb926ebb2009-09-17 17:14:04 +0000986 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
987 from the first long option string (e.g., ``"--foo-bar"`` implies
988 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
989 destination from the first short option string (e.g., ``"-f"`` implies ``f``).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000990
991 Example::
992
993 parser.add_option("-f")
994 parser.add_option("-p", type="float", nargs=3, dest="point")
995
Georg Brandlb926ebb2009-09-17 17:14:04 +0000996 As it parses the command line ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000997
998 -f foo.txt -p 1 -3.5 4 -fbar.txt
999
Georg Brandlb926ebb2009-09-17 17:14:04 +00001000 :mod:`optparse` will set ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001001
1002 options.f = "foo.txt"
1003 options.point = (1.0, -3.5, 4.0)
1004 options.f = "bar.txt"
1005
Georg Brandlb926ebb2009-09-17 17:14:04 +00001006* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1007 :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001008
Georg Brandlb926ebb2009-09-17 17:14:04 +00001009 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001010
1011 Example::
1012
1013 parser.add_option("-q", "--quiet",
1014 action="store_const", const=0, dest="verbose")
1015 parser.add_option("-v", "--verbose",
1016 action="store_const", const=1, dest="verbose")
1017 parser.add_option("--noisy",
1018 action="store_const", const=2, dest="verbose")
1019
1020 If ``"--noisy"`` is seen, :mod:`optparse` will set ::
1021
1022 options.verbose = 2
1023
Georg Brandlb926ebb2009-09-17 17:14:04 +00001024* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001025
Georg Brandlb926ebb2009-09-17 17:14:04 +00001026 A special case of ``"store_const"`` that stores a true value to
1027 :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001028
Georg Brandlb926ebb2009-09-17 17:14:04 +00001029* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001030
Georg Brandlb926ebb2009-09-17 17:14:04 +00001031 Like ``"store_true"``, but stores a false value.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001032
1033 Example::
1034
1035 parser.add_option("--clobber", action="store_true", dest="clobber")
1036 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1037
Georg Brandlb926ebb2009-09-17 17:14:04 +00001038* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1039 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001040
1041 The option must be followed by an argument, which is appended to the list in
Georg Brandlb926ebb2009-09-17 17:14:04 +00001042 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1043 supplied, an empty list is automatically created when :mod:`optparse` first
1044 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1045 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1046 is appended to :attr:`~Option.dest`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001047
Georg Brandlb926ebb2009-09-17 17:14:04 +00001048 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1049 for the ``"store"`` action.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001050
1051 Example::
1052
1053 parser.add_option("-t", "--tracks", action="append", type="int")
1054
1055 If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
1056 of::
1057
1058 options.tracks = []
1059 options.tracks.append(int("3"))
1060
1061 If, a little later on, ``"--tracks=4"`` is seen, it does::
1062
1063 options.tracks.append(int("4"))
1064
Georg Brandlb926ebb2009-09-17 17:14:04 +00001065* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1066 :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001067
Georg Brandlb926ebb2009-09-17 17:14:04 +00001068 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1069 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1070 ``None``, and an empty list is automatically created the first time the option
1071 is encountered.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001072
Georg Brandlb926ebb2009-09-17 17:14:04 +00001073* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001074
Georg Brandlb926ebb2009-09-17 17:14:04 +00001075 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1076 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1077 first time.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001078
1079 Example::
1080
1081 parser.add_option("-v", action="count", dest="verbosity")
1082
1083 The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
1084 equivalent of::
1085
1086 options.verbosity = 0
1087 options.verbosity += 1
1088
1089 Every subsequent occurrence of ``"-v"`` results in ::
1090
1091 options.verbosity += 1
1092
Georg Brandlb926ebb2009-09-17 17:14:04 +00001093* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1094 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1095 :attr:`~Option.callback_kwargs`]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001096
Georg Brandlb926ebb2009-09-17 17:14:04 +00001097 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001098
1099 func(option, opt_str, value, parser, *args, **kwargs)
1100
1101 See section :ref:`optparse-option-callbacks` for more detail.
1102
Georg Brandlb926ebb2009-09-17 17:14:04 +00001103* ``"help"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001104
Georg Brandlb926ebb2009-09-17 17:14:04 +00001105 Prints a complete help message for all the options in the current option
1106 parser. The help message is constructed from the ``usage`` string passed to
1107 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1108 option.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001109
Georg Brandlb926ebb2009-09-17 17:14:04 +00001110 If no :attr:`~Option.help` string is supplied for an option, it will still be
1111 listed in the help message. To omit an option entirely, use the special value
1112 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001113
Georg Brandlb926ebb2009-09-17 17:14:04 +00001114 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1115 OptionParsers, so you do not normally need to create one.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001116
1117 Example::
1118
1119 from optparse import OptionParser, SUPPRESS_HELP
1120
Georg Brandl718b2212009-09-16 13:11:06 +00001121 # usually, a help option is added automatically, but that can
1122 # be suppressed using the add_help_option argument
1123 parser = OptionParser(add_help_option=False)
1124
Georg Brandld7226ff2009-09-16 13:06:22 +00001125 parser.add_option("-h", "--help", action="help")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001126 parser.add_option("-v", action="store_true", dest="verbose",
1127 help="Be moderately verbose")
1128 parser.add_option("--file", dest="filename",
Georg Brandld7226ff2009-09-16 13:06:22 +00001129 help="Input file to read data from")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001130 parser.add_option("--secret", help=SUPPRESS_HELP)
1131
Georg Brandlb926ebb2009-09-17 17:14:04 +00001132 If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line,
1133 it will print something like the following help message to stdout (assuming
Georg Brandl8ec7f652007-08-15 14:28:01 +00001134 ``sys.argv[0]`` is ``"foo.py"``)::
1135
1136 usage: foo.py [options]
1137
1138 options:
1139 -h, --help Show this help message and exit
1140 -v Be moderately verbose
1141 --file=FILENAME Input file to read data from
1142
1143 After printing the help message, :mod:`optparse` terminates your process with
1144 ``sys.exit(0)``.
1145
Georg Brandlb926ebb2009-09-17 17:14:04 +00001146* ``"version"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001147
Georg Brandlb926ebb2009-09-17 17:14:04 +00001148 Prints the version number supplied to the OptionParser to stdout and exits.
1149 The version number is actually formatted and printed by the
1150 ``print_version()`` method of OptionParser. Generally only relevant if the
1151 ``version`` argument is supplied to the OptionParser constructor. As with
1152 :attr:`~Option.help` options, you will rarely create ``version`` options,
1153 since :mod:`optparse` automatically adds them when needed.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001154
1155
1156.. _optparse-standard-option-types:
1157
1158Standard option types
1159^^^^^^^^^^^^^^^^^^^^^
1160
Georg Brandlb926ebb2009-09-17 17:14:04 +00001161:mod:`optparse` has six built-in option types: ``"string"``, ``"int"``,
1162``"long"``, ``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1163option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001164
1165Arguments to string options are not checked or converted in any way: the text on
1166the command line is stored in the destination (or passed to the callback) as-is.
1167
Georg Brandlb926ebb2009-09-17 17:14:04 +00001168Integer arguments (type ``"int"`` or ``"long"``) are parsed as follows:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001169
1170* if the number starts with ``0x``, it is parsed as a hexadecimal number
1171
1172* if the number starts with ``0``, it is parsed as an octal number
1173
Georg Brandl97ca5832007-09-24 17:55:47 +00001174* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl8ec7f652007-08-15 14:28:01 +00001175
1176* otherwise, the number is parsed as a decimal number
1177
1178
Georg Brandlb926ebb2009-09-17 17:14:04 +00001179The conversion is done by calling either :func:`int` or :func:`long` with the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001180appropriate base (2, 8, 10, or 16). If this fails, so will :mod:`optparse`,
1181although with a more useful error message.
1182
Georg Brandlb926ebb2009-09-17 17:14:04 +00001183``"float"`` and ``"complex"`` option arguments are converted directly with
1184:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001185
Georg Brandlb926ebb2009-09-17 17:14:04 +00001186``"choice"`` options are a subtype of ``"string"`` options. The
1187:attr:`~Option.choices`` option attribute (a sequence of strings) defines the
1188set of allowed option arguments. :func:`optparse.check_choice` compares
1189user-supplied option arguments against this master list and raises
1190:exc:`OptionValueError` if an invalid string is given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001191
1192
1193.. _optparse-parsing-arguments:
1194
1195Parsing arguments
1196^^^^^^^^^^^^^^^^^
1197
1198The whole point of creating and populating an OptionParser is to call its
1199:meth:`parse_args` method::
1200
1201 (options, args) = parser.parse_args(args=None, values=None)
1202
1203where the input parameters are
1204
1205``args``
1206 the list of arguments to process (default: ``sys.argv[1:]``)
1207
1208``values``
Georg Brandl8514b852009-09-01 08:06:03 +00001209 object to store option arguments in (default: a new instance of
1210 :class:`optparse.Values`)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001211
1212and the return values are
1213
1214``options``
Georg Brandl8514b852009-09-01 08:06:03 +00001215 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl8ec7f652007-08-15 14:28:01 +00001216 instance created by :mod:`optparse`
1217
1218``args``
1219 the leftover positional arguments after all options have been processed
1220
1221The most common usage is to supply neither keyword argument. If you supply
Georg Brandlb926ebb2009-09-17 17:14:04 +00001222``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl8ec7f652007-08-15 14:28:01 +00001223for every option argument stored to an option destination) and returned by
1224:meth:`parse_args`.
1225
1226If :meth:`parse_args` encounters any errors in the argument list, it calls the
1227OptionParser's :meth:`error` method with an appropriate end-user error message.
1228This ultimately terminates your process with an exit status of 2 (the
1229traditional Unix exit status for command-line errors).
1230
1231
1232.. _optparse-querying-manipulating-option-parser:
1233
1234Querying and manipulating your option parser
1235^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1236
Georg Brandlb926ebb2009-09-17 17:14:04 +00001237The default behavior of the option parser can be customized slightly, and you
1238can also poke around your option parser and see what's there. OptionParser
1239provides several methods to help you out:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001240
Georg Brandlb926ebb2009-09-17 17:14:04 +00001241.. method:: OptionParser.disable_interspersed_args()
Georg Brandl7842a412009-09-17 16:26:06 +00001242
Georg Brandlb926ebb2009-09-17 17:14:04 +00001243 Set parsing to stop on the first non-option. For example, if ``"-a"`` and
1244 ``"-b"`` are both simple options that take no arguments, :mod:`optparse`
1245 normally accepts this syntax::
Georg Brandl7842a412009-09-17 16:26:06 +00001246
Georg Brandlb926ebb2009-09-17 17:14:04 +00001247 prog -a arg1 -b arg2
Georg Brandl7842a412009-09-17 16:26:06 +00001248
Georg Brandlb926ebb2009-09-17 17:14:04 +00001249 and treats it as equivalent to ::
Georg Brandl7842a412009-09-17 16:26:06 +00001250
Georg Brandlb926ebb2009-09-17 17:14:04 +00001251 prog -a -b arg1 arg2
Georg Brandl7842a412009-09-17 16:26:06 +00001252
Georg Brandlb926ebb2009-09-17 17:14:04 +00001253 To disable this feature, call :meth:`disable_interspersed_args`. This
1254 restores traditional Unix syntax, where option parsing stops with the first
1255 non-option argument.
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001256
Georg Brandlb926ebb2009-09-17 17:14:04 +00001257 Use this if you have a command processor which runs another command which has
1258 options of its own and you want to make sure these options don't get
1259 confused. For example, each command might have a different set of options.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001260
Georg Brandlb926ebb2009-09-17 17:14:04 +00001261.. method:: OptionParser.enable_interspersed_args()
1262
1263 Set parsing to not stop on the first non-option, allowing interspersing
1264 switches with command arguments. This is the default behavior.
1265
1266.. method:: OptionParser.get_option(opt_str)
1267
1268 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl8ec7f652007-08-15 14:28:01 +00001269 no options have that option string.
1270
Georg Brandlb926ebb2009-09-17 17:14:04 +00001271.. method:: OptionParser.has_option(opt_str)
1272
1273 Return true if the OptionParser has an option with option string *opt_str*
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001274 (e.g., ``"-q"`` or ``"--verbose"``).
1275
Georg Brandlb926ebb2009-09-17 17:14:04 +00001276.. method:: OptionParser.remove_option(opt_str)
1277
1278 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1279 option is removed. If that option provided any other option strings, all of
1280 those option strings become invalid. If *opt_str* does not occur in any
1281 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001282
1283
1284.. _optparse-conflicts-between-options:
1285
1286Conflicts between options
1287^^^^^^^^^^^^^^^^^^^^^^^^^
1288
1289If you're not careful, it's easy to define options with conflicting option
1290strings::
1291
1292 parser.add_option("-n", "--dry-run", ...)
1293 [...]
1294 parser.add_option("-n", "--noisy", ...)
1295
1296(This is particularly true if you've defined your own OptionParser subclass with
1297some standard options.)
1298
1299Every time you add an option, :mod:`optparse` checks for conflicts with existing
1300options. If it finds any, it invokes the current conflict-handling mechanism.
1301You can set the conflict-handling mechanism either in the constructor::
1302
1303 parser = OptionParser(..., conflict_handler=handler)
1304
1305or with a separate call::
1306
1307 parser.set_conflict_handler(handler)
1308
1309The available conflict handlers are:
1310
Georg Brandlb926ebb2009-09-17 17:14:04 +00001311 ``"error"`` (default)
1312 assume option conflicts are a programming error and raise
1313 :exc:`OptionConflictError`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001314
Georg Brandlb926ebb2009-09-17 17:14:04 +00001315 ``"resolve"``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001316 resolve option conflicts intelligently (see below)
1317
1318
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001319As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl8ec7f652007-08-15 14:28:01 +00001320intelligently and add conflicting options to it::
1321
1322 parser = OptionParser(conflict_handler="resolve")
1323 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1324 parser.add_option("-n", "--noisy", ..., help="be noisy")
1325
1326At this point, :mod:`optparse` detects that a previously-added option is already
1327using the ``"-n"`` option string. Since ``conflict_handler`` is ``"resolve"``,
1328it resolves the situation by removing ``"-n"`` from the earlier option's list of
1329option strings. Now ``"--dry-run"`` is the only way for the user to activate
1330that option. If the user asks for help, the help message will reflect that::
1331
1332 options:
1333 --dry-run do no harm
1334 [...]
1335 -n, --noisy be noisy
1336
1337It's possible to whittle away the option strings for a previously-added option
1338until there are none left, and the user has no way of invoking that option from
1339the command-line. In that case, :mod:`optparse` removes that option completely,
1340so it doesn't show up in help text or anywhere else. Carrying on with our
1341existing OptionParser::
1342
1343 parser.add_option("--dry-run", ..., help="new dry-run option")
1344
1345At this point, the original :option:`-n/--dry-run` option is no longer
1346accessible, so :mod:`optparse` removes it, leaving this help text::
1347
1348 options:
1349 [...]
1350 -n, --noisy be noisy
1351 --dry-run new dry-run option
1352
1353
1354.. _optparse-cleanup:
1355
1356Cleanup
1357^^^^^^^
1358
1359OptionParser instances have several cyclic references. This should not be a
1360problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandlb926ebb2009-09-17 17:14:04 +00001361references explicitly by calling :meth:`~OptionParser.destroy` on your
1362OptionParser once you are done with it. This is particularly useful in
1363long-running applications where large object graphs are reachable from your
1364OptionParser.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001365
1366
1367.. _optparse-other-methods:
1368
1369Other methods
1370^^^^^^^^^^^^^
1371
1372OptionParser supports several other public methods:
1373
Georg Brandlb926ebb2009-09-17 17:14:04 +00001374.. method:: OptionParser.set_usage(usage)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001375
Georg Brandlb926ebb2009-09-17 17:14:04 +00001376 Set the usage string according to the rules described above for the ``usage``
1377 constructor keyword argument. Passing ``None`` sets the default usage
1378 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001379
Georg Brandlb926ebb2009-09-17 17:14:04 +00001380.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001381
Georg Brandlb926ebb2009-09-17 17:14:04 +00001382 Set default values for several option destinations at once. Using
1383 :meth:`set_defaults` is the preferred way to set default values for options,
1384 since multiple options can share the same destination. For example, if
1385 several "mode" options all set the same destination, any one of them can set
1386 the default, and the last one wins::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001387
Georg Brandlb926ebb2009-09-17 17:14:04 +00001388 parser.add_option("--advanced", action="store_const",
1389 dest="mode", const="advanced",
1390 default="novice") # overridden below
1391 parser.add_option("--novice", action="store_const",
1392 dest="mode", const="novice",
1393 default="advanced") # overrides above setting
Georg Brandl8ec7f652007-08-15 14:28:01 +00001394
Georg Brandlb926ebb2009-09-17 17:14:04 +00001395 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001396
Georg Brandlb926ebb2009-09-17 17:14:04 +00001397 parser.set_defaults(mode="advanced")
1398 parser.add_option("--advanced", action="store_const",
1399 dest="mode", const="advanced")
1400 parser.add_option("--novice", action="store_const",
1401 dest="mode", const="novice")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001402
Georg Brandl8ec7f652007-08-15 14:28:01 +00001403
1404.. _optparse-option-callbacks:
1405
1406Option Callbacks
1407----------------
1408
1409When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1410needs, you have two choices: extend :mod:`optparse` or define a callback option.
1411Extending :mod:`optparse` is more general, but overkill for a lot of simple
1412cases. Quite often a simple callback is all you need.
1413
1414There are two steps to defining a callback option:
1415
Georg Brandlb926ebb2009-09-17 17:14:04 +00001416* define the option itself using the ``"callback"`` action
Georg Brandl8ec7f652007-08-15 14:28:01 +00001417
1418* write the callback; this is a function (or method) that takes at least four
1419 arguments, as described below
1420
1421
1422.. _optparse-defining-callback-option:
1423
1424Defining a callback option
1425^^^^^^^^^^^^^^^^^^^^^^^^^^
1426
1427As always, the easiest way to define a callback option is by using the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001428:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1429only option attribute you must specify is ``callback``, the function to call::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001430
1431 parser.add_option("-c", action="callback", callback=my_callback)
1432
1433``callback`` is a function (or other callable object), so you must have already
1434defined ``my_callback()`` when you create this callback option. In this simple
1435case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,
1436which usually means that the option takes no arguments---the mere presence of
1437:option:`-c` on the command-line is all it needs to know. In some
1438circumstances, though, you might want your callback to consume an arbitrary
1439number of command-line arguments. This is where writing callbacks gets tricky;
1440it's covered later in this section.
1441
1442:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandlb926ebb2009-09-17 17:14:04 +00001443will only pass additional arguments if you specify them via
1444:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1445minimal callback function signature is::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001446
1447 def my_callback(option, opt, value, parser):
1448
1449The four arguments to a callback are described below.
1450
1451There are several other option attributes that you can supply when you define a
1452callback option:
1453
Georg Brandlb926ebb2009-09-17 17:14:04 +00001454:attr:`~Option.type`
1455 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1456 instructs :mod:`optparse` to consume one argument and convert it to
1457 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1458 though, :mod:`optparse` passes it to your callback function.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001459
Georg Brandlb926ebb2009-09-17 17:14:04 +00001460:attr:`~Option.nargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001461 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandlb926ebb2009-09-17 17:14:04 +00001462 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1463 :attr:`~Option.type`. It then passes a tuple of converted values to your
1464 callback.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001465
Georg Brandlb926ebb2009-09-17 17:14:04 +00001466:attr:`~Option.callback_args`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001467 a tuple of extra positional arguments to pass to the callback
1468
Georg Brandlb926ebb2009-09-17 17:14:04 +00001469:attr:`~Option.callback_kwargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001470 a dictionary of extra keyword arguments to pass to the callback
1471
1472
1473.. _optparse-how-callbacks-called:
1474
1475How callbacks are called
1476^^^^^^^^^^^^^^^^^^^^^^^^
1477
1478All callbacks are called as follows::
1479
1480 func(option, opt_str, value, parser, *args, **kwargs)
1481
1482where
1483
1484``option``
1485 is the Option instance that's calling the callback
1486
1487``opt_str``
1488 is the option string seen on the command-line that's triggering the callback.
Georg Brandlb926ebb2009-09-17 17:14:04 +00001489 (If an abbreviated long option was used, ``opt_str`` will be the full,
1490 canonical option string---e.g. if the user puts ``"--foo"`` on the
1491 command-line as an abbreviation for ``"--foobar"``, then ``opt_str`` will be
1492 ``"--foobar"``.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001493
1494``value``
1495 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandlb926ebb2009-09-17 17:14:04 +00001496 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1497 the type implied by the option's type. If :attr:`~Option.type` for this option is
1498 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001499 > 1, ``value`` will be a tuple of values of the appropriate type.
1500
1501``parser``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001502 is the OptionParser instance driving the whole thing, mainly useful because
1503 you can access some other interesting data through its instance attributes:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001504
1505 ``parser.largs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001506 the current list of leftover arguments, ie. arguments that have been
1507 consumed but are neither options nor option arguments. Feel free to modify
1508 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1509 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001510
1511 ``parser.rargs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001512 the current list of remaining arguments, ie. with ``opt_str`` and
1513 ``value`` (if applicable) removed, and only the arguments following them
1514 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1515 arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001516
1517 ``parser.values``
1518 the object where option values are by default stored (an instance of
Georg Brandlb926ebb2009-09-17 17:14:04 +00001519 optparse.OptionValues). This lets callbacks use the same mechanism as the
1520 rest of :mod:`optparse` for storing option values; you don't need to mess
1521 around with globals or closures. You can also access or modify the
1522 value(s) of any options already encountered on the command-line.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001523
1524``args``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001525 is a tuple of arbitrary positional arguments supplied via the
1526 :attr:`~Option.callback_args` option attribute.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001527
1528``kwargs``
Georg Brandlb926ebb2009-09-17 17:14:04 +00001529 is a dictionary of arbitrary keyword arguments supplied via
1530 :attr:`~Option.callback_kwargs`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001531
1532
1533.. _optparse-raising-errors-in-callback:
1534
1535Raising errors in a callback
1536^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1537
Georg Brandlb926ebb2009-09-17 17:14:04 +00001538The callback function should raise :exc:`OptionValueError` if there are any
1539problems with the option or its argument(s). :mod:`optparse` catches this and
1540terminates the program, printing the error message you supply to stderr. Your
1541message should be clear, concise, accurate, and mention the option at fault.
1542Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001543
1544
1545.. _optparse-callback-example-1:
1546
1547Callback example 1: trivial callback
1548^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1549
1550Here's an example of a callback option that takes no arguments, and simply
1551records that the option was seen::
1552
1553 def record_foo_seen(option, opt_str, value, parser):
Georg Brandl253a29f2009-02-05 11:33:21 +00001554 parser.values.saw_foo = True
Georg Brandl8ec7f652007-08-15 14:28:01 +00001555
1556 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1557
Georg Brandlb926ebb2009-09-17 17:14:04 +00001558Of course, you could do that with the ``"store_true"`` action.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001559
1560
1561.. _optparse-callback-example-2:
1562
1563Callback example 2: check option order
1564^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1565
1566Here's a slightly more interesting example: record the fact that ``"-a"`` is
1567seen, but blow up if it comes after ``"-b"`` in the command-line. ::
1568
1569 def check_order(option, opt_str, value, parser):
1570 if parser.values.b:
1571 raise OptionValueError("can't use -a after -b")
1572 parser.values.a = 1
1573 [...]
1574 parser.add_option("-a", action="callback", callback=check_order)
1575 parser.add_option("-b", action="store_true", dest="b")
1576
1577
1578.. _optparse-callback-example-3:
1579
1580Callback example 3: check option order (generalized)
1581^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1582
1583If you want to re-use this callback for several similar options (set a flag, but
1584blow up if ``"-b"`` has already been seen), it needs a bit of work: the error
1585message and the flag that it sets must be generalized. ::
1586
1587 def check_order(option, opt_str, value, parser):
1588 if parser.values.b:
1589 raise OptionValueError("can't use %s after -b" % opt_str)
1590 setattr(parser.values, option.dest, 1)
1591 [...]
1592 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1593 parser.add_option("-b", action="store_true", dest="b")
1594 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1595
1596
1597.. _optparse-callback-example-4:
1598
1599Callback example 4: check arbitrary condition
1600^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1601
1602Of course, you could put any condition in there---you're not limited to checking
1603the values of already-defined options. For example, if you have options that
1604should not be called when the moon is full, all you have to do is this::
1605
1606 def check_moon(option, opt_str, value, parser):
1607 if is_moon_full():
1608 raise OptionValueError("%s option invalid when moon is full"
1609 % opt_str)
1610 setattr(parser.values, option.dest, 1)
1611 [...]
1612 parser.add_option("--foo",
1613 action="callback", callback=check_moon, dest="foo")
1614
1615(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1616
1617
1618.. _optparse-callback-example-5:
1619
1620Callback example 5: fixed arguments
1621^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1622
1623Things get slightly more interesting when you define callback options that take
1624a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandlb926ebb2009-09-17 17:14:04 +00001625is similar to defining a ``"store"`` or ``"append"`` option: if you define
1626:attr:`~Option.type`, then the option takes one argument that must be
1627convertible to that type; if you further define :attr:`~Option.nargs`, then the
1628option takes :attr:`~Option.nargs` arguments.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001629
Georg Brandlb926ebb2009-09-17 17:14:04 +00001630Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001631
1632 def store_value(option, opt_str, value, parser):
1633 setattr(parser.values, option.dest, value)
1634 [...]
1635 parser.add_option("--foo",
1636 action="callback", callback=store_value,
1637 type="int", nargs=3, dest="foo")
1638
1639Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1640them to integers for you; all you have to do is store them. (Or whatever;
1641obviously you don't need a callback for this example.)
1642
1643
1644.. _optparse-callback-example-6:
1645
1646Callback example 6: variable arguments
1647^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1648
1649Things get hairy when you want an option to take a variable number of arguments.
1650For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1651built-in capabilities for it. And you have to deal with certain intricacies of
1652conventional Unix command-line parsing that :mod:`optparse` normally handles for
1653you. In particular, callbacks should implement the conventional rules for bare
1654``"--"`` and ``"-"`` arguments:
1655
1656* either ``"--"`` or ``"-"`` can be option arguments
1657
1658* bare ``"--"`` (if not the argument to some option): halt command-line
1659 processing and discard the ``"--"``
1660
1661* bare ``"-"`` (if not the argument to some option): halt command-line
1662 processing but keep the ``"-"`` (append it to ``parser.largs``)
1663
1664If you want an option that takes a variable number of arguments, there are
1665several subtle, tricky issues to worry about. The exact implementation you
1666choose will be based on which trade-offs you're willing to make for your
1667application (which is why :mod:`optparse` doesn't support this sort of thing
1668directly).
1669
1670Nevertheless, here's a stab at a callback for an option with variable
1671arguments::
1672
Georg Brandl60b2e382008-12-15 09:07:39 +00001673 def vararg_callback(option, opt_str, value, parser):
1674 assert value is None
1675 value = []
Georg Brandl8ec7f652007-08-15 14:28:01 +00001676
Georg Brandl60b2e382008-12-15 09:07:39 +00001677 def floatable(str):
1678 try:
1679 float(str)
1680 return True
1681 except ValueError:
1682 return False
Georg Brandl8ec7f652007-08-15 14:28:01 +00001683
Georg Brandl60b2e382008-12-15 09:07:39 +00001684 for arg in parser.rargs:
1685 # stop on --foo like options
1686 if arg[:2] == "--" and len(arg) > 2:
1687 break
1688 # stop on -a, but not on -3 or -3.0
1689 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1690 break
1691 value.append(arg)
1692
1693 del parser.rargs[:len(value)]
Georg Brandl174fbe72009-02-05 10:30:57 +00001694 setattr(parser.values, option.dest, value)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001695
1696 [...]
Andrew M. Kuchling810f8072008-09-06 13:04:02 +00001697 parser.add_option("-c", "--callback", dest="vararg_attr",
Benjamin Petersonc8590942008-04-23 20:38:06 +00001698 action="callback", callback=vararg_callback)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001699
Georg Brandl8ec7f652007-08-15 14:28:01 +00001700
1701.. _optparse-extending-optparse:
1702
1703Extending :mod:`optparse`
1704-------------------------
1705
1706Since the two major controlling factors in how :mod:`optparse` interprets
1707command-line options are the action and type of each option, the most likely
1708direction of extension is to add new actions and new types.
1709
1710
1711.. _optparse-adding-new-types:
1712
1713Adding new types
1714^^^^^^^^^^^^^^^^
1715
1716To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandlb926ebb2009-09-17 17:14:04 +00001717:class:`Option` class. This class has a couple of attributes that define
1718:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001719
Georg Brandlb926ebb2009-09-17 17:14:04 +00001720.. attribute:: Option.TYPES
Georg Brandl8ec7f652007-08-15 14:28:01 +00001721
Georg Brandlb926ebb2009-09-17 17:14:04 +00001722 A tuple of type names; in your subclass, simply define a new tuple
1723 :attr:`TYPES` that builds on the standard one.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001724
Georg Brandlb926ebb2009-09-17 17:14:04 +00001725.. attribute:: Option.TYPE_CHECKER
Georg Brandl8ec7f652007-08-15 14:28:01 +00001726
Georg Brandlb926ebb2009-09-17 17:14:04 +00001727 A dictionary mapping type names to type-checking functions. A type-checking
1728 function has the following signature::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001729
Georg Brandlb926ebb2009-09-17 17:14:04 +00001730 def check_mytype(option, opt, value)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001731
Georg Brandlb926ebb2009-09-17 17:14:04 +00001732 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1733 (e.g., ``"-f"``), and ``value`` is the string from the command line that must
1734 be checked and converted to your desired type. ``check_mytype()`` should
1735 return an object of the hypothetical type ``mytype``. The value returned by
1736 a type-checking function will wind up in the OptionValues instance returned
1737 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1738 ``value`` parameter.
1739
1740 Your type-checking function should raise :exc:`OptionValueError` if it
1741 encounters any problems. :exc:`OptionValueError` takes a single string
1742 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1743 method, which in turn prepends the program name and the string ``"error:"``
1744 and prints everything to stderr before terminating the process.
1745
1746Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl8ec7f652007-08-15 14:28:01 +00001747parse Python-style complex numbers on the command line. (This is even sillier
1748than it used to be, because :mod:`optparse` 1.3 added built-in support for
1749complex numbers, but never mind.)
1750
1751First, the necessary imports::
1752
1753 from copy import copy
1754 from optparse import Option, OptionValueError
1755
1756You need to define your type-checker first, since it's referred to later (in the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001757:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001758
1759 def check_complex(option, opt, value):
1760 try:
1761 return complex(value)
1762 except ValueError:
1763 raise OptionValueError(
1764 "option %s: invalid complex value: %r" % (opt, value))
1765
1766Finally, the Option subclass::
1767
1768 class MyOption (Option):
1769 TYPES = Option.TYPES + ("complex",)
1770 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1771 TYPE_CHECKER["complex"] = check_complex
1772
1773(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandlb926ebb2009-09-17 17:14:04 +00001774up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1775Option class. This being Python, nothing stops you from doing that except good
1776manners and common sense.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001777
1778That's it! Now you can write a script that uses the new option type just like
1779any other :mod:`optparse`\ -based script, except you have to instruct your
1780OptionParser to use MyOption instead of Option::
1781
1782 parser = OptionParser(option_class=MyOption)
1783 parser.add_option("-c", type="complex")
1784
1785Alternately, you can build your own option list and pass it to OptionParser; if
1786you don't use :meth:`add_option` in the above way, you don't need to tell
1787OptionParser which option class to use::
1788
1789 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1790 parser = OptionParser(option_list=option_list)
1791
1792
1793.. _optparse-adding-new-actions:
1794
1795Adding new actions
1796^^^^^^^^^^^^^^^^^^
1797
1798Adding new actions is a bit trickier, because you have to understand that
1799:mod:`optparse` has a couple of classifications for actions:
1800
1801"store" actions
1802 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandlb926ebb2009-09-17 17:14:04 +00001803 current OptionValues instance; these options require a :attr:`~Option.dest`
1804 attribute to be supplied to the Option constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001805
1806"typed" actions
Georg Brandlb926ebb2009-09-17 17:14:04 +00001807 actions that take a value from the command line and expect it to be of a
1808 certain type; or rather, a string that can be converted to a certain type.
1809 These options require a :attr:`~Option.type` attribute to the Option
1810 constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001811
Georg Brandlb926ebb2009-09-17 17:14:04 +00001812These are overlapping sets: some default "store" actions are ``"store"``,
1813``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1814actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001815
1816When you add an action, you need to categorize it by listing it in at least one
1817of the following class attributes of Option (all are lists of strings):
1818
Georg Brandlb926ebb2009-09-17 17:14:04 +00001819.. attribute:: Option.ACTIONS
Georg Brandl8ec7f652007-08-15 14:28:01 +00001820
Georg Brandlb926ebb2009-09-17 17:14:04 +00001821 All actions must be listed in ACTIONS.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001822
Georg Brandlb926ebb2009-09-17 17:14:04 +00001823.. attribute:: Option.STORE_ACTIONS
Georg Brandl8ec7f652007-08-15 14:28:01 +00001824
Georg Brandlb926ebb2009-09-17 17:14:04 +00001825 "store" actions are additionally listed here.
1826
1827.. attribute:: Option.TYPED_ACTIONS
1828
1829 "typed" actions are additionally listed here.
1830
1831.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1832
1833 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl8ec7f652007-08-15 14:28:01 +00001834 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00001835 assigns the default type, ``"string"``, to options with no explicit type
1836 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001837
1838In order to actually implement your new action, you must override Option's
1839:meth:`take_action` method and add a case that recognizes your action.
1840
Georg Brandlb926ebb2009-09-17 17:14:04 +00001841For example, let's add an ``"extend"`` action. This is similar to the standard
1842``"append"`` action, but instead of taking a single value from the command-line
1843and appending it to an existing list, ``"extend"`` will take multiple values in
1844a single comma-delimited string, and extend an existing list with them. That
1845is, if ``"--names"`` is an ``"extend"`` option of type ``"string"``, the command
1846line ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001847
1848 --names=foo,bar --names blah --names ding,dong
1849
1850would result in a list ::
1851
1852 ["foo", "bar", "blah", "ding", "dong"]
1853
1854Again we define a subclass of Option::
1855
1856 class MyOption (Option):
1857
1858 ACTIONS = Option.ACTIONS + ("extend",)
1859 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1860 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1861 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1862
1863 def take_action(self, action, dest, opt, value, values, parser):
1864 if action == "extend":
1865 lvalue = value.split(",")
1866 values.ensure_value(dest, []).extend(lvalue)
1867 else:
1868 Option.take_action(
1869 self, action, dest, opt, value, values, parser)
1870
1871Features of note:
1872
Georg Brandlb926ebb2009-09-17 17:14:04 +00001873* ``"extend"`` both expects a value on the command-line and stores that value
1874 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1875 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001876
Georg Brandlb926ebb2009-09-17 17:14:04 +00001877* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1878 ``"extend"`` actions, we put the ``"extend"`` action in
1879 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001880
1881* :meth:`MyOption.take_action` implements just this one new action, and passes
1882 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandlb926ebb2009-09-17 17:14:04 +00001883 actions.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001884
Georg Brandlb926ebb2009-09-17 17:14:04 +00001885* ``values`` is an instance of the optparse_parser.Values class, which provides
1886 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1887 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl8ec7f652007-08-15 14:28:01 +00001888
1889 values.ensure_value(attr, value)
1890
1891 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandlb926ebb2009-09-17 17:14:04 +00001892 ensure_value() first sets it to ``value``, and then returns 'value. This is
1893 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
1894 of which accumulate data in a variable and expect that variable to be of a
1895 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl8ec7f652007-08-15 14:28:01 +00001896 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandlb926ebb2009-09-17 17:14:04 +00001897 about setting a default value for the option destinations in question; they
1898 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl8ec7f652007-08-15 14:28:01 +00001899 getting it right when it's needed.