blob: 4a6fa392d145aae5a1c40fd25aa9e5ae6110d345 [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
14``optparse`` is a more convenient, flexible, and powerful library for parsing
Mark Summerfieldffde3cf2008-09-08 14:45:37 +000015command-line options than the old :mod:`getopt` module. ``optparse`` uses a more declarative
Georg Brandl8ec7f652007-08-15 14:28:01 +000016style of command-line parsing: you create an instance of :class:`OptionParser`,
17populate it with options, and parse the command line. ``optparse`` allows users
18to specify options in the conventional GNU/POSIX syntax, and additionally
19generates usage and help messages for you.
20
Georg Brandl8ec7f652007-08-15 14:28:01 +000021Here's an example of using ``optparse`` in a simple script::
22
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
39As it parses the command line, ``optparse`` sets attributes of the ``options``
40object returned by :meth:`parse_args` based on user-supplied command-line
41values. When :meth:`parse_args` returns from parsing this command line,
42``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
43``False``. ``optparse`` supports both long and short options, allows short
44options 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
58and ``optparse`` will print out a brief summary of your script's options::
59
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
89 a string entered on the command-line, and passed by the shell to ``execl()`` or
90 ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
91 (``sys.argv[0]`` is the name of the program being executed). Unix shells also
92 use the term "word".
93
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 Brandl8ec7f652007-08-15 14:28:01 +0000100 an argument used to supply extra information to guide or customize the execution
101 of a program. There are many different syntaxes for options; the traditional
102 Unix syntax is a hyphen ("-") followed by a single letter, e.g. ``"-x"`` or
103 ``"-F"``. Also, traditional Unix syntax allows multiple options to be merged
104 into a single argument, e.g. ``"-x -F"`` is equivalent to ``"-xF"``. The GNU
105 project introduced ``"--"`` followed by a series of hyphen-separated words, e.g.
106 ``"--file"`` or ``"--dry-run"``. These are the only two option syntaxes
107 provided by :mod:`optparse`.
108
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
124 These option syntaxes are not supported by :mod:`optparse`, and they never will
125 be. This is deliberate: the first three are non-standard on any environment,
126 and the last only makes sense if you're exclusively targeting VMS, MS-DOS,
127 and/or Windows.
128
129option argument
130 an argument that follows an option, is closely associated with that option, and
131 is consumed from the argument list when that option is. With :mod:`optparse`,
132 option arguments may either be in a separate argument from their option::
133
134 -f foo
135 --file foo
136
137 or included in the same argument::
138
139 -ffoo
140 --file=foo
141
142 Typically, a given option either takes an argument or it doesn't. Lots of people
143 want an "optional option arguments" feature, meaning that some options will take
144 an argument if they see it, and won't if they don't. This is somewhat
145 controversial, because it makes parsing ambiguous: if ``"-a"`` takes an optional
146 argument and ``"-b"`` is another option entirely, how do we interpret ``"-ab"``?
147 Because of this ambiguity, :mod:`optparse` does not support this feature.
148
149positional argument
150 something leftover in the argument list after options have been parsed, i.e.
151 after options and their arguments have been parsed and removed from the argument
152 list.
153
154required option
155 an option that must be supplied on the command-line; note that the phrase
156 "required option" is self-contradictory in English. :mod:`optparse` doesn't
157 prevent you from implementing required options, but doesn't give you much help
158 at it either. See ``examples/required_1.py`` and ``examples/required_2.py`` in
159 the :mod:`optparse` source distribution for two ways to implement required
160 options with :mod:`optparse`.
161
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 Brandl9fa61bb2009-07-26 14:19:57 +0000289:attr:`action`, :attr:`!type`, :attr:`dest` (destination), and :attr:`help`. Of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000290these, :attr:`action` is the most fundamental.
291
292
293.. _optparse-understanding-option-actions:
294
295Understanding option actions
296^^^^^^^^^^^^^^^^^^^^^^^^^^^^
297
298Actions tell :mod:`optparse` what to do when it encounters an option on the
299command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
300adding new actions is an advanced topic covered in section
301:ref:`optparse-extending-optparse`. Most actions tell
302:mod:`optparse` to store a value in some variable---for example, take a string
303from the command line and store it in an attribute of ``options``.
304
305If you don't specify an option action, :mod:`optparse` defaults to ``store``.
306
307
308.. _optparse-store-action:
309
310The store action
311^^^^^^^^^^^^^^^^
312
313The most common option action is ``store``, which tells :mod:`optparse` to take
314the next argument (or the remainder of the current argument), ensure that it is
315of the correct type, and store it to your chosen destination.
316
317For example::
318
319 parser.add_option("-f", "--file",
320 action="store", type="string", dest="filename")
321
322Now let's make up a fake command line and ask :mod:`optparse` to parse it::
323
324 args = ["-f", "foo.txt"]
325 (options, args) = parser.parse_args(args)
326
327When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
328argument, ``"foo.txt"``, and stores it in ``options.filename``. So, after this
329call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
330
331Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
332Here's an option that expects an integer argument::
333
334 parser.add_option("-n", type="int", dest="num")
335
336Note that this option has no long option string, which is perfectly acceptable.
337Also, there's no explicit action, since the default is ``store``.
338
339Let's parse another fake command-line. This time, we'll jam the option argument
340right up against the option: since ``"-n42"`` (one argument) is equivalent to
341``"-n 42"`` (two arguments), the code ::
342
343 (options, args) = parser.parse_args(["-n42"])
344 print options.num
345
346will print ``"42"``.
347
348If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
349the fact that the default action is ``store``, that means our first example can
350be a lot shorter::
351
352 parser.add_option("-f", "--file", dest="filename")
353
354If you don't supply a destination, :mod:`optparse` figures out a sensible
355default from the option strings: if the first long option string is
356``"--foo-bar"``, then the default destination is ``foo_bar``. If there are no
357long option strings, :mod:`optparse` looks at the first short option string: the
358default destination for ``"-f"`` is ``f``.
359
360:mod:`optparse` also includes built-in ``long`` and ``complex`` types. Adding
361types is covered in section :ref:`optparse-extending-optparse`.
362
363
364.. _optparse-handling-boolean-options:
365
366Handling boolean (flag) options
367^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
368
369Flag options---set a variable to true or false when a particular option is seen
370---are quite common. :mod:`optparse` supports them with two separate actions,
371``store_true`` and ``store_false``. For example, you might have a ``verbose``
372flag that is turned on with ``"-v"`` and off with ``"-q"``::
373
374 parser.add_option("-v", action="store_true", dest="verbose")
375 parser.add_option("-q", action="store_false", dest="verbose")
376
377Here we have two different options with the same destination, which is perfectly
378OK. (It just means you have to be a bit careful when setting default values---
379see below.)
380
381When :mod:`optparse` encounters ``"-v"`` on the command line, it sets
382``options.verbose`` to ``True``; when it encounters ``"-q"``,
383``options.verbose`` is set to ``False``.
384
385
386.. _optparse-other-actions:
387
388Other actions
389^^^^^^^^^^^^^
390
391Some other actions supported by :mod:`optparse` are:
392
393``store_const``
394 store a constant value
395
396``append``
397 append this option's argument to a list
398
399``count``
400 increment a counter by one
401
402``callback``
403 call a specified function
404
405These are covered in section :ref:`optparse-reference-guide`, Reference Guide
406and section :ref:`optparse-option-callbacks`.
407
408
409.. _optparse-default-values:
410
411Default values
412^^^^^^^^^^^^^^
413
414All of the above examples involve setting some variable (the "destination") when
415certain command-line options are seen. What happens if those options are never
416seen? Since we didn't supply any defaults, they are all set to ``None``. This
417is usually fine, but sometimes you want more control. :mod:`optparse` lets you
418supply a default value for each destination, which is assigned before the
419command line is parsed.
420
421First, consider the verbose/quiet example. If we want :mod:`optparse` to set
422``verbose`` to ``True`` unless ``"-q"`` is seen, then we can do this::
423
424 parser.add_option("-v", action="store_true", dest="verbose", default=True)
425 parser.add_option("-q", action="store_false", dest="verbose")
426
427Since default values apply to the *destination* rather than to any particular
428option, and these two options happen to have the same destination, this is
429exactly equivalent::
430
431 parser.add_option("-v", action="store_true", dest="verbose")
432 parser.add_option("-q", action="store_false", dest="verbose", default=True)
433
434Consider this::
435
436 parser.add_option("-v", action="store_true", dest="verbose", default=False)
437 parser.add_option("-q", action="store_false", dest="verbose", default=True)
438
439Again, the default value for ``verbose`` will be ``True``: the last default
440value supplied for any particular destination is the one that counts.
441
442A clearer way to specify default values is the :meth:`set_defaults` method of
443OptionParser, which you can call at any time before calling :meth:`parse_args`::
444
445 parser.set_defaults(verbose=True)
446 parser.add_option(...)
447 (options, args) = parser.parse_args()
448
449As before, the last value specified for a given option destination is the one
450that counts. For clarity, try to use one method or the other of setting default
451values, not both.
452
453
454.. _optparse-generating-help:
455
456Generating help
457^^^^^^^^^^^^^^^
458
459:mod:`optparse`'s ability to generate help and usage text automatically is
460useful for creating user-friendly command-line interfaces. All you have to do
461is supply a :attr:`help` value for each option, and optionally a short usage
462message for your whole program. Here's an OptionParser populated with
463user-friendly (documented) options::
464
465 usage = "usage: %prog [options] arg1 arg2"
466 parser = OptionParser(usage=usage)
467 parser.add_option("-v", "--verbose",
468 action="store_true", dest="verbose", default=True,
469 help="make lots of noise [default]")
470 parser.add_option("-q", "--quiet",
Andrew M. Kuchling810f8072008-09-06 13:04:02 +0000471 action="store_false", dest="verbose",
Georg Brandl8ec7f652007-08-15 14:28:01 +0000472 help="be vewwy quiet (I'm hunting wabbits)")
473 parser.add_option("-f", "--filename",
Georg Brandld7226ff2009-09-16 13:06:22 +0000474 metavar="FILE", help="write output to FILE")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000475 parser.add_option("-m", "--mode",
476 default="intermediate",
477 help="interaction mode: novice, intermediate, "
478 "or expert [default: %default]")
479
480If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
481command-line, or if you just call :meth:`parser.print_help`, it prints the
482following to standard output::
483
484 usage: <yourscript> [options] arg1 arg2
485
486 options:
487 -h, --help show this help message and exit
488 -v, --verbose make lots of noise [default]
489 -q, --quiet be vewwy quiet (I'm hunting wabbits)
490 -f FILE, --filename=FILE
491 write output to FILE
492 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
493 expert [default: intermediate]
494
495(If the help output is triggered by a help option, :mod:`optparse` exits after
496printing the help text.)
497
498There's a lot going on here to help :mod:`optparse` generate the best possible
499help message:
500
501* the script defines its own usage message::
502
503 usage = "usage: %prog [options] arg1 arg2"
504
505 :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
506 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string is
507 then printed before the detailed option help.
508
509 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
510 default: ``"usage: %prog [options]"``, which is fine if your script doesn't take
511 any positional arguments.
512
513* every option defines a help string, and doesn't worry about line-wrapping---
514 :mod:`optparse` takes care of wrapping lines and making the help output look
515 good.
516
517* options that take a value indicate this fact in their automatically-generated
518 help message, e.g. for the "mode" option::
519
520 -m MODE, --mode=MODE
521
522 Here, "MODE" is called the meta-variable: it stands for the argument that the
523 user is expected to supply to :option:`-m`/:option:`--mode`. By default,
524 :mod:`optparse` converts the destination variable name to uppercase and uses
525 that for the meta-variable. Sometimes, that's not what you want---for example,
526 the :option:`--filename` option explicitly sets ``metavar="FILE"``, resulting in
527 this automatically-generated option description::
528
529 -f FILE, --filename=FILE
530
531 This is important for more than just saving space, though: the manually written
532 help text uses the meta-variable "FILE" to clue the user in that there's a
533 connection between the semi-formal syntax "-f FILE" and the informal semantic
534 description "write output to FILE". This is a simple but effective way to make
535 your help text a lot clearer and more useful for end users.
536
Georg Brandl799b3722008-03-25 08:39:10 +0000537.. versionadded:: 2.4
538 Options that have a default value can include ``%default`` in the help
539 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
540 default value. If an option has no default value (or the default value is
541 ``None``), ``%default`` expands to ``none``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000542
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000543When dealing with many options, it is convenient to group these
544options for better help output. An :class:`OptionParser` can contain
545several option groups, each of which can contain several options.
546
547Continuing with the parser defined above, adding an
548:class:`OptionGroup` to a parser is easy::
549
550 group = OptionGroup(parser, "Dangerous Options",
Georg Brandl7044b112009-01-03 21:04:55 +0000551 "Caution: use these options at your own risk. "
552 "It is believed that some of them bite.")
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000553 group.add_option("-g", action="store_true", help="Group option.")
554 parser.add_option_group(group)
555
556This would result in the following help output::
557
558 usage: [options] arg1 arg2
559
560 options:
561 -h, --help show this help message and exit
562 -v, --verbose make lots of noise [default]
563 -q, --quiet be vewwy quiet (I'm hunting wabbits)
564 -fFILE, --file=FILE write output to FILE
565 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
Georg Brandl7044b112009-01-03 21:04:55 +0000566 [default], 'expert'
Andrew M. Kuchling8b506e72008-01-19 21:00:38 +0000567
568 Dangerous Options:
Georg Brandl7044b112009-01-03 21:04:55 +0000569 Caution: use of these options is at your own risk. It is believed that
570 some of them bite.
571 -g Group option.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000572
573.. _optparse-printing-version-string:
574
575Printing a version string
576^^^^^^^^^^^^^^^^^^^^^^^^^
577
578Similar to the brief usage string, :mod:`optparse` can also print a version
579string for your program. You have to supply the string as the ``version``
580argument to OptionParser::
581
582 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
583
584``"%prog"`` is expanded just like it is in ``usage``. Apart from that,
585``version`` can contain anything you like. When you supply it, :mod:`optparse`
586automatically adds a ``"--version"`` option to your parser. If it encounters
587this option on the command line, it expands your ``version`` string (by
588replacing ``"%prog"``), prints it to stdout, and exits.
589
590For example, if your script is called ``/usr/bin/foo``::
591
592 $ /usr/bin/foo --version
593 foo 1.0
594
595
596.. _optparse-how-optparse-handles-errors:
597
598How :mod:`optparse` handles errors
599^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
600
601There are two broad classes of errors that :mod:`optparse` has to worry about:
602programmer errors and user errors. Programmer errors are usually erroneous
603calls to ``parser.add_option()``, e.g. invalid option strings, unknown option
604attributes, missing option attributes, etc. These are dealt with in the usual
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +0000605way: raise an exception (either ``optparse.OptionError`` or :exc:`TypeError`) and
Georg Brandl8ec7f652007-08-15 14:28:01 +0000606let the program crash.
607
608Handling user errors is much more important, since they are guaranteed to happen
609no matter how stable your code is. :mod:`optparse` can automatically detect
610some user errors, such as bad option arguments (passing ``"-n 4x"`` where
611:option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
612of the command line, where :option:`-n` takes an argument of any type). Also,
613you can call ``parser.error()`` to signal an application-defined error
614condition::
615
616 (options, args) = parser.parse_args()
617 [...]
618 if options.a and options.b:
619 parser.error("options -a and -b are mutually exclusive")
620
621In either case, :mod:`optparse` handles the error the same way: it prints the
622program's usage message and an error message to standard error and exits with
623error status 2.
624
625Consider the first example above, where the user passes ``"4x"`` to an option
626that takes an integer::
627
628 $ /usr/bin/foo -n 4x
629 usage: foo [options]
630
631 foo: error: option -n: invalid integer value: '4x'
632
633Or, where the user fails to pass a value at all::
634
635 $ /usr/bin/foo -n
636 usage: foo [options]
637
638 foo: error: -n option requires an argument
639
640:mod:`optparse`\ -generated error messages take care always to mention the
641option involved in the error; be sure to do the same when calling
642``parser.error()`` from your application code.
643
Georg Brandl60c0be32008-06-13 13:26:54 +0000644If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Georg Brandl0c9eb432009-06-30 16:35:11 +0000645you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
646and/or :meth:`~OptionParser.error` methods.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000647
648
649.. _optparse-putting-it-all-together:
650
651Putting it all together
652^^^^^^^^^^^^^^^^^^^^^^^
653
654Here's what :mod:`optparse`\ -based scripts usually look like::
655
656 from optparse import OptionParser
657 [...]
658 def main():
659 usage = "usage: %prog [options] arg"
660 parser = OptionParser(usage)
661 parser.add_option("-f", "--file", dest="filename",
662 help="read data from FILENAME")
663 parser.add_option("-v", "--verbose",
664 action="store_true", dest="verbose")
665 parser.add_option("-q", "--quiet",
666 action="store_false", dest="verbose")
667 [...]
668 (options, args) = parser.parse_args()
669 if len(args) != 1:
670 parser.error("incorrect number of arguments")
671 if options.verbose:
672 print "reading %s..." % options.filename
673 [...]
674
675 if __name__ == "__main__":
676 main()
677
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678
679.. _optparse-reference-guide:
680
681Reference Guide
682---------------
683
684
685.. _optparse-creating-parser:
686
687Creating the parser
688^^^^^^^^^^^^^^^^^^^
689
690The first step in using :mod:`optparse` is to create an OptionParser instance::
691
692 parser = OptionParser(...)
693
694The OptionParser constructor has no required arguments, but a number of optional
695keyword arguments. You should always pass them as keyword arguments, i.e. do
696not rely on the order in which the arguments are declared.
697
698 ``usage`` (default: ``"%prog [options]"``)
699 The usage summary to print when your program is run incorrectly or with a help
700 option. When :mod:`optparse` prints the usage string, it expands ``%prog`` to
701 ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you passed that keyword
702 argument). To suppress a usage message, pass the special value
703 ``optparse.SUPPRESS_USAGE``.
704
705 ``option_list`` (default: ``[]``)
706 A list of Option objects to populate the parser with. The options in
707 ``option_list`` are added after any options in ``standard_option_list`` (a class
708 attribute that may be set by OptionParser subclasses), but before any version or
709 help options. Deprecated; use :meth:`add_option` after creating the parser
710 instead.
711
712 ``option_class`` (default: optparse.Option)
713 Class to use when adding options to the parser in :meth:`add_option`.
714
715 ``version`` (default: ``None``)
716 A version string to print when the user supplies a version option. If you supply
717 a true value for ``version``, :mod:`optparse` automatically adds a version
718 option with the single option string ``"--version"``. The substring ``"%prog"``
719 is expanded the same as for ``usage``.
720
721 ``conflict_handler`` (default: ``"error"``)
722 Specifies what to do when options with conflicting option strings are added to
723 the parser; see section :ref:`optparse-conflicts-between-options`.
724
725 ``description`` (default: ``None``)
726 A paragraph of text giving a brief overview of your program. :mod:`optparse`
727 reformats this paragraph to fit the current terminal width and prints it when
728 the user requests help (after ``usage``, but before the list of options).
729
730 ``formatter`` (default: a new IndentedHelpFormatter)
731 An instance of optparse.HelpFormatter that will be used for printing help text.
732 :mod:`optparse` provides two concrete classes for this purpose:
733 IndentedHelpFormatter and TitledHelpFormatter.
734
735 ``add_help_option`` (default: ``True``)
736 If true, :mod:`optparse` will add a help option (with option strings ``"-h"``
737 and ``"--help"``) to the parser.
738
739 ``prog``
740 The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
741 instead of ``os.path.basename(sys.argv[0])``.
742
743
744
745.. _optparse-populating-parser:
746
747Populating the parser
748^^^^^^^^^^^^^^^^^^^^^
749
750There are several ways to populate the parser with options. The preferred way
751is by using ``OptionParser.add_option()``, as shown in section
752:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
753
754* pass it an Option instance (as returned by :func:`make_option`)
755
756* pass it any combination of positional and keyword arguments that are
757 acceptable to :func:`make_option` (i.e., to the Option constructor), and it will
758 create the Option instance for you
759
760The other alternative is to pass a list of pre-constructed Option instances to
761the OptionParser constructor, as in::
762
763 option_list = [
764 make_option("-f", "--filename",
765 action="store", type="string", dest="filename"),
766 make_option("-q", "--quiet",
767 action="store_false", dest="verbose"),
768 ]
769 parser = OptionParser(option_list=option_list)
770
771(:func:`make_option` is a factory function for creating Option instances;
772currently it is an alias for the Option constructor. A future version of
773:mod:`optparse` may split Option into several classes, and :func:`make_option`
774will pick the right class to instantiate. Do not instantiate Option directly.)
775
776
777.. _optparse-defining-options:
778
779Defining options
780^^^^^^^^^^^^^^^^
781
782Each Option instance represents a set of synonymous command-line option strings,
783e.g. :option:`-f` and :option:`--file`. You can specify any number of short or
784long option strings, but you must specify at least one overall option string.
785
786The canonical way to create an Option instance is with the :meth:`add_option`
787method of :class:`OptionParser`::
788
789 parser.add_option(opt_str[, ...], attr=value, ...)
790
791To define an option with only a short option string::
792
793 parser.add_option("-f", attr=value, ...)
794
795And to define an option with only a long option string::
796
797 parser.add_option("--foo", attr=value, ...)
798
799The keyword arguments define attributes of the new Option object. The most
800important option attribute is :attr:`action`, and it largely determines which
801other attributes are relevant or required. If you pass irrelevant option
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000802attributes, or fail to pass required ones, :mod:`optparse` raises an
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +0000803:exc:`OptionError` exception explaining your mistake.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000804
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +0000805An option's *action* determines what :mod:`optparse` does when it encounters
Georg Brandl8ec7f652007-08-15 14:28:01 +0000806this option on the command-line. The standard option actions hard-coded into
807:mod:`optparse` are:
808
Georg Brandlbc3777d2009-09-17 10:23:02 +0000809``'store'``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000810 store this option's argument (default)
811
Georg Brandlbc3777d2009-09-17 10:23:02 +0000812``'store_const'``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000813 store a constant value
814
Georg Brandlbc3777d2009-09-17 10:23:02 +0000815``'store_true'``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000816 store a true value
817
Georg Brandlbc3777d2009-09-17 10:23:02 +0000818``'store_false'``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000819 store a false value
820
Georg Brandlbc3777d2009-09-17 10:23:02 +0000821``'append'``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000822 append this option's argument to a list
823
Georg Brandlbc3777d2009-09-17 10:23:02 +0000824``'append_const'``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000825 append a constant value to a list
826
Georg Brandlbc3777d2009-09-17 10:23:02 +0000827``'count'``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000828 increment a counter by one
829
Georg Brandlbc3777d2009-09-17 10:23:02 +0000830``'callback'``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000831 call a specified function
832
Georg Brandlbc3777d2009-09-17 10:23:02 +0000833``'help'``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000834 print a usage message including all options and the documentation for them
835
836(If you don't supply an action, the default is ``store``. For this action, you
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000837may also supply :attr:`!type` and :attr:`dest` option attributes; see below.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000838
839As you can see, most actions involve storing or updating a value somewhere.
840:mod:`optparse` always creates a special object for this, conventionally called
841``options`` (it happens to be an instance of ``optparse.Values``). Option
842arguments (and various other values) are stored as attributes of this object,
843according to the :attr:`dest` (destination) option attribute.
844
845For example, when you call ::
846
847 parser.parse_args()
848
849one of the first things :mod:`optparse` does is create the ``options`` object::
850
851 options = Values()
852
853If one of the options in this parser is defined with ::
854
855 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
856
857and the command-line being parsed includes any of the following::
858
859 -ffoo
860 -f foo
861 --file=foo
862 --file foo
863
864then :mod:`optparse`, on seeing this option, will do the equivalent of ::
865
866 options.filename = "foo"
867
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000868The :attr:`!type` and :attr:`dest` option attributes are almost as important as
Georg Brandl8ec7f652007-08-15 14:28:01 +0000869:attr:`action`, but :attr:`action` is the only one that makes sense for *all*
870options.
871
872
873.. _optparse-standard-option-actions:
874
875Standard option actions
876^^^^^^^^^^^^^^^^^^^^^^^
877
878The various option actions all have slightly different requirements and effects.
879Most actions have several relevant option attributes which you may specify to
880guide :mod:`optparse`'s behaviour; a few have required attributes, which you
881must specify for any option using that action.
882
Georg Brandlbc3777d2009-09-17 10:23:02 +0000883* ``'store'`` [relevant: :attr:`!type`, :attr:`dest`, ``nargs``, ``choices``]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000884
885 The option must be followed by an argument, which is converted to a value
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000886 according to :attr:`!type` and stored in :attr:`dest`. If ``nargs`` > 1,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000887 multiple arguments will be consumed from the command line; all will be converted
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000888 according to :attr:`!type` and stored to :attr:`dest` as a tuple. See the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000889 "Option types" section below.
890
891 If ``choices`` is supplied (a list or tuple of strings), the type defaults to
Georg Brandlbc3777d2009-09-17 10:23:02 +0000892 ``'choice'``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000893
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000894 If :attr:`!type` is not supplied, it defaults to ``string``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000895
896 If :attr:`dest` is not supplied, :mod:`optparse` derives a destination from the
897 first long option string (e.g., ``"--foo-bar"`` implies ``foo_bar``). If there
898 are no long option strings, :mod:`optparse` derives a destination from the first
899 short option string (e.g., ``"-f"`` implies ``f``).
900
901 Example::
902
903 parser.add_option("-f")
904 parser.add_option("-p", type="float", nargs=3, dest="point")
905
906 As it parses the command line ::
907
908 -f foo.txt -p 1 -3.5 4 -fbar.txt
909
910 :mod:`optparse` will set ::
911
912 options.f = "foo.txt"
913 options.point = (1.0, -3.5, 4.0)
914 options.f = "bar.txt"
915
Georg Brandlbc3777d2009-09-17 10:23:02 +0000916* ``'store_const'`` [required: ``const``; relevant: :attr:`dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000917
918 The value ``const`` is stored in :attr:`dest`.
919
920 Example::
921
922 parser.add_option("-q", "--quiet",
923 action="store_const", const=0, dest="verbose")
924 parser.add_option("-v", "--verbose",
925 action="store_const", const=1, dest="verbose")
926 parser.add_option("--noisy",
927 action="store_const", const=2, dest="verbose")
928
929 If ``"--noisy"`` is seen, :mod:`optparse` will set ::
930
931 options.verbose = 2
932
Georg Brandlbc3777d2009-09-17 10:23:02 +0000933* ``'store_true'`` [relevant: :attr:`dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000934
935 A special case of ``store_const`` that stores a true value to :attr:`dest`.
936
Georg Brandlbc3777d2009-09-17 10:23:02 +0000937* ``'store_false'`` [relevant: :attr:`dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000938
939 Like ``store_true``, but stores a false value.
940
941 Example::
942
943 parser.add_option("--clobber", action="store_true", dest="clobber")
944 parser.add_option("--no-clobber", action="store_false", dest="clobber")
945
Georg Brandlbc3777d2009-09-17 10:23:02 +0000946* ``'append'`` [relevant: :attr:`!type`, :attr:`dest`, ``nargs``, ``choices``]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000947
948 The option must be followed by an argument, which is appended to the list in
949 :attr:`dest`. If no default value for :attr:`dest` is supplied, an empty list
950 is automatically created when :mod:`optparse` first encounters this option on
951 the command-line. If ``nargs`` > 1, multiple arguments are consumed, and a
952 tuple of length ``nargs`` is appended to :attr:`dest`.
953
Georg Brandl9fa61bb2009-07-26 14:19:57 +0000954 The defaults for :attr:`!type` and :attr:`dest` are the same as for the ``store``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000955 action.
956
957 Example::
958
959 parser.add_option("-t", "--tracks", action="append", type="int")
960
961 If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
962 of::
963
964 options.tracks = []
965 options.tracks.append(int("3"))
966
967 If, a little later on, ``"--tracks=4"`` is seen, it does::
968
969 options.tracks.append(int("4"))
970
Georg Brandlbc3777d2009-09-17 10:23:02 +0000971* ``'append_const'`` [required: ``const``; relevant: :attr:`dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000972
973 Like ``store_const``, but the value ``const`` is appended to :attr:`dest`; as
Georg Brandl97ca5832007-09-24 17:55:47 +0000974 with ``append``, :attr:`dest` defaults to ``None``, and an empty list is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000975 automatically created the first time the option is encountered.
976
Georg Brandlbc3777d2009-09-17 10:23:02 +0000977* ``'count'`` [relevant: :attr:`dest`]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000978
979 Increment the integer stored at :attr:`dest`. If no default value is supplied,
980 :attr:`dest` is set to zero before being incremented the first time.
981
982 Example::
983
984 parser.add_option("-v", action="count", dest="verbosity")
985
986 The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
987 equivalent of::
988
989 options.verbosity = 0
990 options.verbosity += 1
991
992 Every subsequent occurrence of ``"-v"`` results in ::
993
994 options.verbosity += 1
995
Georg Brandlbc3777d2009-09-17 10:23:02 +0000996* ``'callback'`` [required: ``callback``; relevant: :attr:`!type`, ``nargs``,
997 ``'callback_args'``, ``callback_kwargs``]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000998
999 Call the function specified by ``callback``, which is called as ::
1000
1001 func(option, opt_str, value, parser, *args, **kwargs)
1002
1003 See section :ref:`optparse-option-callbacks` for more detail.
1004
Georg Brandlbc3777d2009-09-17 10:23:02 +00001005* ``'help'``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001006
1007 Prints a complete help message for all the options in the current option parser.
1008 The help message is constructed from the ``usage`` string passed to
1009 OptionParser's constructor and the :attr:`help` string passed to every option.
1010
1011 If no :attr:`help` string is supplied for an option, it will still be listed in
1012 the help message. To omit an option entirely, use the special value
1013 ``optparse.SUPPRESS_HELP``.
1014
1015 :mod:`optparse` automatically adds a :attr:`help` option to all OptionParsers,
1016 so you do not normally need to create one.
1017
1018 Example::
1019
1020 from optparse import OptionParser, SUPPRESS_HELP
1021
Georg Brandl718b2212009-09-16 13:11:06 +00001022 # usually, a help option is added automatically, but that can
1023 # be suppressed using the add_help_option argument
1024 parser = OptionParser(add_help_option=False)
1025
Georg Brandld7226ff2009-09-16 13:06:22 +00001026 parser.add_option("-h", "--help", action="help")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001027 parser.add_option("-v", action="store_true", dest="verbose",
1028 help="Be moderately verbose")
1029 parser.add_option("--file", dest="filename",
Georg Brandld7226ff2009-09-16 13:06:22 +00001030 help="Input file to read data from")
Georg Brandl8ec7f652007-08-15 14:28:01 +00001031 parser.add_option("--secret", help=SUPPRESS_HELP)
1032
1033 If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line, it
1034 will print something like the following help message to stdout (assuming
1035 ``sys.argv[0]`` is ``"foo.py"``)::
1036
1037 usage: foo.py [options]
1038
1039 options:
1040 -h, --help Show this help message and exit
1041 -v Be moderately verbose
1042 --file=FILENAME Input file to read data from
1043
1044 After printing the help message, :mod:`optparse` terminates your process with
1045 ``sys.exit(0)``.
1046
Georg Brandlbc3777d2009-09-17 10:23:02 +00001047* ``'version'``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001048
1049 Prints the version number supplied to the OptionParser to stdout and exits. The
1050 version number is actually formatted and printed by the ``print_version()``
1051 method of OptionParser. Generally only relevant if the ``version`` argument is
1052 supplied to the OptionParser constructor. As with :attr:`help` options, you
1053 will rarely create ``version`` options, since :mod:`optparse` automatically adds
1054 them when needed.
1055
1056
1057.. _optparse-option-attributes:
1058
1059Option attributes
1060^^^^^^^^^^^^^^^^^
1061
1062The following option attributes may be passed as keyword arguments to
1063``parser.add_option()``. If you pass an option attribute that is not relevant
1064to a particular option, or fail to pass a required option attribute,
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001065:mod:`optparse` raises :exc:`OptionError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001066
1067* :attr:`action` (default: ``"store"``)
1068
1069 Determines :mod:`optparse`'s behaviour when this option is seen on the command
1070 line; the available options are documented above.
1071
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001072* :attr:`!type` (default: ``"string"``)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001073
1074 The argument type expected by this option (e.g., ``"string"`` or ``"int"``); the
1075 available option types are documented below.
1076
1077* :attr:`dest` (default: derived from option strings)
1078
1079 If the option's action implies writing or modifying a value somewhere, this
1080 tells :mod:`optparse` where to write it: :attr:`dest` names an attribute of the
1081 ``options`` object that :mod:`optparse` builds as it parses the command line.
1082
Georg Brandl14315d62009-05-16 11:18:55 +00001083* ``default``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001084
1085 The value to use for this option's destination if the option is not seen on the
Georg Brandl14315d62009-05-16 11:18:55 +00001086 command line. See also ``parser.set_defaults()``.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001087
1088* ``nargs`` (default: 1)
1089
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001090 How many arguments of type :attr:`!type` should be consumed when this option is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001091 seen. If > 1, :mod:`optparse` will store a tuple of values to :attr:`dest`.
1092
1093* ``const``
1094
1095 For actions that store a constant value, the constant value to store.
1096
1097* ``choices``
1098
1099 For options of type ``"choice"``, the list of strings the user may choose from.
1100
1101* ``callback``
1102
1103 For options with action ``"callback"``, the callable to call when this option
1104 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1105 arguments passed to ``callable``.
1106
1107* ``callback_args``, ``callback_kwargs``
1108
1109 Additional positional and keyword arguments to pass to ``callback`` after the
1110 four standard callback arguments.
1111
1112* :attr:`help`
1113
1114 Help text to print for this option when listing all available options after the
1115 user supplies a :attr:`help` option (such as ``"--help"``). If no help text is
1116 supplied, the option will be listed without help text. To hide this option, use
1117 the special value ``SUPPRESS_HELP``.
1118
1119* ``metavar`` (default: derived from option strings)
1120
1121 Stand-in for the option argument(s) to use when printing help text. See section
1122 :ref:`optparse-tutorial` for an example.
1123
1124
1125.. _optparse-standard-option-types:
1126
1127Standard option types
1128^^^^^^^^^^^^^^^^^^^^^
1129
1130:mod:`optparse` has six built-in option types: ``string``, ``int``, ``long``,
1131``choice``, ``float`` and ``complex``. If you need to add new option types, see
1132section :ref:`optparse-extending-optparse`.
1133
1134Arguments to string options are not checked or converted in any way: the text on
1135the command line is stored in the destination (or passed to the callback) as-is.
1136
1137Integer arguments (type ``int`` or ``long``) are parsed as follows:
1138
1139* if the number starts with ``0x``, it is parsed as a hexadecimal number
1140
1141* if the number starts with ``0``, it is parsed as an octal number
1142
Georg Brandl97ca5832007-09-24 17:55:47 +00001143* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl8ec7f652007-08-15 14:28:01 +00001144
1145* otherwise, the number is parsed as a decimal number
1146
1147
1148The conversion is done by calling either ``int()`` or ``long()`` with the
1149appropriate base (2, 8, 10, or 16). If this fails, so will :mod:`optparse`,
1150although with a more useful error message.
1151
1152``float`` and ``complex`` option arguments are converted directly with
1153``float()`` and ``complex()``, with similar error-handling.
1154
1155``choice`` options are a subtype of ``string`` options. The ``choices`` option
1156attribute (a sequence of strings) defines the set of allowed option arguments.
1157``optparse.check_choice()`` compares user-supplied option arguments against this
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001158master list and raises :exc:`OptionValueError` if an invalid string is given.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001159
1160
1161.. _optparse-parsing-arguments:
1162
1163Parsing arguments
1164^^^^^^^^^^^^^^^^^
1165
1166The whole point of creating and populating an OptionParser is to call its
1167:meth:`parse_args` method::
1168
1169 (options, args) = parser.parse_args(args=None, values=None)
1170
1171where the input parameters are
1172
1173``args``
1174 the list of arguments to process (default: ``sys.argv[1:]``)
1175
1176``values``
Georg Brandl8514b852009-09-01 08:06:03 +00001177 object to store option arguments in (default: a new instance of
1178 :class:`optparse.Values`)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001179
1180and the return values are
1181
1182``options``
Georg Brandl8514b852009-09-01 08:06:03 +00001183 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl8ec7f652007-08-15 14:28:01 +00001184 instance created by :mod:`optparse`
1185
1186``args``
1187 the leftover positional arguments after all options have been processed
1188
1189The most common usage is to supply neither keyword argument. If you supply
Georg Brandl8514b852009-09-01 08:06:03 +00001190``values``, it will be modified with repeated ``setattr()`` calls (roughly one
Georg Brandl8ec7f652007-08-15 14:28:01 +00001191for every option argument stored to an option destination) and returned by
1192:meth:`parse_args`.
1193
1194If :meth:`parse_args` encounters any errors in the argument list, it calls the
1195OptionParser's :meth:`error` method with an appropriate end-user error message.
1196This ultimately terminates your process with an exit status of 2 (the
1197traditional Unix exit status for command-line errors).
1198
1199
1200.. _optparse-querying-manipulating-option-parser:
1201
1202Querying and manipulating your option parser
1203^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1204
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001205The default behavior of the option parser can be customized slightly,
1206and you can also poke around your option parser and see what's there.
1207OptionParser provides several methods to help you out:
Georg Brandl8ec7f652007-08-15 14:28:01 +00001208
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001209``disable_interspersed_args()``
Georg Brandl7842a412009-09-17 16:26:06 +00001210 Set parsing to stop on the first non-option. For example, if ``"-a"`` and
1211 ``"-b"`` are both simple options that take no arguments, :mod:`optparse`
1212 normally accepts this syntax::
1213
1214 prog -a arg1 -b arg2
1215
1216 and treats it as equivalent to ::
1217
1218 prog -a -b arg1 arg2
1219
1220 To disable this feature, call ``disable_interspersed_args()``. This restores
1221 traditional Unix syntax, where option parsing stops with the first non-option
1222 argument.
1223
1224 Use this if you have a command processor which runs another command which has
1225 options of its own and you want to make sure these options don't get confused.
1226 For example, each command might have a different set of options.
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001227
1228``enable_interspersed_args()``
Georg Brandl7842a412009-09-17 16:26:06 +00001229 Set parsing to not stop on the first non-option, allowing interspersing
1230 switches with command arguments. This is the default behavior.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001231
1232``get_option(opt_str)``
1233 Returns the Option instance with the option string ``opt_str``, or ``None`` if
1234 no options have that option string.
1235
Andrew M. Kuchling7a4a93b2008-09-28 01:08:47 +00001236``has_option(opt_str)``
1237 Return true if the OptionParser has an option with option string ``opt_str``
1238 (e.g., ``"-q"`` or ``"--verbose"``).
1239
Georg Brandl8ec7f652007-08-15 14:28:01 +00001240``remove_option(opt_str)``
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001241 If the :class:`OptionParser` has an option corresponding to ``opt_str``, that option is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001242 removed. If that option provided any other option strings, all of those option
1243 strings become invalid. If ``opt_str`` does not occur in any option belonging to
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001244 this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001245
1246
1247.. _optparse-conflicts-between-options:
1248
1249Conflicts between options
1250^^^^^^^^^^^^^^^^^^^^^^^^^
1251
1252If you're not careful, it's easy to define options with conflicting option
1253strings::
1254
1255 parser.add_option("-n", "--dry-run", ...)
1256 [...]
1257 parser.add_option("-n", "--noisy", ...)
1258
1259(This is particularly true if you've defined your own OptionParser subclass with
1260some standard options.)
1261
1262Every time you add an option, :mod:`optparse` checks for conflicts with existing
1263options. If it finds any, it invokes the current conflict-handling mechanism.
1264You can set the conflict-handling mechanism either in the constructor::
1265
1266 parser = OptionParser(..., conflict_handler=handler)
1267
1268or with a separate call::
1269
1270 parser.set_conflict_handler(handler)
1271
1272The available conflict handlers are:
1273
Georg Brandlbc3777d2009-09-17 10:23:02 +00001274 ``'error'`` (default)
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001275 assume option conflicts are a programming error and raise :exc:`OptionConflictError`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001276
Georg Brandlbc3777d2009-09-17 10:23:02 +00001277 ``'resolve'``
Georg Brandl8ec7f652007-08-15 14:28:01 +00001278 resolve option conflicts intelligently (see below)
1279
1280
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001281As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl8ec7f652007-08-15 14:28:01 +00001282intelligently and add conflicting options to it::
1283
1284 parser = OptionParser(conflict_handler="resolve")
1285 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1286 parser.add_option("-n", "--noisy", ..., help="be noisy")
1287
1288At this point, :mod:`optparse` detects that a previously-added option is already
1289using the ``"-n"`` option string. Since ``conflict_handler`` is ``"resolve"``,
1290it resolves the situation by removing ``"-n"`` from the earlier option's list of
1291option strings. Now ``"--dry-run"`` is the only way for the user to activate
1292that option. If the user asks for help, the help message will reflect that::
1293
1294 options:
1295 --dry-run do no harm
1296 [...]
1297 -n, --noisy be noisy
1298
1299It's possible to whittle away the option strings for a previously-added option
1300until there are none left, and the user has no way of invoking that option from
1301the command-line. In that case, :mod:`optparse` removes that option completely,
1302so it doesn't show up in help text or anywhere else. Carrying on with our
1303existing OptionParser::
1304
1305 parser.add_option("--dry-run", ..., help="new dry-run option")
1306
1307At this point, the original :option:`-n/--dry-run` option is no longer
1308accessible, so :mod:`optparse` removes it, leaving this help text::
1309
1310 options:
1311 [...]
1312 -n, --noisy be noisy
1313 --dry-run new dry-run option
1314
1315
1316.. _optparse-cleanup:
1317
1318Cleanup
1319^^^^^^^
1320
1321OptionParser instances have several cyclic references. This should not be a
1322problem for Python's garbage collector, but you may wish to break the cyclic
1323references explicitly by calling ``destroy()`` on your OptionParser once you are
1324done with it. This is particularly useful in long-running applications where
1325large object graphs are reachable from your OptionParser.
1326
1327
1328.. _optparse-other-methods:
1329
1330Other methods
1331^^^^^^^^^^^^^
1332
1333OptionParser supports several other public methods:
1334
1335* ``set_usage(usage)``
1336
1337 Set the usage string according to the rules described above for the ``usage``
1338 constructor keyword argument. Passing ``None`` sets the default usage string;
1339 use ``SUPPRESS_USAGE`` to suppress a usage message.
1340
Georg Brandl8ec7f652007-08-15 14:28:01 +00001341* ``set_defaults(dest=value, ...)``
1342
1343 Set default values for several option destinations at once. Using
1344 :meth:`set_defaults` is the preferred way to set default values for options,
1345 since multiple options can share the same destination. For example, if several
1346 "mode" options all set the same destination, any one of them can set the
1347 default, and the last one wins::
1348
1349 parser.add_option("--advanced", action="store_const",
1350 dest="mode", const="advanced",
1351 default="novice") # overridden below
1352 parser.add_option("--novice", action="store_const",
1353 dest="mode", const="novice",
1354 default="advanced") # overrides above setting
1355
1356 To avoid this confusion, use :meth:`set_defaults`::
1357
1358 parser.set_defaults(mode="advanced")
1359 parser.add_option("--advanced", action="store_const",
1360 dest="mode", const="advanced")
1361 parser.add_option("--novice", action="store_const",
1362 dest="mode", const="novice")
1363
Georg Brandl8ec7f652007-08-15 14:28:01 +00001364
1365.. _optparse-option-callbacks:
1366
1367Option Callbacks
1368----------------
1369
1370When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1371needs, you have two choices: extend :mod:`optparse` or define a callback option.
1372Extending :mod:`optparse` is more general, but overkill for a lot of simple
1373cases. Quite often a simple callback is all you need.
1374
1375There are two steps to defining a callback option:
1376
1377* define the option itself using the ``callback`` action
1378
1379* write the callback; this is a function (or method) that takes at least four
1380 arguments, as described below
1381
1382
1383.. _optparse-defining-callback-option:
1384
1385Defining a callback option
1386^^^^^^^^^^^^^^^^^^^^^^^^^^
1387
1388As always, the easiest way to define a callback option is by using the
1389``parser.add_option()`` method. Apart from :attr:`action`, the only option
1390attribute you must specify is ``callback``, the function to call::
1391
1392 parser.add_option("-c", action="callback", callback=my_callback)
1393
1394``callback`` is a function (or other callable object), so you must have already
1395defined ``my_callback()`` when you create this callback option. In this simple
1396case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,
1397which usually means that the option takes no arguments---the mere presence of
1398:option:`-c` on the command-line is all it needs to know. In some
1399circumstances, though, you might want your callback to consume an arbitrary
1400number of command-line arguments. This is where writing callbacks gets tricky;
1401it's covered later in this section.
1402
1403:mod:`optparse` always passes four particular arguments to your callback, and it
1404will only pass additional arguments if you specify them via ``callback_args``
1405and ``callback_kwargs``. Thus, the minimal callback function signature is::
1406
1407 def my_callback(option, opt, value, parser):
1408
1409The four arguments to a callback are described below.
1410
1411There are several other option attributes that you can supply when you define a
1412callback option:
1413
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001414:attr:`!type`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001415 has its usual meaning: as with the ``store`` or ``append`` actions, it instructs
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001416 :mod:`optparse` to consume one argument and convert it to :attr:`!type`. Rather
Georg Brandl8ec7f652007-08-15 14:28:01 +00001417 than storing the converted value(s) anywhere, though, :mod:`optparse` passes it
1418 to your callback function.
1419
1420``nargs``
1421 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001422 consume ``nargs`` arguments, each of which must be convertible to :attr:`!type`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001423 It then passes a tuple of converted values to your callback.
1424
1425``callback_args``
1426 a tuple of extra positional arguments to pass to the callback
1427
1428``callback_kwargs``
1429 a dictionary of extra keyword arguments to pass to the callback
1430
1431
1432.. _optparse-how-callbacks-called:
1433
1434How callbacks are called
1435^^^^^^^^^^^^^^^^^^^^^^^^
1436
1437All callbacks are called as follows::
1438
1439 func(option, opt_str, value, parser, *args, **kwargs)
1440
1441where
1442
1443``option``
1444 is the Option instance that's calling the callback
1445
1446``opt_str``
1447 is the option string seen on the command-line that's triggering the callback.
1448 (If an abbreviated long option was used, ``opt_str`` will be the full, canonical
1449 option string---e.g. if the user puts ``"--foo"`` on the command-line as an
1450 abbreviation for ``"--foobar"``, then ``opt_str`` will be ``"--foobar"``.)
1451
1452``value``
1453 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001454 only expect an argument if :attr:`!type` is set; the type of ``value`` will be
1455 the type implied by the option's type. If :attr:`!type` for this option is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001456 ``None`` (no argument expected), then ``value`` will be ``None``. If ``nargs``
1457 > 1, ``value`` will be a tuple of values of the appropriate type.
1458
1459``parser``
1460 is the OptionParser instance driving the whole thing, mainly useful because you
1461 can access some other interesting data through its instance attributes:
1462
1463 ``parser.largs``
1464 the current list of leftover arguments, ie. arguments that have been consumed
1465 but are neither options nor option arguments. Feel free to modify
1466 ``parser.largs``, e.g. by adding more arguments to it. (This list will become
1467 ``args``, the second return value of :meth:`parse_args`.)
1468
1469 ``parser.rargs``
1470 the current list of remaining arguments, ie. with ``opt_str`` and ``value`` (if
1471 applicable) removed, and only the arguments following them still there. Feel
1472 free to modify ``parser.rargs``, e.g. by consuming more arguments.
1473
1474 ``parser.values``
1475 the object where option values are by default stored (an instance of
1476 optparse.OptionValues). This lets callbacks use the same mechanism as the rest
1477 of :mod:`optparse` for storing option values; you don't need to mess around with
1478 globals or closures. You can also access or modify the value(s) of any options
1479 already encountered on the command-line.
1480
1481``args``
1482 is a tuple of arbitrary positional arguments supplied via the ``callback_args``
1483 option attribute.
1484
1485``kwargs``
1486 is a dictionary of arbitrary keyword arguments supplied via ``callback_kwargs``.
1487
1488
1489.. _optparse-raising-errors-in-callback:
1490
1491Raising errors in a callback
1492^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1493
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001494The callback function should raise :exc:`OptionValueError` if there are any problems
Georg Brandl8ec7f652007-08-15 14:28:01 +00001495with the option or its argument(s). :mod:`optparse` catches this and terminates
1496the program, printing the error message you supply to stderr. Your message
1497should be clear, concise, accurate, and mention the option at fault. Otherwise,
1498the user will have a hard time figuring out what he did wrong.
1499
1500
1501.. _optparse-callback-example-1:
1502
1503Callback example 1: trivial callback
1504^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1505
1506Here's an example of a callback option that takes no arguments, and simply
1507records that the option was seen::
1508
1509 def record_foo_seen(option, opt_str, value, parser):
Georg Brandl253a29f2009-02-05 11:33:21 +00001510 parser.values.saw_foo = True
Georg Brandl8ec7f652007-08-15 14:28:01 +00001511
1512 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1513
1514Of course, you could do that with the ``store_true`` action.
1515
1516
1517.. _optparse-callback-example-2:
1518
1519Callback example 2: check option order
1520^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1521
1522Here's a slightly more interesting example: record the fact that ``"-a"`` is
1523seen, but blow up if it comes after ``"-b"`` in the command-line. ::
1524
1525 def check_order(option, opt_str, value, parser):
1526 if parser.values.b:
1527 raise OptionValueError("can't use -a after -b")
1528 parser.values.a = 1
1529 [...]
1530 parser.add_option("-a", action="callback", callback=check_order)
1531 parser.add_option("-b", action="store_true", dest="b")
1532
1533
1534.. _optparse-callback-example-3:
1535
1536Callback example 3: check option order (generalized)
1537^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1538
1539If you want to re-use this callback for several similar options (set a flag, but
1540blow up if ``"-b"`` has already been seen), it needs a bit of work: the error
1541message and the flag that it sets must be generalized. ::
1542
1543 def check_order(option, opt_str, value, parser):
1544 if parser.values.b:
1545 raise OptionValueError("can't use %s after -b" % opt_str)
1546 setattr(parser.values, option.dest, 1)
1547 [...]
1548 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1549 parser.add_option("-b", action="store_true", dest="b")
1550 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1551
1552
1553.. _optparse-callback-example-4:
1554
1555Callback example 4: check arbitrary condition
1556^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1557
1558Of course, you could put any condition in there---you're not limited to checking
1559the values of already-defined options. For example, if you have options that
1560should not be called when the moon is full, all you have to do is this::
1561
1562 def check_moon(option, opt_str, value, parser):
1563 if is_moon_full():
1564 raise OptionValueError("%s option invalid when moon is full"
1565 % opt_str)
1566 setattr(parser.values, option.dest, 1)
1567 [...]
1568 parser.add_option("--foo",
1569 action="callback", callback=check_moon, dest="foo")
1570
1571(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1572
1573
1574.. _optparse-callback-example-5:
1575
1576Callback example 5: fixed arguments
1577^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1578
1579Things get slightly more interesting when you define callback options that take
1580a fixed number of arguments. Specifying that a callback option takes arguments
1581is similar to defining a ``store`` or ``append`` option: if you define
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001582:attr:`!type`, then the option takes one argument that must be convertible to
Georg Brandl8ec7f652007-08-15 14:28:01 +00001583that type; if you further define ``nargs``, then the option takes ``nargs``
1584arguments.
1585
1586Here's an example that just emulates the standard ``store`` action::
1587
1588 def store_value(option, opt_str, value, parser):
1589 setattr(parser.values, option.dest, value)
1590 [...]
1591 parser.add_option("--foo",
1592 action="callback", callback=store_value,
1593 type="int", nargs=3, dest="foo")
1594
1595Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1596them to integers for you; all you have to do is store them. (Or whatever;
1597obviously you don't need a callback for this example.)
1598
1599
1600.. _optparse-callback-example-6:
1601
1602Callback example 6: variable arguments
1603^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1604
1605Things get hairy when you want an option to take a variable number of arguments.
1606For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1607built-in capabilities for it. And you have to deal with certain intricacies of
1608conventional Unix command-line parsing that :mod:`optparse` normally handles for
1609you. In particular, callbacks should implement the conventional rules for bare
1610``"--"`` and ``"-"`` arguments:
1611
1612* either ``"--"`` or ``"-"`` can be option arguments
1613
1614* bare ``"--"`` (if not the argument to some option): halt command-line
1615 processing and discard the ``"--"``
1616
1617* bare ``"-"`` (if not the argument to some option): halt command-line
1618 processing but keep the ``"-"`` (append it to ``parser.largs``)
1619
1620If you want an option that takes a variable number of arguments, there are
1621several subtle, tricky issues to worry about. The exact implementation you
1622choose will be based on which trade-offs you're willing to make for your
1623application (which is why :mod:`optparse` doesn't support this sort of thing
1624directly).
1625
1626Nevertheless, here's a stab at a callback for an option with variable
1627arguments::
1628
Georg Brandl60b2e382008-12-15 09:07:39 +00001629 def vararg_callback(option, opt_str, value, parser):
1630 assert value is None
1631 value = []
Georg Brandl8ec7f652007-08-15 14:28:01 +00001632
Georg Brandl60b2e382008-12-15 09:07:39 +00001633 def floatable(str):
1634 try:
1635 float(str)
1636 return True
1637 except ValueError:
1638 return False
Georg Brandl8ec7f652007-08-15 14:28:01 +00001639
Georg Brandl60b2e382008-12-15 09:07:39 +00001640 for arg in parser.rargs:
1641 # stop on --foo like options
1642 if arg[:2] == "--" and len(arg) > 2:
1643 break
1644 # stop on -a, but not on -3 or -3.0
1645 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1646 break
1647 value.append(arg)
1648
1649 del parser.rargs[:len(value)]
Georg Brandl174fbe72009-02-05 10:30:57 +00001650 setattr(parser.values, option.dest, value)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001651
1652 [...]
Andrew M. Kuchling810f8072008-09-06 13:04:02 +00001653 parser.add_option("-c", "--callback", dest="vararg_attr",
Benjamin Petersonc8590942008-04-23 20:38:06 +00001654 action="callback", callback=vararg_callback)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001655
Georg Brandl8ec7f652007-08-15 14:28:01 +00001656
1657.. _optparse-extending-optparse:
1658
1659Extending :mod:`optparse`
1660-------------------------
1661
1662Since the two major controlling factors in how :mod:`optparse` interprets
1663command-line options are the action and type of each option, the most likely
1664direction of extension is to add new actions and new types.
1665
1666
1667.. _optparse-adding-new-types:
1668
1669Adding new types
1670^^^^^^^^^^^^^^^^
1671
1672To add new types, you need to define your own subclass of :mod:`optparse`'s
1673Option class. This class has a couple of attributes that define
1674:mod:`optparse`'s types: :attr:`TYPES` and :attr:`TYPE_CHECKER`.
1675
1676:attr:`TYPES` is a tuple of type names; in your subclass, simply define a new
1677tuple :attr:`TYPES` that builds on the standard one.
1678
1679:attr:`TYPE_CHECKER` is a dictionary mapping type names to type-checking
1680functions. A type-checking function has the following signature::
1681
1682 def check_mytype(option, opt, value)
1683
1684where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1685(e.g., ``"-f"``), and ``value`` is the string from the command line that must be
1686checked and converted to your desired type. ``check_mytype()`` should return an
1687object of the hypothetical type ``mytype``. The value returned by a
1688type-checking function will wind up in the OptionValues instance returned by
1689:meth:`OptionParser.parse_args`, or be passed to a callback as the ``value``
1690parameter.
1691
Andrew M. Kuchlingcad8da82008-09-30 13:01:46 +00001692Your type-checking function should raise :exc:`OptionValueError` if it encounters any
1693problems. :exc:`OptionValueError` takes a single string argument, which is passed
1694as-is to :class:`OptionParser`'s :meth:`error` method, which in turn prepends the program
Georg Brandl8ec7f652007-08-15 14:28:01 +00001695name and the string ``"error:"`` and prints everything to stderr before
1696terminating the process.
1697
1698Here's a silly example that demonstrates adding a ``complex`` option type to
1699parse Python-style complex numbers on the command line. (This is even sillier
1700than it used to be, because :mod:`optparse` 1.3 added built-in support for
1701complex numbers, but never mind.)
1702
1703First, the necessary imports::
1704
1705 from copy import copy
1706 from optparse import Option, OptionValueError
1707
1708You need to define your type-checker first, since it's referred to later (in the
1709:attr:`TYPE_CHECKER` class attribute of your Option subclass)::
1710
1711 def check_complex(option, opt, value):
1712 try:
1713 return complex(value)
1714 except ValueError:
1715 raise OptionValueError(
1716 "option %s: invalid complex value: %r" % (opt, value))
1717
1718Finally, the Option subclass::
1719
1720 class MyOption (Option):
1721 TYPES = Option.TYPES + ("complex",)
1722 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1723 TYPE_CHECKER["complex"] = check_complex
1724
1725(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
1726up modifying the :attr:`TYPE_CHECKER` attribute of :mod:`optparse`'s Option
1727class. This being Python, nothing stops you from doing that except good manners
1728and common sense.)
1729
1730That's it! Now you can write a script that uses the new option type just like
1731any other :mod:`optparse`\ -based script, except you have to instruct your
1732OptionParser to use MyOption instead of Option::
1733
1734 parser = OptionParser(option_class=MyOption)
1735 parser.add_option("-c", type="complex")
1736
1737Alternately, you can build your own option list and pass it to OptionParser; if
1738you don't use :meth:`add_option` in the above way, you don't need to tell
1739OptionParser which option class to use::
1740
1741 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1742 parser = OptionParser(option_list=option_list)
1743
1744
1745.. _optparse-adding-new-actions:
1746
1747Adding new actions
1748^^^^^^^^^^^^^^^^^^
1749
1750Adding new actions is a bit trickier, because you have to understand that
1751:mod:`optparse` has a couple of classifications for actions:
1752
1753"store" actions
1754 actions that result in :mod:`optparse` storing a value to an attribute of the
1755 current OptionValues instance; these options require a :attr:`dest` attribute to
1756 be supplied to the Option constructor
1757
1758"typed" actions
1759 actions that take a value from the command line and expect it to be of a certain
1760 type; or rather, a string that can be converted to a certain type. These
Georg Brandl9fa61bb2009-07-26 14:19:57 +00001761 options require a :attr:`!type` attribute to the Option constructor.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001762
1763These are overlapping sets: some default "store" actions are ``store``,
1764``store_const``, ``append``, and ``count``, while the default "typed" actions
1765are ``store``, ``append``, and ``callback``.
1766
1767When you add an action, you need to categorize it by listing it in at least one
1768of the following class attributes of Option (all are lists of strings):
1769
1770:attr:`ACTIONS`
1771 all actions must be listed in ACTIONS
1772
1773:attr:`STORE_ACTIONS`
1774 "store" actions are additionally listed here
1775
1776:attr:`TYPED_ACTIONS`
1777 "typed" actions are additionally listed here
1778
1779``ALWAYS_TYPED_ACTIONS``
1780 actions that always take a type (i.e. whose options always take a value) are
1781 additionally listed here. The only effect of this is that :mod:`optparse`
1782 assigns the default type, ``string``, to options with no explicit type whose
1783 action is listed in ``ALWAYS_TYPED_ACTIONS``.
1784
1785In order to actually implement your new action, you must override Option's
1786:meth:`take_action` method and add a case that recognizes your action.
1787
1788For example, let's add an ``extend`` action. This is similar to the standard
1789``append`` action, but instead of taking a single value from the command-line
1790and appending it to an existing list, ``extend`` will take multiple values in a
1791single comma-delimited string, and extend an existing list with them. That is,
1792if ``"--names"`` is an ``extend`` option of type ``string``, the command line
1793::
1794
1795 --names=foo,bar --names blah --names ding,dong
1796
1797would result in a list ::
1798
1799 ["foo", "bar", "blah", "ding", "dong"]
1800
1801Again we define a subclass of Option::
1802
1803 class MyOption (Option):
1804
1805 ACTIONS = Option.ACTIONS + ("extend",)
1806 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1807 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1808 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1809
1810 def take_action(self, action, dest, opt, value, values, parser):
1811 if action == "extend":
1812 lvalue = value.split(",")
1813 values.ensure_value(dest, []).extend(lvalue)
1814 else:
1815 Option.take_action(
1816 self, action, dest, opt, value, values, parser)
1817
1818Features of note:
1819
1820* ``extend`` both expects a value on the command-line and stores that value
1821 somewhere, so it goes in both :attr:`STORE_ACTIONS` and :attr:`TYPED_ACTIONS`
1822
1823* to ensure that :mod:`optparse` assigns the default type of ``string`` to
1824 ``extend`` actions, we put the ``extend`` action in ``ALWAYS_TYPED_ACTIONS`` as
1825 well
1826
1827* :meth:`MyOption.take_action` implements just this one new action, and passes
1828 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
1829 actions
1830
1831* ``values`` is an instance of the optparse_parser.Values class, which
1832 provides the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1833 essentially :func:`getattr` with a safety valve; it is called as ::
1834
1835 values.ensure_value(attr, value)
1836
1837 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
1838 ensure_value() first sets it to ``value``, and then returns 'value. This is very
1839 handy for actions like ``extend``, ``append``, and ``count``, all of which
1840 accumulate data in a variable and expect that variable to be of a certain type
1841 (a list for the first two, an integer for the latter). Using
1842 :meth:`ensure_value` means that scripts using your action don't have to worry
1843 about setting a default value for the option destinations in question; they can
1844 just leave the default as None and :meth:`ensure_value` will take care of
1845 getting it right when it's needed.