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