blob: 8b585b62f9e0a01eed4165e319b60a0ec208fd77 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001.. % THIS FILE IS AUTO-GENERATED! DO NOT EDIT!
2.. % (Your changes will be lost the next time it is generated.)
3
4
5:mod:`optparse` --- More powerful command line option parser
6============================================================
7
8.. module:: optparse
9 :synopsis: More convenient, flexible, and powerful command-line parsing library.
10.. moduleauthor:: Greg Ward <gward@python.net>
11
12
13.. versionadded:: 2.3
14
15.. sectionauthor:: Greg Ward <gward@python.net>
16
17
18``optparse`` is a more convenient, flexible, and powerful library for parsing
19command-line options than ``getopt``. ``optparse`` uses a more declarative
20style of command-line parsing: you create an instance of :class:`OptionParser`,
21populate it with options, and parse the command line. ``optparse`` allows users
22to specify options in the conventional GNU/POSIX syntax, and additionally
23generates usage and help messages for you.
24
25.. % An intro blurb used only when generating LaTeX docs for the Python
26.. % manual (based on README.txt).
27
28Here's an example of using ``optparse`` in a simple script::
29
30 from optparse import OptionParser
31 [...]
32 parser = OptionParser()
33 parser.add_option("-f", "--file", dest="filename",
34 help="write report to FILE", metavar="FILE")
35 parser.add_option("-q", "--quiet",
36 action="store_false", dest="verbose", default=True,
37 help="don't print status messages to stdout")
38
39 (options, args) = parser.parse_args()
40
41With these few lines of code, users of your script can now do the "usual thing"
42on the command-line, for example::
43
44 <yourscript> --file=outfile -q
45
46As it parses the command line, ``optparse`` sets attributes of the ``options``
47object returned by :meth:`parse_args` based on user-supplied command-line
48values. When :meth:`parse_args` returns from parsing this command line,
49``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
50``False``. ``optparse`` supports both long and short options, allows short
51options to be merged together, and allows options to be associated with their
52arguments in a variety of ways. Thus, the following command lines are all
53equivalent to the above example::
54
55 <yourscript> -f outfile --quiet
56 <yourscript> --quiet --file outfile
57 <yourscript> -q -foutfile
58 <yourscript> -qfoutfile
59
60Additionally, users can run one of ::
61
62 <yourscript> -h
63 <yourscript> --help
64
65and ``optparse`` will print out a brief summary of your script's options::
66
67 usage: <yourscript> [options]
68
69 options:
70 -h, --help show this help message and exit
71 -f FILE, --file=FILE write report to FILE
72 -q, --quiet don't print status messages to stdout
73
74where the value of *yourscript* is determined at runtime (normally from
75``sys.argv[0]``).
76
77.. % $Id: intro.txt 413 2004-09-28 00:59:13Z greg $
78
79
80.. _optparse-background:
81
82Background
83----------
84
85:mod:`optparse` was explicitly designed to encourage the creation of programs
86with straightforward, conventional command-line interfaces. To that end, it
87supports only the most common command-line syntax and semantics conventionally
88used under Unix. If you are unfamiliar with these conventions, read this
89section to acquaint yourself with them.
90
91
92.. _optparse-terminology:
93
94Terminology
95^^^^^^^^^^^
96
97argument
98 a string entered on the command-line, and passed by the shell to ``execl()`` or
99 ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
100 (``sys.argv[0]`` is the name of the program being executed). Unix shells also
101 use the term "word".
102
103 It is occasionally desirable to substitute an argument list other than
104 ``sys.argv[1:]``, so you should read "argument" as "an element of
105 ``sys.argv[1:]``, or of some other list provided as a substitute for
106 ``sys.argv[1:]``".
107
108option
109 an argument used to supply extra information to guide or customize the execution
110 of a program. There are many different syntaxes for options; the traditional
111 Unix syntax is a hyphen ("-") followed by a single letter, e.g. ``"-x"`` or
112 ``"-F"``. Also, traditional Unix syntax allows multiple options to be merged
113 into a single argument, e.g. ``"-x -F"`` is equivalent to ``"-xF"``. The GNU
114 project introduced ``"--"`` followed by a series of hyphen-separated words, e.g.
115 ``"--file"`` or ``"--dry-run"``. These are the only two option syntaxes
116 provided by :mod:`optparse`.
117
118 Some other option syntaxes that the world has seen include:
119
120 * a hyphen followed by a few letters, e.g. ``"-pf"`` (this is *not* the same
121 as multiple options merged into a single argument)
122
123 * a hyphen followed by a whole word, e.g. ``"-file"`` (this is technically
124 equivalent to the previous syntax, but they aren't usually seen in the same
125 program)
126
127 * a plus sign followed by a single letter, or a few letters, or a word, e.g.
128 ``"+f"``, ``"+rgb"``
129
130 * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
131 ``"/file"``
132
133 These option syntaxes are not supported by :mod:`optparse`, and they never will
134 be. This is deliberate: the first three are non-standard on any environment,
135 and the last only makes sense if you're exclusively targeting VMS, MS-DOS,
136 and/or Windows.
137
138option argument
139 an argument that follows an option, is closely associated with that option, and
140 is consumed from the argument list when that option is. With :mod:`optparse`,
141 option arguments may either be in a separate argument from their option::
142
143 -f foo
144 --file foo
145
146 or included in the same argument::
147
148 -ffoo
149 --file=foo
150
151 Typically, a given option either takes an argument or it doesn't. Lots of people
152 want an "optional option arguments" feature, meaning that some options will take
153 an argument if they see it, and won't if they don't. This is somewhat
154 controversial, because it makes parsing ambiguous: if ``"-a"`` takes an optional
155 argument and ``"-b"`` is another option entirely, how do we interpret ``"-ab"``?
156 Because of this ambiguity, :mod:`optparse` does not support this feature.
157
158positional argument
159 something leftover in the argument list after options have been parsed, i.e.
160 after options and their arguments have been parsed and removed from the argument
161 list.
162
163required option
164 an option that must be supplied on the command-line; note that the phrase
165 "required option" is self-contradictory in English. :mod:`optparse` doesn't
166 prevent you from implementing required options, but doesn't give you much help
167 at it either. See ``examples/required_1.py`` and ``examples/required_2.py`` in
168 the :mod:`optparse` source distribution for two ways to implement required
169 options with :mod:`optparse`.
170
171For example, consider this hypothetical command-line::
172
173 prog -v --report /tmp/report.txt foo bar
174
175``"-v"`` and ``"--report"`` are both options. Assuming that :option:`--report`
176takes one argument, ``"/tmp/report.txt"`` is an option argument. ``"foo"`` and
177``"bar"`` are positional arguments.
178
179
180.. _optparse-what-options-for:
181
182What are options for?
183^^^^^^^^^^^^^^^^^^^^^
184
185Options are used to provide extra information to tune or customize the execution
186of a program. In case it wasn't clear, options are usually *optional*. A
187program should be able to run just fine with no options whatsoever. (Pick a
188random program from the Unix or GNU toolsets. Can it run without any options at
189all and still make sense? The main exceptions are ``find``, ``tar``, and
190``dd``\ ---all of which are mutant oddballs that have been rightly criticized
191for their non-standard syntax and confusing interfaces.)
192
193Lots of people want their programs to have "required options". Think about it.
194If it's required, then it's *not optional*! If there is a piece of information
195that your program absolutely requires in order to run successfully, that's what
196positional arguments are for.
197
198As an example of good command-line interface design, consider the humble ``cp``
199utility, for copying files. It doesn't make much sense to try to copy files
200without supplying a destination and at least one source. Hence, ``cp`` fails if
201you run it with no arguments. However, it has a flexible, useful syntax that
202does not require any options at all::
203
204 cp SOURCE DEST
205 cp SOURCE ... DEST-DIR
206
207You can get pretty far with just that. Most ``cp`` implementations provide a
208bunch of options to tweak exactly how the files are copied: you can preserve
209mode and modification time, avoid following symlinks, ask before clobbering
210existing files, etc. But none of this distracts from the core mission of
211``cp``, which is to copy either one file to another, or several files to another
212directory.
213
214
215.. _optparse-what-positional-arguments-for:
216
217What are positional arguments for?
218^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
219
220Positional arguments are for those pieces of information that your program
221absolutely, positively requires to run.
222
223A good user interface should have as few absolute requirements as possible. If
224your program requires 17 distinct pieces of information in order to run
225successfully, it doesn't much matter *how* you get that information from the
226user---most people will give up and walk away before they successfully run the
227program. This applies whether the user interface is a command-line, a
228configuration file, or a GUI: if you make that many demands on your users, most
229of them will simply give up.
230
231In short, try to minimize the amount of information that users are absolutely
232required to supply---use sensible defaults whenever possible. Of course, you
233also want to make your programs reasonably flexible. That's what options are
234for. Again, it doesn't matter if they are entries in a config file, widgets in
235the "Preferences" dialog of a GUI, or command-line options---the more options
236you implement, the more flexible your program is, and the more complicated its
237implementation becomes. Too much flexibility has drawbacks as well, of course;
238too many options can overwhelm users and make your code much harder to maintain.
239
240.. % $Id: tao.txt 413 2004-09-28 00:59:13Z greg $
241
242
243.. _optparse-tutorial:
244
245Tutorial
246--------
247
248While :mod:`optparse` is quite flexible and powerful, it's also straightforward
249to use in most cases. This section covers the code patterns that are common to
250any :mod:`optparse`\ -based program.
251
252First, you need to import the OptionParser class; then, early in the main
253program, create an OptionParser instance::
254
255 from optparse import OptionParser
256 [...]
257 parser = OptionParser()
258
259Then you can start defining options. The basic syntax is::
260
261 parser.add_option(opt_str, ...,
262 attr=value, ...)
263
264Each option has one or more option strings, such as ``"-f"`` or ``"--file"``,
265and several option attributes that tell :mod:`optparse` what to expect and what
266to do when it encounters that option on the command line.
267
268Typically, each option will have one short option string and one long option
269string, e.g.::
270
271 parser.add_option("-f", "--file", ...)
272
273You're free to define as many short option strings and as many long option
274strings as you like (including zero), as long as there is at least one option
275string overall.
276
277The option strings passed to :meth:`add_option` are effectively labels for the
278option defined by that call. For brevity, we will frequently refer to
279*encountering an option* on the command line; in reality, :mod:`optparse`
280encounters *option strings* and looks up options from them.
281
282Once all of your options are defined, instruct :mod:`optparse` to parse your
283program's command line::
284
285 (options, args) = parser.parse_args()
286
287(If you like, you can pass a custom argument list to :meth:`parse_args`, but
288that's rarely necessary: by default it uses ``sys.argv[1:]``.)
289
290:meth:`parse_args` returns two values:
291
292* ``options``, an object containing values for all of your options---e.g. if
293 ``"--file"`` takes a single string argument, then ``options.file`` will be the
294 filename supplied by the user, or ``None`` if the user did not supply that
295 option
296
297* ``args``, the list of positional arguments leftover after parsing options
298
299This tutorial section only covers the four most important option attributes:
300:attr:`action`, :attr:`type`, :attr:`dest` (destination), and :attr:`help`. Of
301these, :attr:`action` is the most fundamental.
302
303
304.. _optparse-understanding-option-actions:
305
306Understanding option actions
307^^^^^^^^^^^^^^^^^^^^^^^^^^^^
308
309Actions tell :mod:`optparse` what to do when it encounters an option on the
310command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
311adding new actions is an advanced topic covered in section
312:ref:`optparse-extending-optparse`. Most actions tell
313:mod:`optparse` to store a value in some variable---for example, take a string
314from the command line and store it in an attribute of ``options``.
315
316If you don't specify an option action, :mod:`optparse` defaults to ``store``.
317
318
319.. _optparse-store-action:
320
321The store action
322^^^^^^^^^^^^^^^^
323
324The most common option action is ``store``, which tells :mod:`optparse` to take
325the next argument (or the remainder of the current argument), ensure that it is
326of the correct type, and store it to your chosen destination.
327
328For example::
329
330 parser.add_option("-f", "--file",
331 action="store", type="string", dest="filename")
332
333Now let's make up a fake command line and ask :mod:`optparse` to parse it::
334
335 args = ["-f", "foo.txt"]
336 (options, args) = parser.parse_args(args)
337
338When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
339argument, ``"foo.txt"``, and stores it in ``options.filename``. So, after this
340call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
341
342Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
343Here's an option that expects an integer argument::
344
345 parser.add_option("-n", type="int", dest="num")
346
347Note that this option has no long option string, which is perfectly acceptable.
348Also, there's no explicit action, since the default is ``store``.
349
350Let's parse another fake command-line. This time, we'll jam the option argument
351right up against the option: since ``"-n42"`` (one argument) is equivalent to
352``"-n 42"`` (two arguments), the code ::
353
354 (options, args) = parser.parse_args(["-n42"])
355 print options.num
356
357will print ``"42"``.
358
359If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
360the fact that the default action is ``store``, that means our first example can
361be a lot shorter::
362
363 parser.add_option("-f", "--file", dest="filename")
364
365If you don't supply a destination, :mod:`optparse` figures out a sensible
366default from the option strings: if the first long option string is
367``"--foo-bar"``, then the default destination is ``foo_bar``. If there are no
368long option strings, :mod:`optparse` looks at the first short option string: the
369default destination for ``"-f"`` is ``f``.
370
371:mod:`optparse` also includes built-in ``long`` and ``complex`` types. Adding
372types is covered in section :ref:`optparse-extending-optparse`.
373
374
375.. _optparse-handling-boolean-options:
376
377Handling boolean (flag) options
378^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
379
380Flag options---set a variable to true or false when a particular option is seen
381---are quite common. :mod:`optparse` supports them with two separate actions,
382``store_true`` and ``store_false``. For example, you might have a ``verbose``
383flag that is turned on with ``"-v"`` and off with ``"-q"``::
384
385 parser.add_option("-v", action="store_true", dest="verbose")
386 parser.add_option("-q", action="store_false", dest="verbose")
387
388Here we have two different options with the same destination, which is perfectly
389OK. (It just means you have to be a bit careful when setting default values---
390see below.)
391
392When :mod:`optparse` encounters ``"-v"`` on the command line, it sets
393``options.verbose`` to ``True``; when it encounters ``"-q"``,
394``options.verbose`` is set to ``False``.
395
396
397.. _optparse-other-actions:
398
399Other actions
400^^^^^^^^^^^^^
401
402Some other actions supported by :mod:`optparse` are:
403
404``store_const``
405 store a constant value
406
407``append``
408 append this option's argument to a list
409
410``count``
411 increment a counter by one
412
413``callback``
414 call a specified function
415
416These are covered in section :ref:`optparse-reference-guide`, Reference Guide
417and section :ref:`optparse-option-callbacks`.
418
419
420.. _optparse-default-values:
421
422Default values
423^^^^^^^^^^^^^^
424
425All of the above examples involve setting some variable (the "destination") when
426certain command-line options are seen. What happens if those options are never
427seen? Since we didn't supply any defaults, they are all set to ``None``. This
428is usually fine, but sometimes you want more control. :mod:`optparse` lets you
429supply a default value for each destination, which is assigned before the
430command line is parsed.
431
432First, consider the verbose/quiet example. If we want :mod:`optparse` to set
433``verbose`` to ``True`` unless ``"-q"`` is seen, then we can do this::
434
435 parser.add_option("-v", action="store_true", dest="verbose", default=True)
436 parser.add_option("-q", action="store_false", dest="verbose")
437
438Since default values apply to the *destination* rather than to any particular
439option, and these two options happen to have the same destination, this is
440exactly equivalent::
441
442 parser.add_option("-v", action="store_true", dest="verbose")
443 parser.add_option("-q", action="store_false", dest="verbose", default=True)
444
445Consider this::
446
447 parser.add_option("-v", action="store_true", dest="verbose", default=False)
448 parser.add_option("-q", action="store_false", dest="verbose", default=True)
449
450Again, the default value for ``verbose`` will be ``True``: the last default
451value supplied for any particular destination is the one that counts.
452
453A clearer way to specify default values is the :meth:`set_defaults` method of
454OptionParser, which you can call at any time before calling :meth:`parse_args`::
455
456 parser.set_defaults(verbose=True)
457 parser.add_option(...)
458 (options, args) = parser.parse_args()
459
460As before, the last value specified for a given option destination is the one
461that counts. For clarity, try to use one method or the other of setting default
462values, not both.
463
464
465.. _optparse-generating-help:
466
467Generating help
468^^^^^^^^^^^^^^^
469
470:mod:`optparse`'s ability to generate help and usage text automatically is
471useful for creating user-friendly command-line interfaces. All you have to do
472is supply a :attr:`help` value for each option, and optionally a short usage
473message for your whole program. Here's an OptionParser populated with
474user-friendly (documented) options::
475
476 usage = "usage: %prog [options] arg1 arg2"
477 parser = OptionParser(usage=usage)
478 parser.add_option("-v", "--verbose",
479 action="store_true", dest="verbose", default=True,
480 help="make lots of noise [default]")
481 parser.add_option("-q", "--quiet",
482 action="store_false", dest="verbose",
483 help="be vewwy quiet (I'm hunting wabbits)")
484 parser.add_option("-f", "--filename",
485 metavar="FILE", help="write output to FILE"),
486 parser.add_option("-m", "--mode",
487 default="intermediate",
488 help="interaction mode: novice, intermediate, "
489 "or expert [default: %default]")
490
491If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
492command-line, or if you just call :meth:`parser.print_help`, it prints the
493following to standard output::
494
495 usage: <yourscript> [options] arg1 arg2
496
497 options:
498 -h, --help show this help message and exit
499 -v, --verbose make lots of noise [default]
500 -q, --quiet be vewwy quiet (I'm hunting wabbits)
501 -f FILE, --filename=FILE
502 write output to FILE
503 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
504 expert [default: intermediate]
505
506(If the help output is triggered by a help option, :mod:`optparse` exits after
507printing the help text.)
508
509There's a lot going on here to help :mod:`optparse` generate the best possible
510help message:
511
512* the script defines its own usage message::
513
514 usage = "usage: %prog [options] arg1 arg2"
515
516 :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
517 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string is
518 then printed before the detailed option help.
519
520 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
521 default: ``"usage: %prog [options]"``, which is fine if your script doesn't take
522 any positional arguments.
523
524* every option defines a help string, and doesn't worry about line-wrapping---
525 :mod:`optparse` takes care of wrapping lines and making the help output look
526 good.
527
528* options that take a value indicate this fact in their automatically-generated
529 help message, e.g. for the "mode" option::
530
531 -m MODE, --mode=MODE
532
533 Here, "MODE" is called the meta-variable: it stands for the argument that the
534 user is expected to supply to :option:`-m`/:option:`--mode`. By default,
535 :mod:`optparse` converts the destination variable name to uppercase and uses
536 that for the meta-variable. Sometimes, that's not what you want---for example,
537 the :option:`--filename` option explicitly sets ``metavar="FILE"``, resulting in
538 this automatically-generated option description::
539
540 -f FILE, --filename=FILE
541
542 This is important for more than just saving space, though: the manually written
543 help text uses the meta-variable "FILE" to clue the user in that there's a
544 connection between the semi-formal syntax "-f FILE" and the informal semantic
545 description "write output to FILE". This is a simple but effective way to make
546 your help text a lot clearer and more useful for end users.
547
548* options that have a default value can include ``%default`` in the help
549 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
550 default value. If an option has no default value (or the default value is
551 ``None``), ``%default`` expands to ``none``.
552
553
554.. _optparse-printing-version-string:
555
556Printing a version string
557^^^^^^^^^^^^^^^^^^^^^^^^^
558
559Similar to the brief usage string, :mod:`optparse` can also print a version
560string for your program. You have to supply the string as the ``version``
561argument to OptionParser::
562
563 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
564
565``"%prog"`` is expanded just like it is in ``usage``. Apart from that,
566``version`` can contain anything you like. When you supply it, :mod:`optparse`
567automatically adds a ``"--version"`` option to your parser. If it encounters
568this option on the command line, it expands your ``version`` string (by
569replacing ``"%prog"``), prints it to stdout, and exits.
570
571For example, if your script is called ``/usr/bin/foo``::
572
573 $ /usr/bin/foo --version
574 foo 1.0
575
576
577.. _optparse-how-optparse-handles-errors:
578
579How :mod:`optparse` handles errors
580^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
581
582There are two broad classes of errors that :mod:`optparse` has to worry about:
583programmer errors and user errors. Programmer errors are usually erroneous
584calls to ``parser.add_option()``, e.g. invalid option strings, unknown option
585attributes, missing option attributes, etc. These are dealt with in the usual
586way: raise an exception (either ``optparse.OptionError`` or ``TypeError``) and
587let the program crash.
588
589Handling user errors is much more important, since they are guaranteed to happen
590no matter how stable your code is. :mod:`optparse` can automatically detect
591some user errors, such as bad option arguments (passing ``"-n 4x"`` where
592:option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
593of the command line, where :option:`-n` takes an argument of any type). Also,
594you can call ``parser.error()`` to signal an application-defined error
595condition::
596
597 (options, args) = parser.parse_args()
598 [...]
599 if options.a and options.b:
600 parser.error("options -a and -b are mutually exclusive")
601
602In either case, :mod:`optparse` handles the error the same way: it prints the
603program's usage message and an error message to standard error and exits with
604error status 2.
605
606Consider the first example above, where the user passes ``"4x"`` to an option
607that takes an integer::
608
609 $ /usr/bin/foo -n 4x
610 usage: foo [options]
611
612 foo: error: option -n: invalid integer value: '4x'
613
614Or, where the user fails to pass a value at all::
615
616 $ /usr/bin/foo -n
617 usage: foo [options]
618
619 foo: error: -n option requires an argument
620
621:mod:`optparse`\ -generated error messages take care always to mention the
622option involved in the error; be sure to do the same when calling
623``parser.error()`` from your application code.
624
625If :mod:`optparse`'s default error-handling behaviour does not suite your needs,
626you'll need to subclass OptionParser and override ``exit()`` and/or
627:meth:`error`.
628
629
630.. _optparse-putting-it-all-together:
631
632Putting it all together
633^^^^^^^^^^^^^^^^^^^^^^^
634
635Here's what :mod:`optparse`\ -based scripts usually look like::
636
637 from optparse import OptionParser
638 [...]
639 def main():
640 usage = "usage: %prog [options] arg"
641 parser = OptionParser(usage)
642 parser.add_option("-f", "--file", dest="filename",
643 help="read data from FILENAME")
644 parser.add_option("-v", "--verbose",
645 action="store_true", dest="verbose")
646 parser.add_option("-q", "--quiet",
647 action="store_false", dest="verbose")
648 [...]
649 (options, args) = parser.parse_args()
650 if len(args) != 1:
651 parser.error("incorrect number of arguments")
652 if options.verbose:
653 print "reading %s..." % options.filename
654 [...]
655
656 if __name__ == "__main__":
657 main()
658
659.. % $Id: tutorial.txt 515 2006-06-10 15:37:45Z gward $
660
661
662.. _optparse-reference-guide:
663
664Reference Guide
665---------------
666
667
668.. _optparse-creating-parser:
669
670Creating the parser
671^^^^^^^^^^^^^^^^^^^
672
673The first step in using :mod:`optparse` is to create an OptionParser instance::
674
675 parser = OptionParser(...)
676
677The OptionParser constructor has no required arguments, but a number of optional
678keyword arguments. You should always pass them as keyword arguments, i.e. do
679not rely on the order in which the arguments are declared.
680
681 ``usage`` (default: ``"%prog [options]"``)
682 The usage summary to print when your program is run incorrectly or with a help
683 option. When :mod:`optparse` prints the usage string, it expands ``%prog`` to
684 ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you passed that keyword
685 argument). To suppress a usage message, pass the special value
686 ``optparse.SUPPRESS_USAGE``.
687
688 ``option_list`` (default: ``[]``)
689 A list of Option objects to populate the parser with. The options in
690 ``option_list`` are added after any options in ``standard_option_list`` (a class
691 attribute that may be set by OptionParser subclasses), but before any version or
692 help options. Deprecated; use :meth:`add_option` after creating the parser
693 instead.
694
695 ``option_class`` (default: optparse.Option)
696 Class to use when adding options to the parser in :meth:`add_option`.
697
698 ``version`` (default: ``None``)
699 A version string to print when the user supplies a version option. If you supply
700 a true value for ``version``, :mod:`optparse` automatically adds a version
701 option with the single option string ``"--version"``. The substring ``"%prog"``
702 is expanded the same as for ``usage``.
703
704 ``conflict_handler`` (default: ``"error"``)
705 Specifies what to do when options with conflicting option strings are added to
706 the parser; see section :ref:`optparse-conflicts-between-options`.
707
708 ``description`` (default: ``None``)
709 A paragraph of text giving a brief overview of your program. :mod:`optparse`
710 reformats this paragraph to fit the current terminal width and prints it when
711 the user requests help (after ``usage``, but before the list of options).
712
713 ``formatter`` (default: a new IndentedHelpFormatter)
714 An instance of optparse.HelpFormatter that will be used for printing help text.
715 :mod:`optparse` provides two concrete classes for this purpose:
716 IndentedHelpFormatter and TitledHelpFormatter.
717
718 ``add_help_option`` (default: ``True``)
719 If true, :mod:`optparse` will add a help option (with option strings ``"-h"``
720 and ``"--help"``) to the parser.
721
722 ``prog``
723 The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
724 instead of ``os.path.basename(sys.argv[0])``.
725
726
727
728.. _optparse-populating-parser:
729
730Populating the parser
731^^^^^^^^^^^^^^^^^^^^^
732
733There are several ways to populate the parser with options. The preferred way
734is by using ``OptionParser.add_option()``, as shown in section
735:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
736
737* pass it an Option instance (as returned by :func:`make_option`)
738
739* pass it any combination of positional and keyword arguments that are
740 acceptable to :func:`make_option` (i.e., to the Option constructor), and it will
741 create the Option instance for you
742
743The other alternative is to pass a list of pre-constructed Option instances to
744the OptionParser constructor, as in::
745
746 option_list = [
747 make_option("-f", "--filename",
748 action="store", type="string", dest="filename"),
749 make_option("-q", "--quiet",
750 action="store_false", dest="verbose"),
751 ]
752 parser = OptionParser(option_list=option_list)
753
754(:func:`make_option` is a factory function for creating Option instances;
755currently it is an alias for the Option constructor. A future version of
756:mod:`optparse` may split Option into several classes, and :func:`make_option`
757will pick the right class to instantiate. Do not instantiate Option directly.)
758
759
760.. _optparse-defining-options:
761
762Defining options
763^^^^^^^^^^^^^^^^
764
765Each Option instance represents a set of synonymous command-line option strings,
766e.g. :option:`-f` and :option:`--file`. You can specify any number of short or
767long option strings, but you must specify at least one overall option string.
768
769The canonical way to create an Option instance is with the :meth:`add_option`
770method of :class:`OptionParser`::
771
772 parser.add_option(opt_str[, ...], attr=value, ...)
773
774To define an option with only a short option string::
775
776 parser.add_option("-f", attr=value, ...)
777
778And to define an option with only a long option string::
779
780 parser.add_option("--foo", attr=value, ...)
781
782The keyword arguments define attributes of the new Option object. The most
783important option attribute is :attr:`action`, and it largely determines which
784other attributes are relevant or required. If you pass irrelevant option
785attributes, or fail to pass required ones, :mod:`optparse` raises an OptionError
786exception explaining your mistake.
787
788An options's *action* determines what :mod:`optparse` does when it encounters
789this option on the command-line. The standard option actions hard-coded into
790:mod:`optparse` are:
791
792``store``
793 store this option's argument (default)
794
795``store_const``
796 store a constant value
797
798``store_true``
799 store a true value
800
801``store_false``
802 store a false value
803
804``append``
805 append this option's argument to a list
806
807``append_const``
808 append a constant value to a list
809
810``count``
811 increment a counter by one
812
813``callback``
814 call a specified function
815
816:attr:`help`
817 print a usage message including all options and the documentation for them
818
819(If you don't supply an action, the default is ``store``. For this action, you
820may also supply :attr:`type` and :attr:`dest` option attributes; see below.)
821
822As you can see, most actions involve storing or updating a value somewhere.
823:mod:`optparse` always creates a special object for this, conventionally called
824``options`` (it happens to be an instance of ``optparse.Values``). Option
825arguments (and various other values) are stored as attributes of this object,
826according to the :attr:`dest` (destination) option attribute.
827
828For example, when you call ::
829
830 parser.parse_args()
831
832one of the first things :mod:`optparse` does is create the ``options`` object::
833
834 options = Values()
835
836If one of the options in this parser is defined with ::
837
838 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
839
840and the command-line being parsed includes any of the following::
841
842 -ffoo
843 -f foo
844 --file=foo
845 --file foo
846
847then :mod:`optparse`, on seeing this option, will do the equivalent of ::
848
849 options.filename = "foo"
850
851The :attr:`type` and :attr:`dest` option attributes are almost as important as
852:attr:`action`, but :attr:`action` is the only one that makes sense for *all*
853options.
854
855
856.. _optparse-standard-option-actions:
857
858Standard option actions
859^^^^^^^^^^^^^^^^^^^^^^^
860
861The various option actions all have slightly different requirements and effects.
862Most actions have several relevant option attributes which you may specify to
863guide :mod:`optparse`'s behaviour; a few have required attributes, which you
864must specify for any option using that action.
865
866* ``store`` [relevant: :attr:`type`, :attr:`dest`, ``nargs``, ``choices``]
867
868 The option must be followed by an argument, which is converted to a value
869 according to :attr:`type` and stored in :attr:`dest`. If ``nargs`` > 1,
870 multiple arguments will be consumed from the command line; all will be converted
871 according to :attr:`type` and stored to :attr:`dest` as a tuple. See the
872 "Option types" section below.
873
874 If ``choices`` is supplied (a list or tuple of strings), the type defaults to
875 ``choice``.
876
877 If :attr:`type` is not supplied, it defaults to ``string``.
878
879 If :attr:`dest` is not supplied, :mod:`optparse` derives a destination from the
880 first long option string (e.g., ``"--foo-bar"`` implies ``foo_bar``). If there
881 are no long option strings, :mod:`optparse` derives a destination from the first
882 short option string (e.g., ``"-f"`` implies ``f``).
883
884 Example::
885
886 parser.add_option("-f")
887 parser.add_option("-p", type="float", nargs=3, dest="point")
888
889 As it parses the command line ::
890
891 -f foo.txt -p 1 -3.5 4 -fbar.txt
892
893 :mod:`optparse` will set ::
894
895 options.f = "foo.txt"
896 options.point = (1.0, -3.5, 4.0)
897 options.f = "bar.txt"
898
899* ``store_const`` [required: ``const``; relevant: :attr:`dest`]
900
901 The value ``const`` is stored in :attr:`dest`.
902
903 Example::
904
905 parser.add_option("-q", "--quiet",
906 action="store_const", const=0, dest="verbose")
907 parser.add_option("-v", "--verbose",
908 action="store_const", const=1, dest="verbose")
909 parser.add_option("--noisy",
910 action="store_const", const=2, dest="verbose")
911
912 If ``"--noisy"`` is seen, :mod:`optparse` will set ::
913
914 options.verbose = 2
915
916* ``store_true`` [relevant: :attr:`dest`]
917
918 A special case of ``store_const`` that stores a true value to :attr:`dest`.
919
920* ``store_false`` [relevant: :attr:`dest`]
921
922 Like ``store_true``, but stores a false value.
923
924 Example::
925
926 parser.add_option("--clobber", action="store_true", dest="clobber")
927 parser.add_option("--no-clobber", action="store_false", dest="clobber")
928
929* ``append`` [relevant: :attr:`type`, :attr:`dest`, ``nargs``, ``choices``]
930
931 The option must be followed by an argument, which is appended to the list in
932 :attr:`dest`. If no default value for :attr:`dest` is supplied, an empty list
933 is automatically created when :mod:`optparse` first encounters this option on
934 the command-line. If ``nargs`` > 1, multiple arguments are consumed, and a
935 tuple of length ``nargs`` is appended to :attr:`dest`.
936
937 The defaults for :attr:`type` and :attr:`dest` are the same as for the ``store``
938 action.
939
940 Example::
941
942 parser.add_option("-t", "--tracks", action="append", type="int")
943
944 If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
945 of::
946
947 options.tracks = []
948 options.tracks.append(int("3"))
949
950 If, a little later on, ``"--tracks=4"`` is seen, it does::
951
952 options.tracks.append(int("4"))
953
954* ``append_const`` [required: ``const``; relevant: :attr:`dest`]
955
956 Like ``store_const``, but the value ``const`` is appended to :attr:`dest`; as
Georg Brandl97ca5832007-09-24 17:55:47 +0000957 with ``append``, :attr:`dest` defaults to ``None``, and an empty list is
Georg Brandl8ec7f652007-08-15 14:28:01 +0000958 automatically created the first time the option is encountered.
959
960* ``count`` [relevant: :attr:`dest`]
961
962 Increment the integer stored at :attr:`dest`. If no default value is supplied,
963 :attr:`dest` is set to zero before being incremented the first time.
964
965 Example::
966
967 parser.add_option("-v", action="count", dest="verbosity")
968
969 The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
970 equivalent of::
971
972 options.verbosity = 0
973 options.verbosity += 1
974
975 Every subsequent occurrence of ``"-v"`` results in ::
976
977 options.verbosity += 1
978
979* ``callback`` [required: ``callback``; relevant: :attr:`type`, ``nargs``,
980 ``callback_args``, ``callback_kwargs``]
981
982 Call the function specified by ``callback``, which is called as ::
983
984 func(option, opt_str, value, parser, *args, **kwargs)
985
986 See section :ref:`optparse-option-callbacks` for more detail.
987
988* :attr:`help`
989
990 Prints a complete help message for all the options in the current option parser.
991 The help message is constructed from the ``usage`` string passed to
992 OptionParser's constructor and the :attr:`help` string passed to every option.
993
994 If no :attr:`help` string is supplied for an option, it will still be listed in
995 the help message. To omit an option entirely, use the special value
996 ``optparse.SUPPRESS_HELP``.
997
998 :mod:`optparse` automatically adds a :attr:`help` option to all OptionParsers,
999 so you do not normally need to create one.
1000
1001 Example::
1002
1003 from optparse import OptionParser, SUPPRESS_HELP
1004
1005 parser = OptionParser()
1006 parser.add_option("-h", "--help", action="help"),
1007 parser.add_option("-v", action="store_true", dest="verbose",
1008 help="Be moderately verbose")
1009 parser.add_option("--file", dest="filename",
1010 help="Input file to read data from"),
1011 parser.add_option("--secret", help=SUPPRESS_HELP)
1012
1013 If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line, it
1014 will print something like the following help message to stdout (assuming
1015 ``sys.argv[0]`` is ``"foo.py"``)::
1016
1017 usage: foo.py [options]
1018
1019 options:
1020 -h, --help Show this help message and exit
1021 -v Be moderately verbose
1022 --file=FILENAME Input file to read data from
1023
1024 After printing the help message, :mod:`optparse` terminates your process with
1025 ``sys.exit(0)``.
1026
1027* ``version``
1028
1029 Prints the version number supplied to the OptionParser to stdout and exits. The
1030 version number is actually formatted and printed by the ``print_version()``
1031 method of OptionParser. Generally only relevant if the ``version`` argument is
1032 supplied to the OptionParser constructor. As with :attr:`help` options, you
1033 will rarely create ``version`` options, since :mod:`optparse` automatically adds
1034 them when needed.
1035
1036
1037.. _optparse-option-attributes:
1038
1039Option attributes
1040^^^^^^^^^^^^^^^^^
1041
1042The following option attributes may be passed as keyword arguments to
1043``parser.add_option()``. If you pass an option attribute that is not relevant
1044to a particular option, or fail to pass a required option attribute,
1045:mod:`optparse` raises OptionError.
1046
1047* :attr:`action` (default: ``"store"``)
1048
1049 Determines :mod:`optparse`'s behaviour when this option is seen on the command
1050 line; the available options are documented above.
1051
1052* :attr:`type` (default: ``"string"``)
1053
1054 The argument type expected by this option (e.g., ``"string"`` or ``"int"``); the
1055 available option types are documented below.
1056
1057* :attr:`dest` (default: derived from option strings)
1058
1059 If the option's action implies writing or modifying a value somewhere, this
1060 tells :mod:`optparse` where to write it: :attr:`dest` names an attribute of the
1061 ``options`` object that :mod:`optparse` builds as it parses the command line.
1062
1063* ``default`` (deprecated)
1064
1065 The value to use for this option's destination if the option is not seen on the
1066 command line. Deprecated; use ``parser.set_defaults()`` instead.
1067
1068* ``nargs`` (default: 1)
1069
1070 How many arguments of type :attr:`type` should be consumed when this option is
1071 seen. If > 1, :mod:`optparse` will store a tuple of values to :attr:`dest`.
1072
1073* ``const``
1074
1075 For actions that store a constant value, the constant value to store.
1076
1077* ``choices``
1078
1079 For options of type ``"choice"``, the list of strings the user may choose from.
1080
1081* ``callback``
1082
1083 For options with action ``"callback"``, the callable to call when this option
1084 is seen. See section :ref:`optparse-option-callbacks` for detail on the
1085 arguments passed to ``callable``.
1086
1087* ``callback_args``, ``callback_kwargs``
1088
1089 Additional positional and keyword arguments to pass to ``callback`` after the
1090 four standard callback arguments.
1091
1092* :attr:`help`
1093
1094 Help text to print for this option when listing all available options after the
1095 user supplies a :attr:`help` option (such as ``"--help"``). If no help text is
1096 supplied, the option will be listed without help text. To hide this option, use
1097 the special value ``SUPPRESS_HELP``.
1098
1099* ``metavar`` (default: derived from option strings)
1100
1101 Stand-in for the option argument(s) to use when printing help text. See section
1102 :ref:`optparse-tutorial` for an example.
1103
1104
1105.. _optparse-standard-option-types:
1106
1107Standard option types
1108^^^^^^^^^^^^^^^^^^^^^
1109
1110:mod:`optparse` has six built-in option types: ``string``, ``int``, ``long``,
1111``choice``, ``float`` and ``complex``. If you need to add new option types, see
1112section :ref:`optparse-extending-optparse`.
1113
1114Arguments to string options are not checked or converted in any way: the text on
1115the command line is stored in the destination (or passed to the callback) as-is.
1116
1117Integer arguments (type ``int`` or ``long``) are parsed as follows:
1118
1119* if the number starts with ``0x``, it is parsed as a hexadecimal number
1120
1121* if the number starts with ``0``, it is parsed as an octal number
1122
Georg Brandl97ca5832007-09-24 17:55:47 +00001123* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl8ec7f652007-08-15 14:28:01 +00001124
1125* otherwise, the number is parsed as a decimal number
1126
1127
1128The conversion is done by calling either ``int()`` or ``long()`` with the
1129appropriate base (2, 8, 10, or 16). If this fails, so will :mod:`optparse`,
1130although with a more useful error message.
1131
1132``float`` and ``complex`` option arguments are converted directly with
1133``float()`` and ``complex()``, with similar error-handling.
1134
1135``choice`` options are a subtype of ``string`` options. The ``choices`` option
1136attribute (a sequence of strings) defines the set of allowed option arguments.
1137``optparse.check_choice()`` compares user-supplied option arguments against this
1138master list and raises OptionValueError if an invalid string is given.
1139
1140
1141.. _optparse-parsing-arguments:
1142
1143Parsing arguments
1144^^^^^^^^^^^^^^^^^
1145
1146The whole point of creating and populating an OptionParser is to call its
1147:meth:`parse_args` method::
1148
1149 (options, args) = parser.parse_args(args=None, values=None)
1150
1151where the input parameters are
1152
1153``args``
1154 the list of arguments to process (default: ``sys.argv[1:]``)
1155
1156``values``
1157 object to store option arguments in (default: a new instance of optparse.Values)
1158
1159and the return values are
1160
1161``options``
1162 the same object that was passed in as ``options``, or the optparse.Values
1163 instance created by :mod:`optparse`
1164
1165``args``
1166 the leftover positional arguments after all options have been processed
1167
1168The most common usage is to supply neither keyword argument. If you supply
1169``options``, it will be modified with repeated ``setattr()`` calls (roughly one
1170for every option argument stored to an option destination) and returned by
1171:meth:`parse_args`.
1172
1173If :meth:`parse_args` encounters any errors in the argument list, it calls the
1174OptionParser's :meth:`error` method with an appropriate end-user error message.
1175This ultimately terminates your process with an exit status of 2 (the
1176traditional Unix exit status for command-line errors).
1177
1178
1179.. _optparse-querying-manipulating-option-parser:
1180
1181Querying and manipulating your option parser
1182^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1183
1184Sometimes, it's useful to poke around your option parser and see what's there.
1185OptionParser provides a couple of methods to help you out:
1186
1187``has_option(opt_str)``
1188 Return true if the OptionParser has an option with option string ``opt_str``
1189 (e.g., ``"-q"`` or ``"--verbose"``).
1190
1191``get_option(opt_str)``
1192 Returns the Option instance with the option string ``opt_str``, or ``None`` if
1193 no options have that option string.
1194
1195``remove_option(opt_str)``
1196 If the OptionParser has an option corresponding to ``opt_str``, that option is
1197 removed. If that option provided any other option strings, all of those option
1198 strings become invalid. If ``opt_str`` does not occur in any option belonging to
1199 this OptionParser, raises ValueError.
1200
1201
1202.. _optparse-conflicts-between-options:
1203
1204Conflicts between options
1205^^^^^^^^^^^^^^^^^^^^^^^^^
1206
1207If you're not careful, it's easy to define options with conflicting option
1208strings::
1209
1210 parser.add_option("-n", "--dry-run", ...)
1211 [...]
1212 parser.add_option("-n", "--noisy", ...)
1213
1214(This is particularly true if you've defined your own OptionParser subclass with
1215some standard options.)
1216
1217Every time you add an option, :mod:`optparse` checks for conflicts with existing
1218options. If it finds any, it invokes the current conflict-handling mechanism.
1219You can set the conflict-handling mechanism either in the constructor::
1220
1221 parser = OptionParser(..., conflict_handler=handler)
1222
1223or with a separate call::
1224
1225 parser.set_conflict_handler(handler)
1226
1227The available conflict handlers are:
1228
1229 ``error`` (default)
1230 assume option conflicts are a programming error and raise OptionConflictError
1231
1232 ``resolve``
1233 resolve option conflicts intelligently (see below)
1234
1235
1236As an example, let's define an OptionParser that resolves conflicts
1237intelligently and add conflicting options to it::
1238
1239 parser = OptionParser(conflict_handler="resolve")
1240 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1241 parser.add_option("-n", "--noisy", ..., help="be noisy")
1242
1243At this point, :mod:`optparse` detects that a previously-added option is already
1244using the ``"-n"`` option string. Since ``conflict_handler`` is ``"resolve"``,
1245it resolves the situation by removing ``"-n"`` from the earlier option's list of
1246option strings. Now ``"--dry-run"`` is the only way for the user to activate
1247that option. If the user asks for help, the help message will reflect that::
1248
1249 options:
1250 --dry-run do no harm
1251 [...]
1252 -n, --noisy be noisy
1253
1254It's possible to whittle away the option strings for a previously-added option
1255until there are none left, and the user has no way of invoking that option from
1256the command-line. In that case, :mod:`optparse` removes that option completely,
1257so it doesn't show up in help text or anywhere else. Carrying on with our
1258existing OptionParser::
1259
1260 parser.add_option("--dry-run", ..., help="new dry-run option")
1261
1262At this point, the original :option:`-n/--dry-run` option is no longer
1263accessible, so :mod:`optparse` removes it, leaving this help text::
1264
1265 options:
1266 [...]
1267 -n, --noisy be noisy
1268 --dry-run new dry-run option
1269
1270
1271.. _optparse-cleanup:
1272
1273Cleanup
1274^^^^^^^
1275
1276OptionParser instances have several cyclic references. This should not be a
1277problem for Python's garbage collector, but you may wish to break the cyclic
1278references explicitly by calling ``destroy()`` on your OptionParser once you are
1279done with it. This is particularly useful in long-running applications where
1280large object graphs are reachable from your OptionParser.
1281
1282
1283.. _optparse-other-methods:
1284
1285Other methods
1286^^^^^^^^^^^^^
1287
1288OptionParser supports several other public methods:
1289
1290* ``set_usage(usage)``
1291
1292 Set the usage string according to the rules described above for the ``usage``
1293 constructor keyword argument. Passing ``None`` sets the default usage string;
1294 use ``SUPPRESS_USAGE`` to suppress a usage message.
1295
1296* ``enable_interspersed_args()``, ``disable_interspersed_args()``
1297
1298 Enable/disable positional arguments interspersed with options, similar to GNU
1299 getopt (enabled by default). For example, if ``"-a"`` and ``"-b"`` are both
1300 simple options that take no arguments, :mod:`optparse` normally accepts this
1301 syntax::
1302
1303 prog -a arg1 -b arg2
1304
1305 and treats it as equivalent to ::
1306
1307 prog -a -b arg1 arg2
1308
1309 To disable this feature, call ``disable_interspersed_args()``. This restores
1310 traditional Unix syntax, where option parsing stops with the first non-option
1311 argument.
1312
1313* ``set_defaults(dest=value, ...)``
1314
1315 Set default values for several option destinations at once. Using
1316 :meth:`set_defaults` is the preferred way to set default values for options,
1317 since multiple options can share the same destination. For example, if several
1318 "mode" options all set the same destination, any one of them can set the
1319 default, and the last one wins::
1320
1321 parser.add_option("--advanced", action="store_const",
1322 dest="mode", const="advanced",
1323 default="novice") # overridden below
1324 parser.add_option("--novice", action="store_const",
1325 dest="mode", const="novice",
1326 default="advanced") # overrides above setting
1327
1328 To avoid this confusion, use :meth:`set_defaults`::
1329
1330 parser.set_defaults(mode="advanced")
1331 parser.add_option("--advanced", action="store_const",
1332 dest="mode", const="advanced")
1333 parser.add_option("--novice", action="store_const",
1334 dest="mode", const="novice")
1335
1336.. % $Id: reference.txt 519 2006-06-11 14:39:11Z gward $
1337
1338
1339.. _optparse-option-callbacks:
1340
1341Option Callbacks
1342----------------
1343
1344When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1345needs, you have two choices: extend :mod:`optparse` or define a callback option.
1346Extending :mod:`optparse` is more general, but overkill for a lot of simple
1347cases. Quite often a simple callback is all you need.
1348
1349There are two steps to defining a callback option:
1350
1351* define the option itself using the ``callback`` action
1352
1353* write the callback; this is a function (or method) that takes at least four
1354 arguments, as described below
1355
1356
1357.. _optparse-defining-callback-option:
1358
1359Defining a callback option
1360^^^^^^^^^^^^^^^^^^^^^^^^^^
1361
1362As always, the easiest way to define a callback option is by using the
1363``parser.add_option()`` method. Apart from :attr:`action`, the only option
1364attribute you must specify is ``callback``, the function to call::
1365
1366 parser.add_option("-c", action="callback", callback=my_callback)
1367
1368``callback`` is a function (or other callable object), so you must have already
1369defined ``my_callback()`` when you create this callback option. In this simple
1370case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,
1371which usually means that the option takes no arguments---the mere presence of
1372:option:`-c` on the command-line is all it needs to know. In some
1373circumstances, though, you might want your callback to consume an arbitrary
1374number of command-line arguments. This is where writing callbacks gets tricky;
1375it's covered later in this section.
1376
1377:mod:`optparse` always passes four particular arguments to your callback, and it
1378will only pass additional arguments if you specify them via ``callback_args``
1379and ``callback_kwargs``. Thus, the minimal callback function signature is::
1380
1381 def my_callback(option, opt, value, parser):
1382
1383The four arguments to a callback are described below.
1384
1385There are several other option attributes that you can supply when you define a
1386callback option:
1387
1388:attr:`type`
1389 has its usual meaning: as with the ``store`` or ``append`` actions, it instructs
1390 :mod:`optparse` to consume one argument and convert it to :attr:`type`. Rather
1391 than storing the converted value(s) anywhere, though, :mod:`optparse` passes it
1392 to your callback function.
1393
1394``nargs``
1395 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
1396 consume ``nargs`` arguments, each of which must be convertible to :attr:`type`.
1397 It then passes a tuple of converted values to your callback.
1398
1399``callback_args``
1400 a tuple of extra positional arguments to pass to the callback
1401
1402``callback_kwargs``
1403 a dictionary of extra keyword arguments to pass to the callback
1404
1405
1406.. _optparse-how-callbacks-called:
1407
1408How callbacks are called
1409^^^^^^^^^^^^^^^^^^^^^^^^
1410
1411All callbacks are called as follows::
1412
1413 func(option, opt_str, value, parser, *args, **kwargs)
1414
1415where
1416
1417``option``
1418 is the Option instance that's calling the callback
1419
1420``opt_str``
1421 is the option string seen on the command-line that's triggering the callback.
1422 (If an abbreviated long option was used, ``opt_str`` will be the full, canonical
1423 option string---e.g. if the user puts ``"--foo"`` on the command-line as an
1424 abbreviation for ``"--foobar"``, then ``opt_str`` will be ``"--foobar"``.)
1425
1426``value``
1427 is the argument to this option seen on the command-line. :mod:`optparse` will
1428 only expect an argument if :attr:`type` is set; the type of ``value`` will be
1429 the type implied by the option's type. If :attr:`type` for this option is
1430 ``None`` (no argument expected), then ``value`` will be ``None``. If ``nargs``
1431 > 1, ``value`` will be a tuple of values of the appropriate type.
1432
1433``parser``
1434 is the OptionParser instance driving the whole thing, mainly useful because you
1435 can access some other interesting data through its instance attributes:
1436
1437 ``parser.largs``
1438 the current list of leftover arguments, ie. arguments that have been consumed
1439 but are neither options nor option arguments. Feel free to modify
1440 ``parser.largs``, e.g. by adding more arguments to it. (This list will become
1441 ``args``, the second return value of :meth:`parse_args`.)
1442
1443 ``parser.rargs``
1444 the current list of remaining arguments, ie. with ``opt_str`` and ``value`` (if
1445 applicable) removed, and only the arguments following them still there. Feel
1446 free to modify ``parser.rargs``, e.g. by consuming more arguments.
1447
1448 ``parser.values``
1449 the object where option values are by default stored (an instance of
1450 optparse.OptionValues). This lets callbacks use the same mechanism as the rest
1451 of :mod:`optparse` for storing option values; you don't need to mess around with
1452 globals or closures. You can also access or modify the value(s) of any options
1453 already encountered on the command-line.
1454
1455``args``
1456 is a tuple of arbitrary positional arguments supplied via the ``callback_args``
1457 option attribute.
1458
1459``kwargs``
1460 is a dictionary of arbitrary keyword arguments supplied via ``callback_kwargs``.
1461
1462
1463.. _optparse-raising-errors-in-callback:
1464
1465Raising errors in a callback
1466^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1467
1468The callback function should raise OptionValueError if there are any problems
1469with the option or its argument(s). :mod:`optparse` catches this and terminates
1470the program, printing the error message you supply to stderr. Your message
1471should be clear, concise, accurate, and mention the option at fault. Otherwise,
1472the user will have a hard time figuring out what he did wrong.
1473
1474
1475.. _optparse-callback-example-1:
1476
1477Callback example 1: trivial callback
1478^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1479
1480Here's an example of a callback option that takes no arguments, and simply
1481records that the option was seen::
1482
1483 def record_foo_seen(option, opt_str, value, parser):
1484 parser.saw_foo = True
1485
1486 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1487
1488Of course, you could do that with the ``store_true`` action.
1489
1490
1491.. _optparse-callback-example-2:
1492
1493Callback example 2: check option order
1494^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1495
1496Here's a slightly more interesting example: record the fact that ``"-a"`` is
1497seen, but blow up if it comes after ``"-b"`` in the command-line. ::
1498
1499 def check_order(option, opt_str, value, parser):
1500 if parser.values.b:
1501 raise OptionValueError("can't use -a after -b")
1502 parser.values.a = 1
1503 [...]
1504 parser.add_option("-a", action="callback", callback=check_order)
1505 parser.add_option("-b", action="store_true", dest="b")
1506
1507
1508.. _optparse-callback-example-3:
1509
1510Callback example 3: check option order (generalized)
1511^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1512
1513If you want to re-use this callback for several similar options (set a flag, but
1514blow up if ``"-b"`` has already been seen), it needs a bit of work: the error
1515message and the flag that it sets must be generalized. ::
1516
1517 def check_order(option, opt_str, value, parser):
1518 if parser.values.b:
1519 raise OptionValueError("can't use %s after -b" % opt_str)
1520 setattr(parser.values, option.dest, 1)
1521 [...]
1522 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1523 parser.add_option("-b", action="store_true", dest="b")
1524 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1525
1526
1527.. _optparse-callback-example-4:
1528
1529Callback example 4: check arbitrary condition
1530^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1531
1532Of course, you could put any condition in there---you're not limited to checking
1533the values of already-defined options. For example, if you have options that
1534should not be called when the moon is full, all you have to do is this::
1535
1536 def check_moon(option, opt_str, value, parser):
1537 if is_moon_full():
1538 raise OptionValueError("%s option invalid when moon is full"
1539 % opt_str)
1540 setattr(parser.values, option.dest, 1)
1541 [...]
1542 parser.add_option("--foo",
1543 action="callback", callback=check_moon, dest="foo")
1544
1545(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1546
1547
1548.. _optparse-callback-example-5:
1549
1550Callback example 5: fixed arguments
1551^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1552
1553Things get slightly more interesting when you define callback options that take
1554a fixed number of arguments. Specifying that a callback option takes arguments
1555is similar to defining a ``store`` or ``append`` option: if you define
1556:attr:`type`, then the option takes one argument that must be convertible to
1557that type; if you further define ``nargs``, then the option takes ``nargs``
1558arguments.
1559
1560Here's an example that just emulates the standard ``store`` action::
1561
1562 def store_value(option, opt_str, value, parser):
1563 setattr(parser.values, option.dest, value)
1564 [...]
1565 parser.add_option("--foo",
1566 action="callback", callback=store_value,
1567 type="int", nargs=3, dest="foo")
1568
1569Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1570them to integers for you; all you have to do is store them. (Or whatever;
1571obviously you don't need a callback for this example.)
1572
1573
1574.. _optparse-callback-example-6:
1575
1576Callback example 6: variable arguments
1577^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1578
1579Things get hairy when you want an option to take a variable number of arguments.
1580For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1581built-in capabilities for it. And you have to deal with certain intricacies of
1582conventional Unix command-line parsing that :mod:`optparse` normally handles for
1583you. In particular, callbacks should implement the conventional rules for bare
1584``"--"`` and ``"-"`` arguments:
1585
1586* either ``"--"`` or ``"-"`` can be option arguments
1587
1588* bare ``"--"`` (if not the argument to some option): halt command-line
1589 processing and discard the ``"--"``
1590
1591* bare ``"-"`` (if not the argument to some option): halt command-line
1592 processing but keep the ``"-"`` (append it to ``parser.largs``)
1593
1594If you want an option that takes a variable number of arguments, there are
1595several subtle, tricky issues to worry about. The exact implementation you
1596choose will be based on which trade-offs you're willing to make for your
1597application (which is why :mod:`optparse` doesn't support this sort of thing
1598directly).
1599
1600Nevertheless, here's a stab at a callback for an option with variable
1601arguments::
1602
1603 def vararg_callback(option, opt_str, value, parser):
1604 assert value is None
1605 done = 0
1606 value = []
1607 rargs = parser.rargs
1608 while rargs:
1609 arg = rargs[0]
1610
1611 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1612 # etc. Note that this also stops on "-3" or "-3.0", so if
1613 # your option takes numeric values, you will need to handle
1614 # this.
1615 if ((arg[:2] == "--" and len(arg) > 2) or
1616 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1617 break
1618 else:
1619 value.append(arg)
1620 del rargs[0]
1621
1622 setattr(parser.values, option.dest, value)
1623
1624 [...]
1625 parser.add_option("-c", "--callback",
1626 action="callback", callback=varargs)
1627
1628The main weakness with this particular implementation is that negative numbers
1629in the arguments following ``"-c"`` will be interpreted as further options
1630(probably causing an error), rather than as arguments to ``"-c"``. Fixing this
1631is left as an exercise for the reader.
1632
1633.. % $Id: callbacks.txt 415 2004-09-30 02:26:17Z greg $
1634
1635
1636.. _optparse-extending-optparse:
1637
1638Extending :mod:`optparse`
1639-------------------------
1640
1641Since the two major controlling factors in how :mod:`optparse` interprets
1642command-line options are the action and type of each option, the most likely
1643direction of extension is to add new actions and new types.
1644
1645
1646.. _optparse-adding-new-types:
1647
1648Adding new types
1649^^^^^^^^^^^^^^^^
1650
1651To add new types, you need to define your own subclass of :mod:`optparse`'s
1652Option class. This class has a couple of attributes that define
1653:mod:`optparse`'s types: :attr:`TYPES` and :attr:`TYPE_CHECKER`.
1654
1655:attr:`TYPES` is a tuple of type names; in your subclass, simply define a new
1656tuple :attr:`TYPES` that builds on the standard one.
1657
1658:attr:`TYPE_CHECKER` is a dictionary mapping type names to type-checking
1659functions. A type-checking function has the following signature::
1660
1661 def check_mytype(option, opt, value)
1662
1663where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1664(e.g., ``"-f"``), and ``value`` is the string from the command line that must be
1665checked and converted to your desired type. ``check_mytype()`` should return an
1666object of the hypothetical type ``mytype``. The value returned by a
1667type-checking function will wind up in the OptionValues instance returned by
1668:meth:`OptionParser.parse_args`, or be passed to a callback as the ``value``
1669parameter.
1670
1671Your type-checking function should raise OptionValueError if it encounters any
1672problems. OptionValueError takes a single string argument, which is passed
1673as-is to OptionParser's :meth:`error` method, which in turn prepends the program
1674name and the string ``"error:"`` and prints everything to stderr before
1675terminating the process.
1676
1677Here's a silly example that demonstrates adding a ``complex`` option type to
1678parse Python-style complex numbers on the command line. (This is even sillier
1679than it used to be, because :mod:`optparse` 1.3 added built-in support for
1680complex numbers, but never mind.)
1681
1682First, the necessary imports::
1683
1684 from copy import copy
1685 from optparse import Option, OptionValueError
1686
1687You need to define your type-checker first, since it's referred to later (in the
1688:attr:`TYPE_CHECKER` class attribute of your Option subclass)::
1689
1690 def check_complex(option, opt, value):
1691 try:
1692 return complex(value)
1693 except ValueError:
1694 raise OptionValueError(
1695 "option %s: invalid complex value: %r" % (opt, value))
1696
1697Finally, the Option subclass::
1698
1699 class MyOption (Option):
1700 TYPES = Option.TYPES + ("complex",)
1701 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1702 TYPE_CHECKER["complex"] = check_complex
1703
1704(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
1705up modifying the :attr:`TYPE_CHECKER` attribute of :mod:`optparse`'s Option
1706class. This being Python, nothing stops you from doing that except good manners
1707and common sense.)
1708
1709That's it! Now you can write a script that uses the new option type just like
1710any other :mod:`optparse`\ -based script, except you have to instruct your
1711OptionParser to use MyOption instead of Option::
1712
1713 parser = OptionParser(option_class=MyOption)
1714 parser.add_option("-c", type="complex")
1715
1716Alternately, you can build your own option list and pass it to OptionParser; if
1717you don't use :meth:`add_option` in the above way, you don't need to tell
1718OptionParser which option class to use::
1719
1720 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1721 parser = OptionParser(option_list=option_list)
1722
1723
1724.. _optparse-adding-new-actions:
1725
1726Adding new actions
1727^^^^^^^^^^^^^^^^^^
1728
1729Adding new actions is a bit trickier, because you have to understand that
1730:mod:`optparse` has a couple of classifications for actions:
1731
1732"store" actions
1733 actions that result in :mod:`optparse` storing a value to an attribute of the
1734 current OptionValues instance; these options require a :attr:`dest` attribute to
1735 be supplied to the Option constructor
1736
1737"typed" actions
1738 actions that take a value from the command line and expect it to be of a certain
1739 type; or rather, a string that can be converted to a certain type. These
1740 options require a :attr:`type` attribute to the Option constructor.
1741
1742These are overlapping sets: some default "store" actions are ``store``,
1743``store_const``, ``append``, and ``count``, while the default "typed" actions
1744are ``store``, ``append``, and ``callback``.
1745
1746When you add an action, you need to categorize it by listing it in at least one
1747of the following class attributes of Option (all are lists of strings):
1748
1749:attr:`ACTIONS`
1750 all actions must be listed in ACTIONS
1751
1752:attr:`STORE_ACTIONS`
1753 "store" actions are additionally listed here
1754
1755:attr:`TYPED_ACTIONS`
1756 "typed" actions are additionally listed here
1757
1758``ALWAYS_TYPED_ACTIONS``
1759 actions that always take a type (i.e. whose options always take a value) are
1760 additionally listed here. The only effect of this is that :mod:`optparse`
1761 assigns the default type, ``string``, to options with no explicit type whose
1762 action is listed in ``ALWAYS_TYPED_ACTIONS``.
1763
1764In order to actually implement your new action, you must override Option's
1765:meth:`take_action` method and add a case that recognizes your action.
1766
1767For example, let's add an ``extend`` action. This is similar to the standard
1768``append`` action, but instead of taking a single value from the command-line
1769and appending it to an existing list, ``extend`` will take multiple values in a
1770single comma-delimited string, and extend an existing list with them. That is,
1771if ``"--names"`` is an ``extend`` option of type ``string``, the command line
1772::
1773
1774 --names=foo,bar --names blah --names ding,dong
1775
1776would result in a list ::
1777
1778 ["foo", "bar", "blah", "ding", "dong"]
1779
1780Again we define a subclass of Option::
1781
1782 class MyOption (Option):
1783
1784 ACTIONS = Option.ACTIONS + ("extend",)
1785 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1786 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1787 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1788
1789 def take_action(self, action, dest, opt, value, values, parser):
1790 if action == "extend":
1791 lvalue = value.split(",")
1792 values.ensure_value(dest, []).extend(lvalue)
1793 else:
1794 Option.take_action(
1795 self, action, dest, opt, value, values, parser)
1796
1797Features of note:
1798
1799* ``extend`` both expects a value on the command-line and stores that value
1800 somewhere, so it goes in both :attr:`STORE_ACTIONS` and :attr:`TYPED_ACTIONS`
1801
1802* to ensure that :mod:`optparse` assigns the default type of ``string`` to
1803 ``extend`` actions, we put the ``extend`` action in ``ALWAYS_TYPED_ACTIONS`` as
1804 well
1805
1806* :meth:`MyOption.take_action` implements just this one new action, and passes
1807 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
1808 actions
1809
1810* ``values`` is an instance of the optparse_parser.Values class, which
1811 provides the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1812 essentially :func:`getattr` with a safety valve; it is called as ::
1813
1814 values.ensure_value(attr, value)
1815
1816 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
1817 ensure_value() first sets it to ``value``, and then returns 'value. This is very
1818 handy for actions like ``extend``, ``append``, and ``count``, all of which
1819 accumulate data in a variable and expect that variable to be of a certain type
1820 (a list for the first two, an integer for the latter). Using
1821 :meth:`ensure_value` means that scripts using your action don't have to worry
1822 about setting a default value for the option destinations in question; they can
1823 just leave the default as None and :meth:`ensure_value` will take care of
1824 getting it right when it's needed.
1825
1826.. % $Id: extending.txt 517 2006-06-10 16:18:11Z gward $
1827