blob: 90c28a0487156a9f73107f15c9103c0ad2871c2c [file] [log] [blame]
Steven Bethard6d265692010-03-02 09:22:57 +00001:mod:`optparse` --- Parser for command line options
2===================================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
4.. module:: optparse
Steven Bethard6d265692010-03-02 09:22:57 +00005 :synopsis: Command-line option parsing library.
Georg Brandl116aa622007-08-15 14:28:22 +00006.. moduleauthor:: Greg Ward <gward@python.net>
Georg Brandl116aa622007-08-15 14:28:22 +00007.. sectionauthor:: Greg Ward <gward@python.net>
8
9
Georg Brandl15a515f2009-09-17 22:11:49 +000010:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
11command-line options than the old :mod:`getopt` module. :mod:`optparse` uses a
12more declarative style of command-line parsing: you create an instance of
13:class:`OptionParser`, populate it with options, and parse the command
14line. :mod:`optparse` allows users to specify options in the conventional
15GNU/POSIX syntax, and additionally generates usage and help messages for you.
Georg Brandl116aa622007-08-15 14:28:22 +000016
Georg Brandl15a515f2009-09-17 22:11:49 +000017Here's an example of using :mod:`optparse` in a simple script::
Georg Brandl116aa622007-08-15 14:28:22 +000018
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
Georg Brandl15a515f2009-09-17 22:11:49 +000035As it parses the command line, :mod:`optparse` sets attributes of the
36``options`` object returned by :meth:`parse_args` based on user-supplied
37command-line values. When :meth:`parse_args` returns from parsing this command
38line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
39``False``. :mod:`optparse` supports both long and short options, allows short
Georg Brandl116aa622007-08-15 14:28:22 +000040options 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
Ezio Melotti383ae952010-01-03 09:06:02 +000054and :mod:`optparse` will print out a brief summary of your script's options:
55
56.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +000057
58 usage: <yourscript> [options]
59
60 options:
61 -h, --help show this help message and exit
62 -f FILE, --file=FILE write report to FILE
63 -q, --quiet don't print status messages to stdout
64
65where the value of *yourscript* is determined at runtime (normally from
66``sys.argv[0]``).
67
Georg Brandl116aa622007-08-15 14:28:22 +000068
69.. _optparse-background:
70
71Background
72----------
73
74:mod:`optparse` was explicitly designed to encourage the creation of programs
75with straightforward, conventional command-line interfaces. To that end, it
76supports only the most common command-line syntax and semantics conventionally
77used under Unix. If you are unfamiliar with these conventions, read this
78section to acquaint yourself with them.
79
80
81.. _optparse-terminology:
82
83Terminology
84^^^^^^^^^^^
85
86argument
Georg Brandl15a515f2009-09-17 22:11:49 +000087 a string entered on the command-line, and passed by the shell to ``execl()``
88 or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
89 (``sys.argv[0]`` is the name of the program being executed). Unix shells
90 also use the term "word".
Georg Brandl116aa622007-08-15 14:28:22 +000091
92 It is occasionally desirable to substitute an argument list other than
93 ``sys.argv[1:]``, so you should read "argument" as "an element of
94 ``sys.argv[1:]``, or of some other list provided as a substitute for
95 ``sys.argv[1:]``".
96
Benjamin Petersonae5360b2008-09-08 23:05:23 +000097option
Georg Brandl15a515f2009-09-17 22:11:49 +000098 an argument used to supply extra information to guide or customize the
99 execution of a program. There are many different syntaxes for options; the
100 traditional Unix syntax is a hyphen ("-") followed by a single letter,
101 e.g. ``"-x"`` or ``"-F"``. Also, traditional Unix syntax allows multiple
102 options to be merged into a single argument, e.g. ``"-x -F"`` is equivalent
103 to ``"-xF"``. The GNU project introduced ``"--"`` followed by a series of
104 hyphen-separated words, e.g. ``"--file"`` or ``"--dry-run"``. These are the
105 only two option syntaxes provided by :mod:`optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107 Some other option syntaxes that the world has seen include:
108
109 * a hyphen followed by a few letters, e.g. ``"-pf"`` (this is *not* the same
110 as multiple options merged into a single argument)
111
112 * a hyphen followed by a whole word, e.g. ``"-file"`` (this is technically
113 equivalent to the previous syntax, but they aren't usually seen in the same
114 program)
115
116 * a plus sign followed by a single letter, or a few letters, or a word, e.g.
117 ``"+f"``, ``"+rgb"``
118
119 * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
120 ``"/file"``
121
Georg Brandl15a515f2009-09-17 22:11:49 +0000122 These option syntaxes are not supported by :mod:`optparse`, and they never
123 will be. This is deliberate: the first three are non-standard on any
124 environment, and the last only makes sense if you're exclusively targeting
125 VMS, MS-DOS, and/or Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127option argument
Georg Brandl15a515f2009-09-17 22:11:49 +0000128 an argument that follows an option, is closely associated with that option,
129 and is consumed from the argument list when that option is. With
130 :mod:`optparse`, option arguments may either be in a separate argument from
Ezio Melotti383ae952010-01-03 09:06:02 +0000131 their option:
132
133 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135 -f foo
136 --file foo
137
Ezio Melotti383ae952010-01-03 09:06:02 +0000138 or included in the same argument:
139
140 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000141
142 -ffoo
143 --file=foo
144
Georg Brandl15a515f2009-09-17 22:11:49 +0000145 Typically, a given option either takes an argument or it doesn't. Lots of
146 people want an "optional option arguments" feature, meaning that some options
147 will take an argument if they see it, and won't if they don't. This is
148 somewhat controversial, because it makes parsing ambiguous: if ``"-a"`` takes
149 an optional argument and ``"-b"`` is another option entirely, how do we
150 interpret ``"-ab"``? Because of this ambiguity, :mod:`optparse` does not
151 support this feature.
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153positional argument
154 something leftover in the argument list after options have been parsed, i.e.
Georg Brandl15a515f2009-09-17 22:11:49 +0000155 after options and their arguments have been parsed and removed from the
156 argument list.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158required option
159 an option that must be supplied on the command-line; note that the phrase
160 "required option" is self-contradictory in English. :mod:`optparse` doesn't
Georg Brandl15a515f2009-09-17 22:11:49 +0000161 prevent you from implementing required options, but doesn't give you much
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000162 help at it either.
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164For example, consider this hypothetical command-line::
165
166 prog -v --report /tmp/report.txt foo bar
167
168``"-v"`` and ``"--report"`` are both options. Assuming that :option:`--report`
169takes one argument, ``"/tmp/report.txt"`` is an option argument. ``"foo"`` and
170``"bar"`` are positional arguments.
171
172
173.. _optparse-what-options-for:
174
175What are options for?
176^^^^^^^^^^^^^^^^^^^^^
177
178Options are used to provide extra information to tune or customize the execution
179of a program. In case it wasn't clear, options are usually *optional*. A
180program should be able to run just fine with no options whatsoever. (Pick a
181random program from the Unix or GNU toolsets. Can it run without any options at
182all and still make sense? The main exceptions are ``find``, ``tar``, and
183``dd``\ ---all of which are mutant oddballs that have been rightly criticized
184for their non-standard syntax and confusing interfaces.)
185
186Lots of people want their programs to have "required options". Think about it.
187If it's required, then it's *not optional*! If there is a piece of information
188that your program absolutely requires in order to run successfully, that's what
189positional arguments are for.
190
191As an example of good command-line interface design, consider the humble ``cp``
192utility, for copying files. It doesn't make much sense to try to copy files
193without supplying a destination and at least one source. Hence, ``cp`` fails if
194you run it with no arguments. However, it has a flexible, useful syntax that
195does not require any options at all::
196
197 cp SOURCE DEST
198 cp SOURCE ... DEST-DIR
199
200You can get pretty far with just that. Most ``cp`` implementations provide a
201bunch of options to tweak exactly how the files are copied: you can preserve
202mode and modification time, avoid following symlinks, ask before clobbering
203existing files, etc. But none of this distracts from the core mission of
204``cp``, which is to copy either one file to another, or several files to another
205directory.
206
207
208.. _optparse-what-positional-arguments-for:
209
210What are positional arguments for?
211^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
212
213Positional arguments are for those pieces of information that your program
214absolutely, positively requires to run.
215
216A good user interface should have as few absolute requirements as possible. If
217your program requires 17 distinct pieces of information in order to run
218successfully, it doesn't much matter *how* you get that information from the
219user---most people will give up and walk away before they successfully run the
220program. This applies whether the user interface is a command-line, a
221configuration file, or a GUI: if you make that many demands on your users, most
222of them will simply give up.
223
224In short, try to minimize the amount of information that users are absolutely
225required to supply---use sensible defaults whenever possible. Of course, you
226also want to make your programs reasonably flexible. That's what options are
227for. Again, it doesn't matter if they are entries in a config file, widgets in
228the "Preferences" dialog of a GUI, or command-line options---the more options
229you implement, the more flexible your program is, and the more complicated its
230implementation becomes. Too much flexibility has drawbacks as well, of course;
231too many options can overwhelm users and make your code much harder to maintain.
232
Georg Brandl116aa622007-08-15 14:28:22 +0000233
234.. _optparse-tutorial:
235
236Tutorial
237--------
238
239While :mod:`optparse` is quite flexible and powerful, it's also straightforward
240to use in most cases. This section covers the code patterns that are common to
241any :mod:`optparse`\ -based program.
242
243First, you need to import the OptionParser class; then, early in the main
244program, create an OptionParser instance::
245
246 from optparse import OptionParser
247 [...]
248 parser = OptionParser()
249
250Then you can start defining options. The basic syntax is::
251
252 parser.add_option(opt_str, ...,
253 attr=value, ...)
254
255Each option has one or more option strings, such as ``"-f"`` or ``"--file"``,
256and several option attributes that tell :mod:`optparse` what to expect and what
257to do when it encounters that option on the command line.
258
259Typically, each option will have one short option string and one long option
260string, e.g.::
261
262 parser.add_option("-f", "--file", ...)
263
264You're free to define as many short option strings and as many long option
265strings as you like (including zero), as long as there is at least one option
266string overall.
267
268The option strings passed to :meth:`add_option` are effectively labels for the
269option defined by that call. For brevity, we will frequently refer to
270*encountering an option* on the command line; in reality, :mod:`optparse`
271encounters *option strings* and looks up options from them.
272
273Once all of your options are defined, instruct :mod:`optparse` to parse your
274program's command line::
275
276 (options, args) = parser.parse_args()
277
278(If you like, you can pass a custom argument list to :meth:`parse_args`, but
279that's rarely necessary: by default it uses ``sys.argv[1:]``.)
280
281:meth:`parse_args` returns two values:
282
283* ``options``, an object containing values for all of your options---e.g. if
284 ``"--file"`` takes a single string argument, then ``options.file`` will be the
285 filename supplied by the user, or ``None`` if the user did not supply that
286 option
287
288* ``args``, the list of positional arguments leftover after parsing options
289
290This tutorial section only covers the four most important option attributes:
Georg Brandl15a515f2009-09-17 22:11:49 +0000291:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
292(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
293most fundamental.
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295
296.. _optparse-understanding-option-actions:
297
298Understanding option actions
299^^^^^^^^^^^^^^^^^^^^^^^^^^^^
300
301Actions tell :mod:`optparse` what to do when it encounters an option on the
302command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
303adding new actions is an advanced topic covered in section
Georg Brandl15a515f2009-09-17 22:11:49 +0000304:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
305a value in some variable---for example, take a string from the command line and
306store it in an attribute of ``options``.
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308If you don't specify an option action, :mod:`optparse` defaults to ``store``.
309
310
311.. _optparse-store-action:
312
313The store action
314^^^^^^^^^^^^^^^^
315
316The most common option action is ``store``, which tells :mod:`optparse` to take
317the next argument (or the remainder of the current argument), ensure that it is
318of the correct type, and store it to your chosen destination.
319
320For example::
321
322 parser.add_option("-f", "--file",
323 action="store", type="string", dest="filename")
324
325Now let's make up a fake command line and ask :mod:`optparse` to parse it::
326
327 args = ["-f", "foo.txt"]
328 (options, args) = parser.parse_args(args)
329
330When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
331argument, ``"foo.txt"``, and stores it in ``options.filename``. So, after this
332call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
333
334Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
335Here's an option that expects an integer argument::
336
337 parser.add_option("-n", type="int", dest="num")
338
339Note that this option has no long option string, which is perfectly acceptable.
340Also, there's no explicit action, since the default is ``store``.
341
342Let's parse another fake command-line. This time, we'll jam the option argument
343right up against the option: since ``"-n42"`` (one argument) is equivalent to
Georg Brandl15a515f2009-09-17 22:11:49 +0000344``"-n 42"`` (two arguments), the code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000345
346 (options, args) = parser.parse_args(["-n42"])
Georg Brandl6911e3c2007-09-04 07:15:32 +0000347 print(options.num)
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349will print ``"42"``.
350
351If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
352the fact that the default action is ``store``, that means our first example can
353be a lot shorter::
354
355 parser.add_option("-f", "--file", dest="filename")
356
357If you don't supply a destination, :mod:`optparse` figures out a sensible
358default from the option strings: if the first long option string is
359``"--foo-bar"``, then the default destination is ``foo_bar``. If there are no
360long option strings, :mod:`optparse` looks at the first short option string: the
361default destination for ``"-f"`` is ``f``.
362
Georg Brandl5c106642007-11-29 17:41:05 +0000363:mod:`optparse` also includes the built-in ``complex`` type. Adding
Georg Brandl116aa622007-08-15 14:28:22 +0000364types is covered in section :ref:`optparse-extending-optparse`.
365
366
367.. _optparse-handling-boolean-options:
368
369Handling boolean (flag) options
370^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
371
372Flag options---set a variable to true or false when a particular option is seen
373---are quite common. :mod:`optparse` supports them with two separate actions,
374``store_true`` and ``store_false``. For example, you might have a ``verbose``
375flag that is turned on with ``"-v"`` and off with ``"-q"``::
376
377 parser.add_option("-v", action="store_true", dest="verbose")
378 parser.add_option("-q", action="store_false", dest="verbose")
379
380Here we have two different options with the same destination, which is perfectly
381OK. (It just means you have to be a bit careful when setting default values---
382see below.)
383
384When :mod:`optparse` encounters ``"-v"`` on the command line, it sets
385``options.verbose`` to ``True``; when it encounters ``"-q"``,
386``options.verbose`` is set to ``False``.
387
388
389.. _optparse-other-actions:
390
391Other actions
392^^^^^^^^^^^^^
393
394Some other actions supported by :mod:`optparse` are:
395
Georg Brandl15a515f2009-09-17 22:11:49 +0000396``"store_const"``
Georg Brandl116aa622007-08-15 14:28:22 +0000397 store a constant value
398
Georg Brandl15a515f2009-09-17 22:11:49 +0000399``"append"``
Georg Brandl116aa622007-08-15 14:28:22 +0000400 append this option's argument to a list
401
Georg Brandl15a515f2009-09-17 22:11:49 +0000402``"count"``
Georg Brandl116aa622007-08-15 14:28:22 +0000403 increment a counter by one
404
Georg Brandl15a515f2009-09-17 22:11:49 +0000405``"callback"``
Georg Brandl116aa622007-08-15 14:28:22 +0000406 call a specified function
407
408These are covered in section :ref:`optparse-reference-guide`, Reference Guide
409and section :ref:`optparse-option-callbacks`.
410
411
412.. _optparse-default-values:
413
414Default values
415^^^^^^^^^^^^^^
416
417All of the above examples involve setting some variable (the "destination") when
418certain command-line options are seen. What happens if those options are never
419seen? Since we didn't supply any defaults, they are all set to ``None``. This
420is usually fine, but sometimes you want more control. :mod:`optparse` lets you
421supply a default value for each destination, which is assigned before the
422command line is parsed.
423
424First, consider the verbose/quiet example. If we want :mod:`optparse` to set
425``verbose`` to ``True`` unless ``"-q"`` is seen, then we can do this::
426
427 parser.add_option("-v", action="store_true", dest="verbose", default=True)
428 parser.add_option("-q", action="store_false", dest="verbose")
429
430Since default values apply to the *destination* rather than to any particular
431option, and these two options happen to have the same destination, this is
432exactly equivalent::
433
434 parser.add_option("-v", action="store_true", dest="verbose")
435 parser.add_option("-q", action="store_false", dest="verbose", default=True)
436
437Consider this::
438
439 parser.add_option("-v", action="store_true", dest="verbose", default=False)
440 parser.add_option("-q", action="store_false", dest="verbose", default=True)
441
442Again, the default value for ``verbose`` will be ``True``: the last default
443value supplied for any particular destination is the one that counts.
444
445A clearer way to specify default values is the :meth:`set_defaults` method of
446OptionParser, which you can call at any time before calling :meth:`parse_args`::
447
448 parser.set_defaults(verbose=True)
449 parser.add_option(...)
450 (options, args) = parser.parse_args()
451
452As before, the last value specified for a given option destination is the one
453that counts. For clarity, try to use one method or the other of setting default
454values, not both.
455
456
457.. _optparse-generating-help:
458
459Generating help
460^^^^^^^^^^^^^^^
461
462:mod:`optparse`'s ability to generate help and usage text automatically is
463useful for creating user-friendly command-line interfaces. All you have to do
Georg Brandl15a515f2009-09-17 22:11:49 +0000464is supply a :attr:`~Option.help` value for each option, and optionally a short
465usage message for your whole program. Here's an OptionParser populated with
Georg Brandl116aa622007-08-15 14:28:22 +0000466user-friendly (documented) options::
467
468 usage = "usage: %prog [options] arg1 arg2"
469 parser = OptionParser(usage=usage)
470 parser.add_option("-v", "--verbose",
471 action="store_true", dest="verbose", default=True,
472 help="make lots of noise [default]")
473 parser.add_option("-q", "--quiet",
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000474 action="store_false", dest="verbose",
Georg Brandl116aa622007-08-15 14:28:22 +0000475 help="be vewwy quiet (I'm hunting wabbits)")
476 parser.add_option("-f", "--filename",
Georg Brandlee8783d2009-09-16 16:00:31 +0000477 metavar="FILE", help="write output to FILE")
Georg Brandl116aa622007-08-15 14:28:22 +0000478 parser.add_option("-m", "--mode",
479 default="intermediate",
480 help="interaction mode: novice, intermediate, "
481 "or expert [default: %default]")
482
483If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
484command-line, or if you just call :meth:`parser.print_help`, it prints the
Ezio Melotti383ae952010-01-03 09:06:02 +0000485following to standard output:
486
487.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +0000488
489 usage: <yourscript> [options] arg1 arg2
490
491 options:
492 -h, --help show this help message and exit
493 -v, --verbose make lots of noise [default]
494 -q, --quiet be vewwy quiet (I'm hunting wabbits)
495 -f FILE, --filename=FILE
496 write output to FILE
497 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
498 expert [default: intermediate]
499
500(If the help output is triggered by a help option, :mod:`optparse` exits after
501printing the help text.)
502
503There's a lot going on here to help :mod:`optparse` generate the best possible
504help message:
505
506* the script defines its own usage message::
507
508 usage = "usage: %prog [options] arg1 arg2"
509
510 :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
Georg Brandl15a515f2009-09-17 22:11:49 +0000511 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
512 is then printed before the detailed option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandl15a515f2009-09-17 22:11:49 +0000515 default: ``"usage: %prog [options]"``, which is fine if your script doesn't
516 take any positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000517
518* every option defines a help string, and doesn't worry about line-wrapping---
519 :mod:`optparse` takes care of wrapping lines and making the help output look
520 good.
521
522* options that take a value indicate this fact in their automatically-generated
523 help message, e.g. for the "mode" option::
524
525 -m MODE, --mode=MODE
526
527 Here, "MODE" is called the meta-variable: it stands for the argument that the
528 user is expected to supply to :option:`-m`/:option:`--mode`. By default,
529 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandl15a515f2009-09-17 22:11:49 +0000530 that for the meta-variable. Sometimes, that's not what you want---for
531 example, the :option:`--filename` option explicitly sets ``metavar="FILE"``,
532 resulting in this automatically-generated option description::
Georg Brandl116aa622007-08-15 14:28:22 +0000533
534 -f FILE, --filename=FILE
535
Georg Brandl15a515f2009-09-17 22:11:49 +0000536 This is important for more than just saving space, though: the manually
537 written help text uses the meta-variable "FILE" to clue the user in that
538 there's a connection between the semi-formal syntax "-f FILE" and the informal
539 semantic description "write output to FILE". This is a simple but effective
540 way to make your help text a lot clearer and more useful for end users.
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542* options that have a default value can include ``%default`` in the help
543 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
544 default value. If an option has no default value (or the default value is
545 ``None``), ``%default`` expands to ``none``.
546
Georg Brandl15a515f2009-09-17 22:11:49 +0000547When dealing with many options, it is convenient to group these options for
548better help output. An :class:`OptionParser` can contain several option groups,
549each of which can contain several options.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000550
Georg Brandl15a515f2009-09-17 22:11:49 +0000551Continuing with the parser defined above, adding an :class:`OptionGroup` to a
552parser is easy::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000553
554 group = OptionGroup(parser, "Dangerous Options",
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000555 "Caution: use these options at your own risk. "
556 "It is believed that some of them bite.")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000557 group.add_option("-g", action="store_true", help="Group option.")
558 parser.add_option_group(group)
559
Ezio Melotti383ae952010-01-03 09:06:02 +0000560This would result in the following help output:
561
562.. code-block:: text
Christian Heimesfdab48e2008-01-20 09:06:41 +0000563
564 usage: [options] arg1 arg2
565
566 options:
567 -h, --help show this help message and exit
568 -v, --verbose make lots of noise [default]
569 -q, --quiet be vewwy quiet (I'm hunting wabbits)
570 -fFILE, --file=FILE write output to FILE
571 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000572 [default], 'expert'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000573
574 Dangerous Options:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000575 Caution: use of these options is at your own risk. It is believed that
576 some of them bite.
577 -g Group option.
Georg Brandl116aa622007-08-15 14:28:22 +0000578
579.. _optparse-printing-version-string:
580
581Printing a version string
582^^^^^^^^^^^^^^^^^^^^^^^^^
583
584Similar to the brief usage string, :mod:`optparse` can also print a version
585string for your program. You have to supply the string as the ``version``
586argument to OptionParser::
587
588 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
589
590``"%prog"`` is expanded just like it is in ``usage``. Apart from that,
591``version`` can contain anything you like. When you supply it, :mod:`optparse`
592automatically adds a ``"--version"`` option to your parser. If it encounters
593this option on the command line, it expands your ``version`` string (by
594replacing ``"%prog"``), prints it to stdout, and exits.
595
596For example, if your script is called ``/usr/bin/foo``::
597
598 $ /usr/bin/foo --version
599 foo 1.0
600
Ezio Melotti1ce43192010-01-04 21:53:17 +0000601The following two methods can be used to print and get the ``version`` string:
602
603.. method:: OptionParser.print_version(file=None)
604
605 Print the version message for the current program (``self.version``) to
606 *file* (default stdout). As with :meth:`print_usage`, any occurrence
607 of ``"%prog"`` in ``self.version`` is replaced with the name of the current
608 program. Does nothing if ``self.version`` is empty or undefined.
609
610.. method:: OptionParser.get_version()
611
612 Same as :meth:`print_version` but returns the version string instead of
613 printing it.
614
Georg Brandl116aa622007-08-15 14:28:22 +0000615
616.. _optparse-how-optparse-handles-errors:
617
618How :mod:`optparse` handles errors
619^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
620
621There are two broad classes of errors that :mod:`optparse` has to worry about:
622programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandl15a515f2009-09-17 22:11:49 +0000623calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
624option attributes, missing option attributes, etc. These are dealt with in the
625usual way: raise an exception (either :exc:`optparse.OptionError` or
626:exc:`TypeError`) and let the program crash.
Georg Brandl116aa622007-08-15 14:28:22 +0000627
628Handling user errors is much more important, since they are guaranteed to happen
629no matter how stable your code is. :mod:`optparse` can automatically detect
630some user errors, such as bad option arguments (passing ``"-n 4x"`` where
631:option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
632of the command line, where :option:`-n` takes an argument of any type). Also,
Georg Brandl15a515f2009-09-17 22:11:49 +0000633you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl116aa622007-08-15 14:28:22 +0000634condition::
635
636 (options, args) = parser.parse_args()
637 [...]
638 if options.a and options.b:
639 parser.error("options -a and -b are mutually exclusive")
640
641In either case, :mod:`optparse` handles the error the same way: it prints the
642program's usage message and an error message to standard error and exits with
643error status 2.
644
645Consider the first example above, where the user passes ``"4x"`` to an option
646that takes an integer::
647
648 $ /usr/bin/foo -n 4x
649 usage: foo [options]
650
651 foo: error: option -n: invalid integer value: '4x'
652
653Or, where the user fails to pass a value at all::
654
655 $ /usr/bin/foo -n
656 usage: foo [options]
657
658 foo: error: -n option requires an argument
659
660:mod:`optparse`\ -generated error messages take care always to mention the
661option involved in the error; be sure to do the same when calling
Georg Brandl15a515f2009-09-17 22:11:49 +0000662:func:`OptionParser.error` from your application code.
Georg Brandl116aa622007-08-15 14:28:22 +0000663
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000664If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000665you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
666and/or :meth:`~OptionParser.error` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000667
668
669.. _optparse-putting-it-all-together:
670
671Putting it all together
672^^^^^^^^^^^^^^^^^^^^^^^
673
674Here's what :mod:`optparse`\ -based scripts usually look like::
675
676 from optparse import OptionParser
677 [...]
678 def main():
679 usage = "usage: %prog [options] arg"
680 parser = OptionParser(usage)
681 parser.add_option("-f", "--file", dest="filename",
682 help="read data from FILENAME")
683 parser.add_option("-v", "--verbose",
684 action="store_true", dest="verbose")
685 parser.add_option("-q", "--quiet",
686 action="store_false", dest="verbose")
687 [...]
688 (options, args) = parser.parse_args()
689 if len(args) != 1:
690 parser.error("incorrect number of arguments")
691 if options.verbose:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000692 print("reading %s..." % options.filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000693 [...]
694
695 if __name__ == "__main__":
696 main()
697
Georg Brandl116aa622007-08-15 14:28:22 +0000698
699.. _optparse-reference-guide:
700
701Reference Guide
702---------------
703
704
705.. _optparse-creating-parser:
706
707Creating the parser
708^^^^^^^^^^^^^^^^^^^
709
Georg Brandl15a515f2009-09-17 22:11:49 +0000710The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Georg Brandl15a515f2009-09-17 22:11:49 +0000712.. class:: OptionParser(...)
Georg Brandl116aa622007-08-15 14:28:22 +0000713
Georg Brandl15a515f2009-09-17 22:11:49 +0000714 The OptionParser constructor has no required arguments, but a number of
715 optional keyword arguments. You should always pass them as keyword
716 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl116aa622007-08-15 14:28:22 +0000717
718 ``usage`` (default: ``"%prog [options]"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000719 The usage summary to print when your program is run incorrectly or with a
720 help option. When :mod:`optparse` prints the usage string, it expands
721 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
722 passed that keyword argument). To suppress a usage message, pass the
723 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl116aa622007-08-15 14:28:22 +0000724
725 ``option_list`` (default: ``[]``)
726 A list of Option objects to populate the parser with. The options in
Georg Brandl15a515f2009-09-17 22:11:49 +0000727 ``option_list`` are added after any options in ``standard_option_list`` (a
728 class attribute that may be set by OptionParser subclasses), but before
729 any version or help options. Deprecated; use :meth:`add_option` after
730 creating the parser instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000731
732 ``option_class`` (default: optparse.Option)
733 Class to use when adding options to the parser in :meth:`add_option`.
734
735 ``version`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000736 A version string to print when the user supplies a version option. If you
737 supply a true value for ``version``, :mod:`optparse` automatically adds a
738 version option with the single option string ``"--version"``. The
739 substring ``"%prog"`` is expanded the same as for ``usage``.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741 ``conflict_handler`` (default: ``"error"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000742 Specifies what to do when options with conflicting option strings are
743 added to the parser; see section
744 :ref:`optparse-conflicts-between-options`.
Georg Brandl116aa622007-08-15 14:28:22 +0000745
746 ``description`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000747 A paragraph of text giving a brief overview of your program.
748 :mod:`optparse` reformats this paragraph to fit the current terminal width
749 and prints it when the user requests help (after ``usage``, but before the
750 list of options).
Georg Brandl116aa622007-08-15 14:28:22 +0000751
Georg Brandl15a515f2009-09-17 22:11:49 +0000752 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
753 An instance of optparse.HelpFormatter that will be used for printing help
754 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl116aa622007-08-15 14:28:22 +0000755 IndentedHelpFormatter and TitledHelpFormatter.
756
757 ``add_help_option`` (default: ``True``)
758 If true, :mod:`optparse` will add a help option (with option strings ``"-h"``
759 and ``"--help"``) to the parser.
760
761 ``prog``
762 The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
763 instead of ``os.path.basename(sys.argv[0])``.
764
Senthil Kumaran5b58f5e2010-03-23 11:00:53 +0000765 ``epilog`` (default: ``None``)
766 A paragraph of help text to print after the option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000767
768.. _optparse-populating-parser:
769
770Populating the parser
771^^^^^^^^^^^^^^^^^^^^^
772
773There are several ways to populate the parser with options. The preferred way
Georg Brandl15a515f2009-09-17 22:11:49 +0000774is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl116aa622007-08-15 14:28:22 +0000775:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
776
777* pass it an Option instance (as returned by :func:`make_option`)
778
779* pass it any combination of positional and keyword arguments that are
Georg Brandl15a515f2009-09-17 22:11:49 +0000780 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
781 will create the Option instance for you
Georg Brandl116aa622007-08-15 14:28:22 +0000782
783The other alternative is to pass a list of pre-constructed Option instances to
784the OptionParser constructor, as in::
785
786 option_list = [
787 make_option("-f", "--filename",
788 action="store", type="string", dest="filename"),
789 make_option("-q", "--quiet",
790 action="store_false", dest="verbose"),
791 ]
792 parser = OptionParser(option_list=option_list)
793
794(:func:`make_option` is a factory function for creating Option instances;
795currently it is an alias for the Option constructor. A future version of
796:mod:`optparse` may split Option into several classes, and :func:`make_option`
797will pick the right class to instantiate. Do not instantiate Option directly.)
798
799
800.. _optparse-defining-options:
801
802Defining options
803^^^^^^^^^^^^^^^^
804
805Each Option instance represents a set of synonymous command-line option strings,
806e.g. :option:`-f` and :option:`--file`. You can specify any number of short or
807long option strings, but you must specify at least one overall option string.
808
Georg Brandl15a515f2009-09-17 22:11:49 +0000809The canonical way to create an :class:`Option` instance is with the
810:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl116aa622007-08-15 14:28:22 +0000811
Georg Brandl15a515f2009-09-17 22:11:49 +0000812.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000813
Georg Brandl15a515f2009-09-17 22:11:49 +0000814 To define an option with only a short option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000815
Georg Brandl15a515f2009-09-17 22:11:49 +0000816 parser.add_option("-f", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000817
Georg Brandl15a515f2009-09-17 22:11:49 +0000818 And to define an option with only a long option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000819
Georg Brandl15a515f2009-09-17 22:11:49 +0000820 parser.add_option("--foo", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000821
Georg Brandl15a515f2009-09-17 22:11:49 +0000822 The keyword arguments define attributes of the new Option object. The most
823 important option attribute is :attr:`~Option.action`, and it largely
824 determines which other attributes are relevant or required. If you pass
825 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
826 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl116aa622007-08-15 14:28:22 +0000827
Georg Brandl15a515f2009-09-17 22:11:49 +0000828 An option's *action* determines what :mod:`optparse` does when it encounters
829 this option on the command-line. The standard option actions hard-coded into
830 :mod:`optparse` are:
Georg Brandl116aa622007-08-15 14:28:22 +0000831
Georg Brandl15a515f2009-09-17 22:11:49 +0000832 ``"store"``
833 store this option's argument (default)
Georg Brandl116aa622007-08-15 14:28:22 +0000834
Georg Brandl15a515f2009-09-17 22:11:49 +0000835 ``"store_const"``
836 store a constant value
Georg Brandl116aa622007-08-15 14:28:22 +0000837
Georg Brandl15a515f2009-09-17 22:11:49 +0000838 ``"store_true"``
839 store a true value
Georg Brandl116aa622007-08-15 14:28:22 +0000840
Georg Brandl15a515f2009-09-17 22:11:49 +0000841 ``"store_false"``
842 store a false value
Georg Brandl116aa622007-08-15 14:28:22 +0000843
Georg Brandl15a515f2009-09-17 22:11:49 +0000844 ``"append"``
845 append this option's argument to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000846
Georg Brandl15a515f2009-09-17 22:11:49 +0000847 ``"append_const"``
848 append a constant value to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000849
Georg Brandl15a515f2009-09-17 22:11:49 +0000850 ``"count"``
851 increment a counter by one
Georg Brandl116aa622007-08-15 14:28:22 +0000852
Georg Brandl15a515f2009-09-17 22:11:49 +0000853 ``"callback"``
854 call a specified function
Georg Brandl116aa622007-08-15 14:28:22 +0000855
Georg Brandl15a515f2009-09-17 22:11:49 +0000856 ``"help"``
857 print a usage message including all options and the documentation for them
Georg Brandl116aa622007-08-15 14:28:22 +0000858
Georg Brandl15a515f2009-09-17 22:11:49 +0000859 (If you don't supply an action, the default is ``"store"``. For this action,
860 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
861 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000862
863As you can see, most actions involve storing or updating a value somewhere.
864:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandl15a515f2009-09-17 22:11:49 +0000865``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl116aa622007-08-15 14:28:22 +0000866arguments (and various other values) are stored as attributes of this object,
Georg Brandl15a515f2009-09-17 22:11:49 +0000867according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000868
Georg Brandl15a515f2009-09-17 22:11:49 +0000869For example, when you call ::
Georg Brandl116aa622007-08-15 14:28:22 +0000870
871 parser.parse_args()
872
873one of the first things :mod:`optparse` does is create the ``options`` object::
874
875 options = Values()
876
Georg Brandl15a515f2009-09-17 22:11:49 +0000877If one of the options in this parser is defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +0000878
879 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
880
881and the command-line being parsed includes any of the following::
882
883 -ffoo
884 -f foo
885 --file=foo
886 --file foo
887
Georg Brandl15a515f2009-09-17 22:11:49 +0000888then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl116aa622007-08-15 14:28:22 +0000889
890 options.filename = "foo"
891
Georg Brandl15a515f2009-09-17 22:11:49 +0000892The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
893as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
894one that makes sense for *all* options.
895
896
897.. _optparse-option-attributes:
898
899Option attributes
900^^^^^^^^^^^^^^^^^
901
902The following option attributes may be passed as keyword arguments to
903:meth:`OptionParser.add_option`. If you pass an option attribute that is not
904relevant to a particular option, or fail to pass a required option attribute,
905:mod:`optparse` raises :exc:`OptionError`.
906
907.. attribute:: Option.action
908
909 (default: ``"store"``)
910
911 Determines :mod:`optparse`'s behaviour when this option is seen on the
912 command line; the available options are documented :ref:`here
913 <optparse-standard-option-actions>`.
914
915.. attribute:: Option.type
916
917 (default: ``"string"``)
918
919 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
920 the available option types are documented :ref:`here
921 <optparse-standard-option-types>`.
922
923.. attribute:: Option.dest
924
925 (default: derived from option strings)
926
927 If the option's action implies writing or modifying a value somewhere, this
928 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
929 attribute of the ``options`` object that :mod:`optparse` builds as it parses
930 the command line.
931
932.. attribute:: Option.default
933
934 The value to use for this option's destination if the option is not seen on
935 the command line. See also :meth:`OptionParser.set_defaults`.
936
937.. attribute:: Option.nargs
938
939 (default: 1)
940
941 How many arguments of type :attr:`~Option.type` should be consumed when this
942 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
943 :attr:`~Option.dest`.
944
945.. attribute:: Option.const
946
947 For actions that store a constant value, the constant value to store.
948
949.. attribute:: Option.choices
950
951 For options of type ``"choice"``, the list of strings the user may choose
952 from.
953
954.. attribute:: Option.callback
955
956 For options with action ``"callback"``, the callable to call when this option
957 is seen. See section :ref:`optparse-option-callbacks` for detail on the
958 arguments passed to the callable.
959
960.. attribute:: Option.callback_args
961 Option.callback_kwargs
962
963 Additional positional and keyword arguments to pass to ``callback`` after the
964 four standard callback arguments.
965
966.. attribute:: Option.help
967
968 Help text to print for this option when listing all available options after
969 the user supplies a :attr:`~Option.help` option (such as ``"--help"``). If
970 no help text is supplied, the option will be listed without help text. To
971 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
972
973.. attribute:: Option.metavar
974
975 (default: derived from option strings)
976
977 Stand-in for the option argument(s) to use when printing help text. See
978 section :ref:`optparse-tutorial` for an example.
Georg Brandl116aa622007-08-15 14:28:22 +0000979
980
981.. _optparse-standard-option-actions:
982
983Standard option actions
984^^^^^^^^^^^^^^^^^^^^^^^
985
986The various option actions all have slightly different requirements and effects.
987Most actions have several relevant option attributes which you may specify to
988guide :mod:`optparse`'s behaviour; a few have required attributes, which you
989must specify for any option using that action.
990
Georg Brandl15a515f2009-09-17 22:11:49 +0000991* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
992 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +0000993
994 The option must be followed by an argument, which is converted to a value
Georg Brandl15a515f2009-09-17 22:11:49 +0000995 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
996 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
997 command line; all will be converted according to :attr:`~Option.type` and
998 stored to :attr:`~Option.dest` as a tuple. See the
999 :ref:`optparse-standard-option-types` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001000
Georg Brandl15a515f2009-09-17 22:11:49 +00001001 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
1002 defaults to ``"choice"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001003
Georg Brandl15a515f2009-09-17 22:11:49 +00001004 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001005
Georg Brandl15a515f2009-09-17 22:11:49 +00001006 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
1007 from the first long option string (e.g., ``"--foo-bar"`` implies
1008 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
1009 destination from the first short option string (e.g., ``"-f"`` implies ``f``).
Georg Brandl116aa622007-08-15 14:28:22 +00001010
1011 Example::
1012
1013 parser.add_option("-f")
1014 parser.add_option("-p", type="float", nargs=3, dest="point")
1015
Georg Brandl15a515f2009-09-17 22:11:49 +00001016 As it parses the command line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001017
1018 -f foo.txt -p 1 -3.5 4 -fbar.txt
1019
Georg Brandl15a515f2009-09-17 22:11:49 +00001020 :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +00001021
1022 options.f = "foo.txt"
1023 options.point = (1.0, -3.5, 4.0)
1024 options.f = "bar.txt"
1025
Georg Brandl15a515f2009-09-17 22:11:49 +00001026* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1027 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001028
Georg Brandl15a515f2009-09-17 22:11:49 +00001029 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001030
1031 Example::
1032
1033 parser.add_option("-q", "--quiet",
1034 action="store_const", const=0, dest="verbose")
1035 parser.add_option("-v", "--verbose",
1036 action="store_const", const=1, dest="verbose")
1037 parser.add_option("--noisy",
1038 action="store_const", const=2, dest="verbose")
1039
1040 If ``"--noisy"`` is seen, :mod:`optparse` will set ::
1041
1042 options.verbose = 2
1043
Georg Brandl15a515f2009-09-17 22:11:49 +00001044* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001045
Georg Brandl15a515f2009-09-17 22:11:49 +00001046 A special case of ``"store_const"`` that stores a true value to
1047 :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001048
Georg Brandl15a515f2009-09-17 22:11:49 +00001049* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001050
Georg Brandl15a515f2009-09-17 22:11:49 +00001051 Like ``"store_true"``, but stores a false value.
Georg Brandl116aa622007-08-15 14:28:22 +00001052
1053 Example::
1054
1055 parser.add_option("--clobber", action="store_true", dest="clobber")
1056 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1057
Georg Brandl15a515f2009-09-17 22:11:49 +00001058* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1059 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001060
1061 The option must be followed by an argument, which is appended to the list in
Georg Brandl15a515f2009-09-17 22:11:49 +00001062 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1063 supplied, an empty list is automatically created when :mod:`optparse` first
1064 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1065 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1066 is appended to :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001067
Georg Brandl15a515f2009-09-17 22:11:49 +00001068 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1069 for the ``"store"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001070
1071 Example::
1072
1073 parser.add_option("-t", "--tracks", action="append", type="int")
1074
1075 If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
1076 of::
1077
1078 options.tracks = []
1079 options.tracks.append(int("3"))
1080
1081 If, a little later on, ``"--tracks=4"`` is seen, it does::
1082
1083 options.tracks.append(int("4"))
1084
Georg Brandl15a515f2009-09-17 22:11:49 +00001085* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1086 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001087
Georg Brandl15a515f2009-09-17 22:11:49 +00001088 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1089 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1090 ``None``, and an empty list is automatically created the first time the option
1091 is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +00001092
Georg Brandl15a515f2009-09-17 22:11:49 +00001093* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001094
Georg Brandl15a515f2009-09-17 22:11:49 +00001095 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1096 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1097 first time.
Georg Brandl116aa622007-08-15 14:28:22 +00001098
1099 Example::
1100
1101 parser.add_option("-v", action="count", dest="verbosity")
1102
1103 The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
1104 equivalent of::
1105
1106 options.verbosity = 0
1107 options.verbosity += 1
1108
1109 Every subsequent occurrence of ``"-v"`` results in ::
1110
1111 options.verbosity += 1
1112
Georg Brandl15a515f2009-09-17 22:11:49 +00001113* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1114 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1115 :attr:`~Option.callback_kwargs`]
Georg Brandl116aa622007-08-15 14:28:22 +00001116
Georg Brandl15a515f2009-09-17 22:11:49 +00001117 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001118
1119 func(option, opt_str, value, parser, *args, **kwargs)
1120
1121 See section :ref:`optparse-option-callbacks` for more detail.
1122
Georg Brandl15a515f2009-09-17 22:11:49 +00001123* ``"help"``
Georg Brandl116aa622007-08-15 14:28:22 +00001124
Georg Brandl15a515f2009-09-17 22:11:49 +00001125 Prints a complete help message for all the options in the current option
1126 parser. The help message is constructed from the ``usage`` string passed to
1127 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1128 option.
Georg Brandl116aa622007-08-15 14:28:22 +00001129
Georg Brandl15a515f2009-09-17 22:11:49 +00001130 If no :attr:`~Option.help` string is supplied for an option, it will still be
1131 listed in the help message. To omit an option entirely, use the special value
1132 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl116aa622007-08-15 14:28:22 +00001133
Georg Brandl15a515f2009-09-17 22:11:49 +00001134 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1135 OptionParsers, so you do not normally need to create one.
Georg Brandl116aa622007-08-15 14:28:22 +00001136
1137 Example::
1138
1139 from optparse import OptionParser, SUPPRESS_HELP
1140
Georg Brandlee8783d2009-09-16 16:00:31 +00001141 # usually, a help option is added automatically, but that can
1142 # be suppressed using the add_help_option argument
1143 parser = OptionParser(add_help_option=False)
1144
1145 parser.add_option("-h", "--help", action="help")
Georg Brandl116aa622007-08-15 14:28:22 +00001146 parser.add_option("-v", action="store_true", dest="verbose",
1147 help="Be moderately verbose")
1148 parser.add_option("--file", dest="filename",
Georg Brandlee8783d2009-09-16 16:00:31 +00001149 help="Input file to read data from")
Georg Brandl116aa622007-08-15 14:28:22 +00001150 parser.add_option("--secret", help=SUPPRESS_HELP)
1151
Georg Brandl15a515f2009-09-17 22:11:49 +00001152 If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line,
1153 it will print something like the following help message to stdout (assuming
Ezio Melotti383ae952010-01-03 09:06:02 +00001154 ``sys.argv[0]`` is ``"foo.py"``):
1155
1156 .. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +00001157
1158 usage: foo.py [options]
1159
1160 options:
1161 -h, --help Show this help message and exit
1162 -v Be moderately verbose
1163 --file=FILENAME Input file to read data from
1164
1165 After printing the help message, :mod:`optparse` terminates your process with
1166 ``sys.exit(0)``.
1167
Georg Brandl15a515f2009-09-17 22:11:49 +00001168* ``"version"``
Georg Brandl116aa622007-08-15 14:28:22 +00001169
Georg Brandl15a515f2009-09-17 22:11:49 +00001170 Prints the version number supplied to the OptionParser to stdout and exits.
1171 The version number is actually formatted and printed by the
1172 ``print_version()`` method of OptionParser. Generally only relevant if the
1173 ``version`` argument is supplied to the OptionParser constructor. As with
1174 :attr:`~Option.help` options, you will rarely create ``version`` options,
1175 since :mod:`optparse` automatically adds them when needed.
Georg Brandl116aa622007-08-15 14:28:22 +00001176
1177
1178.. _optparse-standard-option-types:
1179
1180Standard option types
1181^^^^^^^^^^^^^^^^^^^^^
1182
Georg Brandl15a515f2009-09-17 22:11:49 +00001183:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1184``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1185option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +00001186
1187Arguments to string options are not checked or converted in any way: the text on
1188the command line is stored in the destination (or passed to the callback) as-is.
1189
Georg Brandl15a515f2009-09-17 22:11:49 +00001190Integer arguments (type ``"int"``) are parsed as follows:
Georg Brandl116aa622007-08-15 14:28:22 +00001191
1192* if the number starts with ``0x``, it is parsed as a hexadecimal number
1193
1194* if the number starts with ``0``, it is parsed as an octal number
1195
Georg Brandl9afde1c2007-11-01 20:32:30 +00001196* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl116aa622007-08-15 14:28:22 +00001197
1198* otherwise, the number is parsed as a decimal number
1199
1200
Georg Brandl15a515f2009-09-17 22:11:49 +00001201The conversion is done by calling :func:`int` with the appropriate base (2, 8,
120210, or 16). If this fails, so will :mod:`optparse`, although with a more useful
Georg Brandl5c106642007-11-29 17:41:05 +00001203error message.
Georg Brandl116aa622007-08-15 14:28:22 +00001204
Georg Brandl15a515f2009-09-17 22:11:49 +00001205``"float"`` and ``"complex"`` option arguments are converted directly with
1206:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl116aa622007-08-15 14:28:22 +00001207
Georg Brandl15a515f2009-09-17 22:11:49 +00001208``"choice"`` options are a subtype of ``"string"`` options. The
1209:attr:`~Option.choices`` option attribute (a sequence of strings) defines the
1210set of allowed option arguments. :func:`optparse.check_choice` compares
1211user-supplied option arguments against this master list and raises
1212:exc:`OptionValueError` if an invalid string is given.
Georg Brandl116aa622007-08-15 14:28:22 +00001213
1214
1215.. _optparse-parsing-arguments:
1216
1217Parsing arguments
1218^^^^^^^^^^^^^^^^^
1219
1220The whole point of creating and populating an OptionParser is to call its
1221:meth:`parse_args` method::
1222
1223 (options, args) = parser.parse_args(args=None, values=None)
1224
1225where the input parameters are
1226
1227``args``
1228 the list of arguments to process (default: ``sys.argv[1:]``)
1229
1230``values``
Georg Brandla6053b42009-09-01 08:11:14 +00001231 object to store option arguments in (default: a new instance of
1232 :class:`optparse.Values`)
Georg Brandl116aa622007-08-15 14:28:22 +00001233
1234and the return values are
1235
1236``options``
Georg Brandla6053b42009-09-01 08:11:14 +00001237 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl116aa622007-08-15 14:28:22 +00001238 instance created by :mod:`optparse`
1239
1240``args``
1241 the leftover positional arguments after all options have been processed
1242
1243The most common usage is to supply neither keyword argument. If you supply
Georg Brandl15a515f2009-09-17 22:11:49 +00001244``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl116aa622007-08-15 14:28:22 +00001245for every option argument stored to an option destination) and returned by
1246:meth:`parse_args`.
1247
1248If :meth:`parse_args` encounters any errors in the argument list, it calls the
1249OptionParser's :meth:`error` method with an appropriate end-user error message.
1250This ultimately terminates your process with an exit status of 2 (the
1251traditional Unix exit status for command-line errors).
1252
1253
1254.. _optparse-querying-manipulating-option-parser:
1255
1256Querying and manipulating your option parser
1257^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1258
Georg Brandl15a515f2009-09-17 22:11:49 +00001259The default behavior of the option parser can be customized slightly, and you
1260can also poke around your option parser and see what's there. OptionParser
1261provides several methods to help you out:
Georg Brandl116aa622007-08-15 14:28:22 +00001262
Georg Brandl15a515f2009-09-17 22:11:49 +00001263.. method:: OptionParser.disable_interspersed_args()
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001264
Georg Brandl15a515f2009-09-17 22:11:49 +00001265 Set parsing to stop on the first non-option. For example, if ``"-a"`` and
1266 ``"-b"`` are both simple options that take no arguments, :mod:`optparse`
1267 normally accepts this syntax::
Georg Brandl116aa622007-08-15 14:28:22 +00001268
Georg Brandl15a515f2009-09-17 22:11:49 +00001269 prog -a arg1 -b arg2
1270
1271 and treats it as equivalent to ::
1272
1273 prog -a -b arg1 arg2
1274
1275 To disable this feature, call :meth:`disable_interspersed_args`. This
1276 restores traditional Unix syntax, where option parsing stops with the first
1277 non-option argument.
1278
1279 Use this if you have a command processor which runs another command which has
1280 options of its own and you want to make sure these options don't get
1281 confused. For example, each command might have a different set of options.
1282
1283.. method:: OptionParser.enable_interspersed_args()
1284
1285 Set parsing to not stop on the first non-option, allowing interspersing
1286 switches with command arguments. This is the default behavior.
1287
1288.. method:: OptionParser.get_option(opt_str)
1289
1290 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl116aa622007-08-15 14:28:22 +00001291 no options have that option string.
1292
Georg Brandl15a515f2009-09-17 22:11:49 +00001293.. method:: OptionParser.has_option(opt_str)
1294
1295 Return true if the OptionParser has an option with option string *opt_str*
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001296 (e.g., ``"-q"`` or ``"--verbose"``).
1297
Georg Brandl15a515f2009-09-17 22:11:49 +00001298.. method:: OptionParser.remove_option(opt_str)
1299
1300 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1301 option is removed. If that option provided any other option strings, all of
1302 those option strings become invalid. If *opt_str* does not occur in any
1303 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001304
1305
1306.. _optparse-conflicts-between-options:
1307
1308Conflicts between options
1309^^^^^^^^^^^^^^^^^^^^^^^^^
1310
1311If you're not careful, it's easy to define options with conflicting option
1312strings::
1313
1314 parser.add_option("-n", "--dry-run", ...)
1315 [...]
1316 parser.add_option("-n", "--noisy", ...)
1317
1318(This is particularly true if you've defined your own OptionParser subclass with
1319some standard options.)
1320
1321Every time you add an option, :mod:`optparse` checks for conflicts with existing
1322options. If it finds any, it invokes the current conflict-handling mechanism.
1323You can set the conflict-handling mechanism either in the constructor::
1324
1325 parser = OptionParser(..., conflict_handler=handler)
1326
1327or with a separate call::
1328
1329 parser.set_conflict_handler(handler)
1330
1331The available conflict handlers are:
1332
Georg Brandl15a515f2009-09-17 22:11:49 +00001333 ``"error"`` (default)
1334 assume option conflicts are a programming error and raise
1335 :exc:`OptionConflictError`
Georg Brandl116aa622007-08-15 14:28:22 +00001336
Georg Brandl15a515f2009-09-17 22:11:49 +00001337 ``"resolve"``
Georg Brandl116aa622007-08-15 14:28:22 +00001338 resolve option conflicts intelligently (see below)
1339
1340
Benjamin Petersone5384b02008-10-04 22:00:42 +00001341As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl116aa622007-08-15 14:28:22 +00001342intelligently and add conflicting options to it::
1343
1344 parser = OptionParser(conflict_handler="resolve")
1345 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1346 parser.add_option("-n", "--noisy", ..., help="be noisy")
1347
1348At this point, :mod:`optparse` detects that a previously-added option is already
1349using the ``"-n"`` option string. Since ``conflict_handler`` is ``"resolve"``,
1350it resolves the situation by removing ``"-n"`` from the earlier option's list of
1351option strings. Now ``"--dry-run"`` is the only way for the user to activate
1352that option. If the user asks for help, the help message will reflect that::
1353
1354 options:
1355 --dry-run do no harm
1356 [...]
1357 -n, --noisy be noisy
1358
1359It's possible to whittle away the option strings for a previously-added option
1360until there are none left, and the user has no way of invoking that option from
1361the command-line. In that case, :mod:`optparse` removes that option completely,
1362so it doesn't show up in help text or anywhere else. Carrying on with our
1363existing OptionParser::
1364
1365 parser.add_option("--dry-run", ..., help="new dry-run option")
1366
1367At this point, the original :option:`-n/--dry-run` option is no longer
1368accessible, so :mod:`optparse` removes it, leaving this help text::
1369
1370 options:
1371 [...]
1372 -n, --noisy be noisy
1373 --dry-run new dry-run option
1374
1375
1376.. _optparse-cleanup:
1377
1378Cleanup
1379^^^^^^^
1380
1381OptionParser instances have several cyclic references. This should not be a
1382problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandl15a515f2009-09-17 22:11:49 +00001383references explicitly by calling :meth:`~OptionParser.destroy` on your
1384OptionParser once you are done with it. This is particularly useful in
1385long-running applications where large object graphs are reachable from your
1386OptionParser.
Georg Brandl116aa622007-08-15 14:28:22 +00001387
1388
1389.. _optparse-other-methods:
1390
1391Other methods
1392^^^^^^^^^^^^^
1393
1394OptionParser supports several other public methods:
1395
Georg Brandl15a515f2009-09-17 22:11:49 +00001396.. method:: OptionParser.set_usage(usage)
Georg Brandl116aa622007-08-15 14:28:22 +00001397
Georg Brandl15a515f2009-09-17 22:11:49 +00001398 Set the usage string according to the rules described above for the ``usage``
1399 constructor keyword argument. Passing ``None`` sets the default usage
1400 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl116aa622007-08-15 14:28:22 +00001401
Ezio Melotti1ce43192010-01-04 21:53:17 +00001402.. method:: OptionParser.print_usage(file=None)
1403
1404 Print the usage message for the current program (``self.usage``) to *file*
1405 (default stdout). Any occurrence of the string ``"%prog"`` in ``self.usage``
1406 is replaced with the name of the current program. Does nothing if
1407 ``self.usage`` is empty or not defined.
1408
1409.. method:: OptionParser.get_usage()
1410
1411 Same as :meth:`print_usage` but returns the usage string instead of
1412 printing it.
1413
Georg Brandl15a515f2009-09-17 22:11:49 +00001414.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +00001415
Georg Brandl15a515f2009-09-17 22:11:49 +00001416 Set default values for several option destinations at once. Using
1417 :meth:`set_defaults` is the preferred way to set default values for options,
1418 since multiple options can share the same destination. For example, if
1419 several "mode" options all set the same destination, any one of them can set
1420 the default, and the last one wins::
Georg Brandl116aa622007-08-15 14:28:22 +00001421
Georg Brandl15a515f2009-09-17 22:11:49 +00001422 parser.add_option("--advanced", action="store_const",
1423 dest="mode", const="advanced",
1424 default="novice") # overridden below
1425 parser.add_option("--novice", action="store_const",
1426 dest="mode", const="novice",
1427 default="advanced") # overrides above setting
Georg Brandl116aa622007-08-15 14:28:22 +00001428
Georg Brandl15a515f2009-09-17 22:11:49 +00001429 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl116aa622007-08-15 14:28:22 +00001430
Georg Brandl15a515f2009-09-17 22:11:49 +00001431 parser.set_defaults(mode="advanced")
1432 parser.add_option("--advanced", action="store_const",
1433 dest="mode", const="advanced")
1434 parser.add_option("--novice", action="store_const",
1435 dest="mode", const="novice")
Georg Brandl116aa622007-08-15 14:28:22 +00001436
Georg Brandl116aa622007-08-15 14:28:22 +00001437
1438.. _optparse-option-callbacks:
1439
1440Option Callbacks
1441----------------
1442
1443When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1444needs, you have two choices: extend :mod:`optparse` or define a callback option.
1445Extending :mod:`optparse` is more general, but overkill for a lot of simple
1446cases. Quite often a simple callback is all you need.
1447
1448There are two steps to defining a callback option:
1449
Georg Brandl15a515f2009-09-17 22:11:49 +00001450* define the option itself using the ``"callback"`` action
Georg Brandl116aa622007-08-15 14:28:22 +00001451
1452* write the callback; this is a function (or method) that takes at least four
1453 arguments, as described below
1454
1455
1456.. _optparse-defining-callback-option:
1457
1458Defining a callback option
1459^^^^^^^^^^^^^^^^^^^^^^^^^^
1460
1461As always, the easiest way to define a callback option is by using the
Georg Brandl15a515f2009-09-17 22:11:49 +00001462:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1463only option attribute you must specify is ``callback``, the function to call::
Georg Brandl116aa622007-08-15 14:28:22 +00001464
1465 parser.add_option("-c", action="callback", callback=my_callback)
1466
1467``callback`` is a function (or other callable object), so you must have already
1468defined ``my_callback()`` when you create this callback option. In this simple
1469case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,
1470which usually means that the option takes no arguments---the mere presence of
1471:option:`-c` on the command-line is all it needs to know. In some
1472circumstances, though, you might want your callback to consume an arbitrary
1473number of command-line arguments. This is where writing callbacks gets tricky;
1474it's covered later in this section.
1475
1476:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandl15a515f2009-09-17 22:11:49 +00001477will only pass additional arguments if you specify them via
1478:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1479minimal callback function signature is::
Georg Brandl116aa622007-08-15 14:28:22 +00001480
1481 def my_callback(option, opt, value, parser):
1482
1483The four arguments to a callback are described below.
1484
1485There are several other option attributes that you can supply when you define a
1486callback option:
1487
Georg Brandl15a515f2009-09-17 22:11:49 +00001488:attr:`~Option.type`
1489 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1490 instructs :mod:`optparse` to consume one argument and convert it to
1491 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1492 though, :mod:`optparse` passes it to your callback function.
Georg Brandl116aa622007-08-15 14:28:22 +00001493
Georg Brandl15a515f2009-09-17 22:11:49 +00001494:attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001495 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001496 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1497 :attr:`~Option.type`. It then passes a tuple of converted values to your
1498 callback.
Georg Brandl116aa622007-08-15 14:28:22 +00001499
Georg Brandl15a515f2009-09-17 22:11:49 +00001500:attr:`~Option.callback_args`
Georg Brandl116aa622007-08-15 14:28:22 +00001501 a tuple of extra positional arguments to pass to the callback
1502
Georg Brandl15a515f2009-09-17 22:11:49 +00001503:attr:`~Option.callback_kwargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001504 a dictionary of extra keyword arguments to pass to the callback
1505
1506
1507.. _optparse-how-callbacks-called:
1508
1509How callbacks are called
1510^^^^^^^^^^^^^^^^^^^^^^^^
1511
1512All callbacks are called as follows::
1513
1514 func(option, opt_str, value, parser, *args, **kwargs)
1515
1516where
1517
1518``option``
1519 is the Option instance that's calling the callback
1520
1521``opt_str``
1522 is the option string seen on the command-line that's triggering the callback.
Georg Brandl15a515f2009-09-17 22:11:49 +00001523 (If an abbreviated long option was used, ``opt_str`` will be the full,
1524 canonical option string---e.g. if the user puts ``"--foo"`` on the
1525 command-line as an abbreviation for ``"--foobar"``, then ``opt_str`` will be
1526 ``"--foobar"``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001527
1528``value``
1529 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001530 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1531 the type implied by the option's type. If :attr:`~Option.type` for this option is
1532 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001533 > 1, ``value`` will be a tuple of values of the appropriate type.
1534
1535``parser``
Georg Brandl15a515f2009-09-17 22:11:49 +00001536 is the OptionParser instance driving the whole thing, mainly useful because
1537 you can access some other interesting data through its instance attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001538
1539 ``parser.largs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001540 the current list of leftover arguments, ie. arguments that have been
1541 consumed but are neither options nor option arguments. Feel free to modify
1542 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1543 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001544
1545 ``parser.rargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001546 the current list of remaining arguments, ie. with ``opt_str`` and
1547 ``value`` (if applicable) removed, and only the arguments following them
1548 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1549 arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001550
1551 ``parser.values``
1552 the object where option values are by default stored (an instance of
Georg Brandl15a515f2009-09-17 22:11:49 +00001553 optparse.OptionValues). This lets callbacks use the same mechanism as the
1554 rest of :mod:`optparse` for storing option values; you don't need to mess
1555 around with globals or closures. You can also access or modify the
1556 value(s) of any options already encountered on the command-line.
Georg Brandl116aa622007-08-15 14:28:22 +00001557
1558``args``
Georg Brandl15a515f2009-09-17 22:11:49 +00001559 is a tuple of arbitrary positional arguments supplied via the
1560 :attr:`~Option.callback_args` option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001561
1562``kwargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001563 is a dictionary of arbitrary keyword arguments supplied via
1564 :attr:`~Option.callback_kwargs`.
Georg Brandl116aa622007-08-15 14:28:22 +00001565
1566
1567.. _optparse-raising-errors-in-callback:
1568
1569Raising errors in a callback
1570^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1571
Georg Brandl15a515f2009-09-17 22:11:49 +00001572The callback function should raise :exc:`OptionValueError` if there are any
1573problems with the option or its argument(s). :mod:`optparse` catches this and
1574terminates the program, printing the error message you supply to stderr. Your
1575message should be clear, concise, accurate, and mention the option at fault.
1576Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl116aa622007-08-15 14:28:22 +00001577
1578
1579.. _optparse-callback-example-1:
1580
1581Callback example 1: trivial callback
1582^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1583
1584Here's an example of a callback option that takes no arguments, and simply
1585records that the option was seen::
1586
1587 def record_foo_seen(option, opt_str, value, parser):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001588 parser.values.saw_foo = True
Georg Brandl116aa622007-08-15 14:28:22 +00001589
1590 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1591
Georg Brandl15a515f2009-09-17 22:11:49 +00001592Of course, you could do that with the ``"store_true"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001593
1594
1595.. _optparse-callback-example-2:
1596
1597Callback example 2: check option order
1598^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1599
1600Here's a slightly more interesting example: record the fact that ``"-a"`` is
1601seen, but blow up if it comes after ``"-b"`` in the command-line. ::
1602
1603 def check_order(option, opt_str, value, parser):
1604 if parser.values.b:
1605 raise OptionValueError("can't use -a after -b")
1606 parser.values.a = 1
1607 [...]
1608 parser.add_option("-a", action="callback", callback=check_order)
1609 parser.add_option("-b", action="store_true", dest="b")
1610
1611
1612.. _optparse-callback-example-3:
1613
1614Callback example 3: check option order (generalized)
1615^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1616
1617If you want to re-use this callback for several similar options (set a flag, but
1618blow up if ``"-b"`` has already been seen), it needs a bit of work: the error
1619message and the flag that it sets must be generalized. ::
1620
1621 def check_order(option, opt_str, value, parser):
1622 if parser.values.b:
1623 raise OptionValueError("can't use %s after -b" % opt_str)
1624 setattr(parser.values, option.dest, 1)
1625 [...]
1626 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1627 parser.add_option("-b", action="store_true", dest="b")
1628 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1629
1630
1631.. _optparse-callback-example-4:
1632
1633Callback example 4: check arbitrary condition
1634^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1635
1636Of course, you could put any condition in there---you're not limited to checking
1637the values of already-defined options. For example, if you have options that
1638should not be called when the moon is full, all you have to do is this::
1639
1640 def check_moon(option, opt_str, value, parser):
1641 if is_moon_full():
1642 raise OptionValueError("%s option invalid when moon is full"
1643 % opt_str)
1644 setattr(parser.values, option.dest, 1)
1645 [...]
1646 parser.add_option("--foo",
1647 action="callback", callback=check_moon, dest="foo")
1648
1649(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1650
1651
1652.. _optparse-callback-example-5:
1653
1654Callback example 5: fixed arguments
1655^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1656
1657Things get slightly more interesting when you define callback options that take
1658a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandl15a515f2009-09-17 22:11:49 +00001659is similar to defining a ``"store"`` or ``"append"`` option: if you define
1660:attr:`~Option.type`, then the option takes one argument that must be
1661convertible to that type; if you further define :attr:`~Option.nargs`, then the
1662option takes :attr:`~Option.nargs` arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001663
Georg Brandl15a515f2009-09-17 22:11:49 +00001664Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl116aa622007-08-15 14:28:22 +00001665
1666 def store_value(option, opt_str, value, parser):
1667 setattr(parser.values, option.dest, value)
1668 [...]
1669 parser.add_option("--foo",
1670 action="callback", callback=store_value,
1671 type="int", nargs=3, dest="foo")
1672
1673Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1674them to integers for you; all you have to do is store them. (Or whatever;
1675obviously you don't need a callback for this example.)
1676
1677
1678.. _optparse-callback-example-6:
1679
1680Callback example 6: variable arguments
1681^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1682
1683Things get hairy when you want an option to take a variable number of arguments.
1684For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1685built-in capabilities for it. And you have to deal with certain intricacies of
1686conventional Unix command-line parsing that :mod:`optparse` normally handles for
1687you. In particular, callbacks should implement the conventional rules for bare
1688``"--"`` and ``"-"`` arguments:
1689
1690* either ``"--"`` or ``"-"`` can be option arguments
1691
1692* bare ``"--"`` (if not the argument to some option): halt command-line
1693 processing and discard the ``"--"``
1694
1695* bare ``"-"`` (if not the argument to some option): halt command-line
1696 processing but keep the ``"-"`` (append it to ``parser.largs``)
1697
1698If you want an option that takes a variable number of arguments, there are
1699several subtle, tricky issues to worry about. The exact implementation you
1700choose will be based on which trade-offs you're willing to make for your
1701application (which is why :mod:`optparse` doesn't support this sort of thing
1702directly).
1703
1704Nevertheless, here's a stab at a callback for an option with variable
1705arguments::
1706
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001707 def vararg_callback(option, opt_str, value, parser):
1708 assert value is None
1709 value = []
Georg Brandl116aa622007-08-15 14:28:22 +00001710
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001711 def floatable(str):
1712 try:
1713 float(str)
1714 return True
1715 except ValueError:
1716 return False
Georg Brandl116aa622007-08-15 14:28:22 +00001717
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001718 for arg in parser.rargs:
1719 # stop on --foo like options
1720 if arg[:2] == "--" and len(arg) > 2:
1721 break
1722 # stop on -a, but not on -3 or -3.0
1723 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1724 break
1725 value.append(arg)
1726
1727 del parser.rargs[:len(value)]
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001728 setattr(parser.values, option.dest, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001729
1730 [...]
Benjamin Petersonae5360b2008-09-08 23:05:23 +00001731 parser.add_option("-c", "--callback", dest="vararg_attr",
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001732 action="callback", callback=vararg_callback)
Georg Brandl116aa622007-08-15 14:28:22 +00001733
Georg Brandl116aa622007-08-15 14:28:22 +00001734
1735.. _optparse-extending-optparse:
1736
1737Extending :mod:`optparse`
1738-------------------------
1739
1740Since the two major controlling factors in how :mod:`optparse` interprets
1741command-line options are the action and type of each option, the most likely
1742direction of extension is to add new actions and new types.
1743
1744
1745.. _optparse-adding-new-types:
1746
1747Adding new types
1748^^^^^^^^^^^^^^^^
1749
1750To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandl15a515f2009-09-17 22:11:49 +00001751:class:`Option` class. This class has a couple of attributes that define
1752:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl116aa622007-08-15 14:28:22 +00001753
Georg Brandl15a515f2009-09-17 22:11:49 +00001754.. attribute:: Option.TYPES
Georg Brandl116aa622007-08-15 14:28:22 +00001755
Georg Brandl15a515f2009-09-17 22:11:49 +00001756 A tuple of type names; in your subclass, simply define a new tuple
1757 :attr:`TYPES` that builds on the standard one.
Georg Brandl116aa622007-08-15 14:28:22 +00001758
Georg Brandl15a515f2009-09-17 22:11:49 +00001759.. attribute:: Option.TYPE_CHECKER
Georg Brandl116aa622007-08-15 14:28:22 +00001760
Georg Brandl15a515f2009-09-17 22:11:49 +00001761 A dictionary mapping type names to type-checking functions. A type-checking
1762 function has the following signature::
Georg Brandl116aa622007-08-15 14:28:22 +00001763
Georg Brandl15a515f2009-09-17 22:11:49 +00001764 def check_mytype(option, opt, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001765
Georg Brandl15a515f2009-09-17 22:11:49 +00001766 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1767 (e.g., ``"-f"``), and ``value`` is the string from the command line that must
1768 be checked and converted to your desired type. ``check_mytype()`` should
1769 return an object of the hypothetical type ``mytype``. The value returned by
1770 a type-checking function will wind up in the OptionValues instance returned
1771 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1772 ``value`` parameter.
1773
1774 Your type-checking function should raise :exc:`OptionValueError` if it
1775 encounters any problems. :exc:`OptionValueError` takes a single string
1776 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1777 method, which in turn prepends the program name and the string ``"error:"``
1778 and prints everything to stderr before terminating the process.
1779
1780Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl116aa622007-08-15 14:28:22 +00001781parse Python-style complex numbers on the command line. (This is even sillier
1782than it used to be, because :mod:`optparse` 1.3 added built-in support for
1783complex numbers, but never mind.)
1784
1785First, the necessary imports::
1786
1787 from copy import copy
1788 from optparse import Option, OptionValueError
1789
1790You need to define your type-checker first, since it's referred to later (in the
Georg Brandl15a515f2009-09-17 22:11:49 +00001791:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl116aa622007-08-15 14:28:22 +00001792
1793 def check_complex(option, opt, value):
1794 try:
1795 return complex(value)
1796 except ValueError:
1797 raise OptionValueError(
1798 "option %s: invalid complex value: %r" % (opt, value))
1799
1800Finally, the Option subclass::
1801
1802 class MyOption (Option):
1803 TYPES = Option.TYPES + ("complex",)
1804 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1805 TYPE_CHECKER["complex"] = check_complex
1806
1807(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandl15a515f2009-09-17 22:11:49 +00001808up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1809Option class. This being Python, nothing stops you from doing that except good
1810manners and common sense.)
Georg Brandl116aa622007-08-15 14:28:22 +00001811
1812That's it! Now you can write a script that uses the new option type just like
1813any other :mod:`optparse`\ -based script, except you have to instruct your
1814OptionParser to use MyOption instead of Option::
1815
1816 parser = OptionParser(option_class=MyOption)
1817 parser.add_option("-c", type="complex")
1818
1819Alternately, you can build your own option list and pass it to OptionParser; if
1820you don't use :meth:`add_option` in the above way, you don't need to tell
1821OptionParser which option class to use::
1822
1823 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1824 parser = OptionParser(option_list=option_list)
1825
1826
1827.. _optparse-adding-new-actions:
1828
1829Adding new actions
1830^^^^^^^^^^^^^^^^^^
1831
1832Adding new actions is a bit trickier, because you have to understand that
1833:mod:`optparse` has a couple of classifications for actions:
1834
1835"store" actions
1836 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandl15a515f2009-09-17 22:11:49 +00001837 current OptionValues instance; these options require a :attr:`~Option.dest`
1838 attribute to be supplied to the Option constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001839
1840"typed" actions
Georg Brandl15a515f2009-09-17 22:11:49 +00001841 actions that take a value from the command line and expect it to be of a
1842 certain type; or rather, a string that can be converted to a certain type.
1843 These options require a :attr:`~Option.type` attribute to the Option
1844 constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001845
Georg Brandl15a515f2009-09-17 22:11:49 +00001846These are overlapping sets: some default "store" actions are ``"store"``,
1847``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1848actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001849
1850When you add an action, you need to categorize it by listing it in at least one
1851of the following class attributes of Option (all are lists of strings):
1852
Georg Brandl15a515f2009-09-17 22:11:49 +00001853.. attribute:: Option.ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001854
Georg Brandl15a515f2009-09-17 22:11:49 +00001855 All actions must be listed in ACTIONS.
Georg Brandl116aa622007-08-15 14:28:22 +00001856
Georg Brandl15a515f2009-09-17 22:11:49 +00001857.. attribute:: Option.STORE_ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001858
Georg Brandl15a515f2009-09-17 22:11:49 +00001859 "store" actions are additionally listed here.
1860
1861.. attribute:: Option.TYPED_ACTIONS
1862
1863 "typed" actions are additionally listed here.
1864
1865.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1866
1867 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl116aa622007-08-15 14:28:22 +00001868 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001869 assigns the default type, ``"string"``, to options with no explicit type
1870 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001871
1872In order to actually implement your new action, you must override Option's
1873:meth:`take_action` method and add a case that recognizes your action.
1874
Georg Brandl15a515f2009-09-17 22:11:49 +00001875For example, let's add an ``"extend"`` action. This is similar to the standard
1876``"append"`` action, but instead of taking a single value from the command-line
1877and appending it to an existing list, ``"extend"`` will take multiple values in
1878a single comma-delimited string, and extend an existing list with them. That
1879is, if ``"--names"`` is an ``"extend"`` option of type ``"string"``, the command
1880line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001881
1882 --names=foo,bar --names blah --names ding,dong
1883
1884would result in a list ::
1885
1886 ["foo", "bar", "blah", "ding", "dong"]
1887
1888Again we define a subclass of Option::
1889
Ezio Melotti383ae952010-01-03 09:06:02 +00001890 class MyOption(Option):
Georg Brandl116aa622007-08-15 14:28:22 +00001891
1892 ACTIONS = Option.ACTIONS + ("extend",)
1893 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1894 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1895 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1896
1897 def take_action(self, action, dest, opt, value, values, parser):
1898 if action == "extend":
1899 lvalue = value.split(",")
1900 values.ensure_value(dest, []).extend(lvalue)
1901 else:
1902 Option.take_action(
1903 self, action, dest, opt, value, values, parser)
1904
1905Features of note:
1906
Georg Brandl15a515f2009-09-17 22:11:49 +00001907* ``"extend"`` both expects a value on the command-line and stores that value
1908 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1909 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001910
Georg Brandl15a515f2009-09-17 22:11:49 +00001911* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1912 ``"extend"`` actions, we put the ``"extend"`` action in
1913 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001914
1915* :meth:`MyOption.take_action` implements just this one new action, and passes
1916 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001917 actions.
Georg Brandl116aa622007-08-15 14:28:22 +00001918
Georg Brandl15a515f2009-09-17 22:11:49 +00001919* ``values`` is an instance of the optparse_parser.Values class, which provides
1920 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1921 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001922
1923 values.ensure_value(attr, value)
1924
1925 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandl15a515f2009-09-17 22:11:49 +00001926 ensure_value() first sets it to ``value``, and then returns 'value. This is
1927 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
1928 of which accumulate data in a variable and expect that variable to be of a
1929 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl116aa622007-08-15 14:28:22 +00001930 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandl15a515f2009-09-17 22:11:49 +00001931 about setting a default value for the option destinations in question; they
1932 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl116aa622007-08-15 14:28:22 +00001933 getting it right when it's needed.