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