blob: 523079f9a86447803dd2b93317b61d87bd7806de [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`optparse` --- More powerful command line option parser
2============================================================
3
4.. module:: optparse
5 :synopsis: More convenient, flexible, and powerful command-line parsing library.
6.. moduleauthor:: Greg Ward <gward@python.net>
Georg Brandl116aa622007-08-15 14:28:22 +00007.. sectionauthor:: Greg Ward <gward@python.net>
8
9
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
Georg Brandl15a515f2009-09-17 22:11:49 +000054and :mod:`optparse` will print out a brief summary of your script's options::
Georg Brandl116aa622007-08-15 14:28:22 +000055
56 usage: <yourscript> [options]
57
58 options:
59 -h, --help show this help message and exit
60 -f FILE, --file=FILE write report to FILE
61 -q, --quiet don't print status messages to stdout
62
63where the value of *yourscript* is determined at runtime (normally from
64``sys.argv[0]``).
65
Georg Brandl116aa622007-08-15 14:28:22 +000066
67.. _optparse-background:
68
69Background
70----------
71
72:mod:`optparse` was explicitly designed to encourage the creation of programs
73with straightforward, conventional command-line interfaces. To that end, it
74supports only the most common command-line syntax and semantics conventionally
75used under Unix. If you are unfamiliar with these conventions, read this
76section to acquaint yourself with them.
77
78
79.. _optparse-terminology:
80
81Terminology
82^^^^^^^^^^^
83
84argument
Georg Brandl15a515f2009-09-17 22:11:49 +000085 a string entered on the command-line, and passed by the shell to ``execl()``
86 or ``execv()``. In Python, arguments are elements of ``sys.argv[1:]``
87 (``sys.argv[0]`` is the name of the program being executed). Unix shells
88 also use the term "word".
Georg Brandl116aa622007-08-15 14:28:22 +000089
90 It is occasionally desirable to substitute an argument list other than
91 ``sys.argv[1:]``, so you should read "argument" as "an element of
92 ``sys.argv[1:]``, or of some other list provided as a substitute for
93 ``sys.argv[1:]``".
94
Benjamin Petersonae5360b2008-09-08 23:05:23 +000095option
Georg Brandl15a515f2009-09-17 22:11:49 +000096 an argument used to supply extra information to guide or customize the
97 execution of a program. There are many different syntaxes for options; the
98 traditional Unix syntax is a hyphen ("-") followed by a single letter,
99 e.g. ``"-x"`` or ``"-F"``. Also, traditional Unix syntax allows multiple
100 options to be merged into a single argument, e.g. ``"-x -F"`` is equivalent
101 to ``"-xF"``. The GNU project introduced ``"--"`` followed by a series of
102 hyphen-separated words, e.g. ``"--file"`` or ``"--dry-run"``. These are the
103 only two option syntaxes provided by :mod:`optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105 Some other option syntaxes that the world has seen include:
106
107 * a hyphen followed by a few letters, e.g. ``"-pf"`` (this is *not* the same
108 as multiple options merged into a single argument)
109
110 * a hyphen followed by a whole word, e.g. ``"-file"`` (this is technically
111 equivalent to the previous syntax, but they aren't usually seen in the same
112 program)
113
114 * a plus sign followed by a single letter, or a few letters, or a word, e.g.
115 ``"+f"``, ``"+rgb"``
116
117 * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
118 ``"/file"``
119
Georg Brandl15a515f2009-09-17 22:11:49 +0000120 These option syntaxes are not supported by :mod:`optparse`, and they never
121 will be. This is deliberate: the first three are non-standard on any
122 environment, and the last only makes sense if you're exclusively targeting
123 VMS, MS-DOS, and/or Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000124
125option argument
Georg Brandl15a515f2009-09-17 22:11:49 +0000126 an argument that follows an option, is closely associated with that option,
127 and is consumed from the argument list when that option is. With
128 :mod:`optparse`, option arguments may either be in a separate argument from
129 their option::
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131 -f foo
132 --file foo
133
134 or included in the same argument::
135
136 -ffoo
137 --file=foo
138
Georg Brandl15a515f2009-09-17 22:11:49 +0000139 Typically, a given option either takes an argument or it doesn't. Lots of
140 people want an "optional option arguments" feature, meaning that some options
141 will take an argument if they see it, and won't if they don't. This is
142 somewhat controversial, because it makes parsing ambiguous: if ``"-a"`` takes
143 an optional argument and ``"-b"`` is another option entirely, how do we
144 interpret ``"-ab"``? Because of this ambiguity, :mod:`optparse` does not
145 support this feature.
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147positional argument
148 something leftover in the argument list after options have been parsed, i.e.
Georg Brandl15a515f2009-09-17 22:11:49 +0000149 after options and their arguments have been parsed and removed from the
150 argument list.
Georg Brandl116aa622007-08-15 14:28:22 +0000151
152required option
153 an option that must be supplied on the command-line; note that the phrase
154 "required option" is self-contradictory in English. :mod:`optparse` doesn't
Georg Brandl15a515f2009-09-17 22:11:49 +0000155 prevent you from implementing required options, but doesn't give you much
156 help at it either. See ``examples/required_1.py`` and
157 ``examples/required_2.py`` in the :mod:`optparse` source distribution for two
158 ways to implement required options with :mod:`optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160For example, consider this hypothetical command-line::
161
162 prog -v --report /tmp/report.txt foo bar
163
164``"-v"`` and ``"--report"`` are both options. Assuming that :option:`--report`
165takes one argument, ``"/tmp/report.txt"`` is an option argument. ``"foo"`` and
166``"bar"`` are positional arguments.
167
168
169.. _optparse-what-options-for:
170
171What are options for?
172^^^^^^^^^^^^^^^^^^^^^
173
174Options are used to provide extra information to tune or customize the execution
175of a program. In case it wasn't clear, options are usually *optional*. A
176program should be able to run just fine with no options whatsoever. (Pick a
177random program from the Unix or GNU toolsets. Can it run without any options at
178all and still make sense? The main exceptions are ``find``, ``tar``, and
179``dd``\ ---all of which are mutant oddballs that have been rightly criticized
180for their non-standard syntax and confusing interfaces.)
181
182Lots of people want their programs to have "required options". Think about it.
183If it's required, then it's *not optional*! If there is a piece of information
184that your program absolutely requires in order to run successfully, that's what
185positional arguments are for.
186
187As an example of good command-line interface design, consider the humble ``cp``
188utility, for copying files. It doesn't make much sense to try to copy files
189without supplying a destination and at least one source. Hence, ``cp`` fails if
190you run it with no arguments. However, it has a flexible, useful syntax that
191does not require any options at all::
192
193 cp SOURCE DEST
194 cp SOURCE ... DEST-DIR
195
196You can get pretty far with just that. Most ``cp`` implementations provide a
197bunch of options to tweak exactly how the files are copied: you can preserve
198mode and modification time, avoid following symlinks, ask before clobbering
199existing files, etc. But none of this distracts from the core mission of
200``cp``, which is to copy either one file to another, or several files to another
201directory.
202
203
204.. _optparse-what-positional-arguments-for:
205
206What are positional arguments for?
207^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
208
209Positional arguments are for those pieces of information that your program
210absolutely, positively requires to run.
211
212A good user interface should have as few absolute requirements as possible. If
213your program requires 17 distinct pieces of information in order to run
214successfully, it doesn't much matter *how* you get that information from the
215user---most people will give up and walk away before they successfully run the
216program. This applies whether the user interface is a command-line, a
217configuration file, or a GUI: if you make that many demands on your users, most
218of them will simply give up.
219
220In short, try to minimize the amount of information that users are absolutely
221required to supply---use sensible defaults whenever possible. Of course, you
222also want to make your programs reasonably flexible. That's what options are
223for. Again, it doesn't matter if they are entries in a config file, widgets in
224the "Preferences" dialog of a GUI, or command-line options---the more options
225you implement, the more flexible your program is, and the more complicated its
226implementation becomes. Too much flexibility has drawbacks as well, of course;
227too many options can overwhelm users and make your code much harder to maintain.
228
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230.. _optparse-tutorial:
231
232Tutorial
233--------
234
235While :mod:`optparse` is quite flexible and powerful, it's also straightforward
236to use in most cases. This section covers the code patterns that are common to
237any :mod:`optparse`\ -based program.
238
239First, you need to import the OptionParser class; then, early in the main
240program, create an OptionParser instance::
241
242 from optparse import OptionParser
243 [...]
244 parser = OptionParser()
245
246Then you can start defining options. The basic syntax is::
247
248 parser.add_option(opt_str, ...,
249 attr=value, ...)
250
251Each option has one or more option strings, such as ``"-f"`` or ``"--file"``,
252and several option attributes that tell :mod:`optparse` what to expect and what
253to do when it encounters that option on the command line.
254
255Typically, each option will have one short option string and one long option
256string, e.g.::
257
258 parser.add_option("-f", "--file", ...)
259
260You're free to define as many short option strings and as many long option
261strings as you like (including zero), as long as there is at least one option
262string overall.
263
264The option strings passed to :meth:`add_option` are effectively labels for the
265option defined by that call. For brevity, we will frequently refer to
266*encountering an option* on the command line; in reality, :mod:`optparse`
267encounters *option strings* and looks up options from them.
268
269Once all of your options are defined, instruct :mod:`optparse` to parse your
270program's command line::
271
272 (options, args) = parser.parse_args()
273
274(If you like, you can pass a custom argument list to :meth:`parse_args`, but
275that's rarely necessary: by default it uses ``sys.argv[1:]``.)
276
277:meth:`parse_args` returns two values:
278
279* ``options``, an object containing values for all of your options---e.g. if
280 ``"--file"`` takes a single string argument, then ``options.file`` will be the
281 filename supplied by the user, or ``None`` if the user did not supply that
282 option
283
284* ``args``, the list of positional arguments leftover after parsing options
285
286This tutorial section only covers the four most important option attributes:
Georg Brandl15a515f2009-09-17 22:11:49 +0000287:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
288(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
289most fundamental.
Georg Brandl116aa622007-08-15 14:28:22 +0000290
291
292.. _optparse-understanding-option-actions:
293
294Understanding option actions
295^^^^^^^^^^^^^^^^^^^^^^^^^^^^
296
297Actions tell :mod:`optparse` what to do when it encounters an option on the
298command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
299adding new actions is an advanced topic covered in section
Georg Brandl15a515f2009-09-17 22:11:49 +0000300:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
301a value in some variable---for example, take a string from the command line and
302store it in an attribute of ``options``.
Georg Brandl116aa622007-08-15 14:28:22 +0000303
304If you don't specify an option action, :mod:`optparse` defaults to ``store``.
305
306
307.. _optparse-store-action:
308
309The store action
310^^^^^^^^^^^^^^^^
311
312The most common option action is ``store``, which tells :mod:`optparse` to take
313the next argument (or the remainder of the current argument), ensure that it is
314of the correct type, and store it to your chosen destination.
315
316For example::
317
318 parser.add_option("-f", "--file",
319 action="store", type="string", dest="filename")
320
321Now let's make up a fake command line and ask :mod:`optparse` to parse it::
322
323 args = ["-f", "foo.txt"]
324 (options, args) = parser.parse_args(args)
325
326When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
327argument, ``"foo.txt"``, and stores it in ``options.filename``. So, after this
328call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
329
330Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
331Here's an option that expects an integer argument::
332
333 parser.add_option("-n", type="int", dest="num")
334
335Note that this option has no long option string, which is perfectly acceptable.
336Also, there's no explicit action, since the default is ``store``.
337
338Let's parse another fake command-line. This time, we'll jam the option argument
339right up against the option: since ``"-n42"`` (one argument) is equivalent to
Georg Brandl15a515f2009-09-17 22:11:49 +0000340``"-n 42"`` (two arguments), the code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000341
342 (options, args) = parser.parse_args(["-n42"])
Georg Brandl6911e3c2007-09-04 07:15:32 +0000343 print(options.num)
Georg Brandl116aa622007-08-15 14:28:22 +0000344
345will print ``"42"``.
346
347If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
348the fact that the default action is ``store``, that means our first example can
349be a lot shorter::
350
351 parser.add_option("-f", "--file", dest="filename")
352
353If you don't supply a destination, :mod:`optparse` figures out a sensible
354default from the option strings: if the first long option string is
355``"--foo-bar"``, then the default destination is ``foo_bar``. If there are no
356long option strings, :mod:`optparse` looks at the first short option string: the
357default destination for ``"-f"`` is ``f``.
358
Georg Brandl5c106642007-11-29 17:41:05 +0000359:mod:`optparse` also includes the built-in ``complex`` type. Adding
Georg Brandl116aa622007-08-15 14:28:22 +0000360types is covered in section :ref:`optparse-extending-optparse`.
361
362
363.. _optparse-handling-boolean-options:
364
365Handling boolean (flag) options
366^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
367
368Flag options---set a variable to true or false when a particular option is seen
369---are quite common. :mod:`optparse` supports them with two separate actions,
370``store_true`` and ``store_false``. For example, you might have a ``verbose``
371flag that is turned on with ``"-v"`` and off with ``"-q"``::
372
373 parser.add_option("-v", action="store_true", dest="verbose")
374 parser.add_option("-q", action="store_false", dest="verbose")
375
376Here we have two different options with the same destination, which is perfectly
377OK. (It just means you have to be a bit careful when setting default values---
378see below.)
379
380When :mod:`optparse` encounters ``"-v"`` on the command line, it sets
381``options.verbose`` to ``True``; when it encounters ``"-q"``,
382``options.verbose`` is set to ``False``.
383
384
385.. _optparse-other-actions:
386
387Other actions
388^^^^^^^^^^^^^
389
390Some other actions supported by :mod:`optparse` are:
391
Georg Brandl15a515f2009-09-17 22:11:49 +0000392``"store_const"``
Georg Brandl116aa622007-08-15 14:28:22 +0000393 store a constant value
394
Georg Brandl15a515f2009-09-17 22:11:49 +0000395``"append"``
Georg Brandl116aa622007-08-15 14:28:22 +0000396 append this option's argument to a list
397
Georg Brandl15a515f2009-09-17 22:11:49 +0000398``"count"``
Georg Brandl116aa622007-08-15 14:28:22 +0000399 increment a counter by one
400
Georg Brandl15a515f2009-09-17 22:11:49 +0000401``"callback"``
Georg Brandl116aa622007-08-15 14:28:22 +0000402 call a specified function
403
404These are covered in section :ref:`optparse-reference-guide`, Reference Guide
405and section :ref:`optparse-option-callbacks`.
406
407
408.. _optparse-default-values:
409
410Default values
411^^^^^^^^^^^^^^
412
413All of the above examples involve setting some variable (the "destination") when
414certain command-line options are seen. What happens if those options are never
415seen? Since we didn't supply any defaults, they are all set to ``None``. This
416is usually fine, but sometimes you want more control. :mod:`optparse` lets you
417supply a default value for each destination, which is assigned before the
418command line is parsed.
419
420First, consider the verbose/quiet example. If we want :mod:`optparse` to set
421``verbose`` to ``True`` unless ``"-q"`` is seen, then we can do this::
422
423 parser.add_option("-v", action="store_true", dest="verbose", default=True)
424 parser.add_option("-q", action="store_false", dest="verbose")
425
426Since default values apply to the *destination* rather than to any particular
427option, and these two options happen to have the same destination, this is
428exactly equivalent::
429
430 parser.add_option("-v", action="store_true", dest="verbose")
431 parser.add_option("-q", action="store_false", dest="verbose", default=True)
432
433Consider this::
434
435 parser.add_option("-v", action="store_true", dest="verbose", default=False)
436 parser.add_option("-q", action="store_false", dest="verbose", default=True)
437
438Again, the default value for ``verbose`` will be ``True``: the last default
439value supplied for any particular destination is the one that counts.
440
441A clearer way to specify default values is the :meth:`set_defaults` method of
442OptionParser, which you can call at any time before calling :meth:`parse_args`::
443
444 parser.set_defaults(verbose=True)
445 parser.add_option(...)
446 (options, args) = parser.parse_args()
447
448As before, the last value specified for a given option destination is the one
449that counts. For clarity, try to use one method or the other of setting default
450values, not both.
451
452
453.. _optparse-generating-help:
454
455Generating help
456^^^^^^^^^^^^^^^
457
458:mod:`optparse`'s ability to generate help and usage text automatically is
459useful for creating user-friendly command-line interfaces. All you have to do
Georg Brandl15a515f2009-09-17 22:11:49 +0000460is supply a :attr:`~Option.help` value for each option, and optionally a short
461usage message for your whole program. Here's an OptionParser populated with
Georg Brandl116aa622007-08-15 14:28:22 +0000462user-friendly (documented) options::
463
464 usage = "usage: %prog [options] arg1 arg2"
465 parser = OptionParser(usage=usage)
466 parser.add_option("-v", "--verbose",
467 action="store_true", dest="verbose", default=True,
468 help="make lots of noise [default]")
469 parser.add_option("-q", "--quiet",
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000470 action="store_false", dest="verbose",
Georg Brandl116aa622007-08-15 14:28:22 +0000471 help="be vewwy quiet (I'm hunting wabbits)")
472 parser.add_option("-f", "--filename",
Georg Brandlee8783d2009-09-16 16:00:31 +0000473 metavar="FILE", help="write output to FILE")
Georg Brandl116aa622007-08-15 14:28:22 +0000474 parser.add_option("-m", "--mode",
475 default="intermediate",
476 help="interaction mode: novice, intermediate, "
477 "or expert [default: %default]")
478
479If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
480command-line, or if you just call :meth:`parser.print_help`, it prints the
481following to standard output::
482
483 usage: <yourscript> [options] arg1 arg2
484
485 options:
486 -h, --help show this help message and exit
487 -v, --verbose make lots of noise [default]
488 -q, --quiet be vewwy quiet (I'm hunting wabbits)
489 -f FILE, --filename=FILE
490 write output to FILE
491 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
492 expert [default: intermediate]
493
494(If the help output is triggered by a help option, :mod:`optparse` exits after
495printing the help text.)
496
497There's a lot going on here to help :mod:`optparse` generate the best possible
498help message:
499
500* the script defines its own usage message::
501
502 usage = "usage: %prog [options] arg1 arg2"
503
504 :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
Georg Brandl15a515f2009-09-17 22:11:49 +0000505 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
506 is then printed before the detailed option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000507
508 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandl15a515f2009-09-17 22:11:49 +0000509 default: ``"usage: %prog [options]"``, which is fine if your script doesn't
510 take any positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000511
512* every option defines a help string, and doesn't worry about line-wrapping---
513 :mod:`optparse` takes care of wrapping lines and making the help output look
514 good.
515
516* options that take a value indicate this fact in their automatically-generated
517 help message, e.g. for the "mode" option::
518
519 -m MODE, --mode=MODE
520
521 Here, "MODE" is called the meta-variable: it stands for the argument that the
522 user is expected to supply to :option:`-m`/:option:`--mode`. By default,
523 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandl15a515f2009-09-17 22:11:49 +0000524 that for the meta-variable. Sometimes, that's not what you want---for
525 example, the :option:`--filename` option explicitly sets ``metavar="FILE"``,
526 resulting in this automatically-generated option description::
Georg Brandl116aa622007-08-15 14:28:22 +0000527
528 -f FILE, --filename=FILE
529
Georg Brandl15a515f2009-09-17 22:11:49 +0000530 This is important for more than just saving space, though: the manually
531 written help text uses the meta-variable "FILE" to clue the user in that
532 there's a connection between the semi-formal syntax "-f FILE" and the informal
533 semantic description "write output to FILE". This is a simple but effective
534 way to make your help text a lot clearer and more useful for end users.
Georg Brandl116aa622007-08-15 14:28:22 +0000535
536* options that have a default value can include ``%default`` in the help
537 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
538 default value. If an option has no default value (or the default value is
539 ``None``), ``%default`` expands to ``none``.
540
Georg Brandl15a515f2009-09-17 22:11:49 +0000541When dealing with many options, it is convenient to group these options for
542better help output. An :class:`OptionParser` can contain several option groups,
543each of which can contain several options.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000544
Georg Brandl15a515f2009-09-17 22:11:49 +0000545Continuing with the parser defined above, adding an :class:`OptionGroup` to a
546parser is easy::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000547
548 group = OptionGroup(parser, "Dangerous Options",
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000549 "Caution: use these options at your own risk. "
550 "It is believed that some of them bite.")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000551 group.add_option("-g", action="store_true", help="Group option.")
552 parser.add_option_group(group)
553
554This would result in the following help output::
555
556 usage: [options] arg1 arg2
557
558 options:
559 -h, --help show this help message and exit
560 -v, --verbose make lots of noise [default]
561 -q, --quiet be vewwy quiet (I'm hunting wabbits)
562 -fFILE, --file=FILE write output to FILE
563 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000564 [default], 'expert'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000565
566 Dangerous Options:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000567 Caution: use of these options is at your own risk. It is believed that
568 some of them bite.
569 -g Group option.
Georg Brandl116aa622007-08-15 14:28:22 +0000570
571.. _optparse-printing-version-string:
572
573Printing a version string
574^^^^^^^^^^^^^^^^^^^^^^^^^
575
576Similar to the brief usage string, :mod:`optparse` can also print a version
577string for your program. You have to supply the string as the ``version``
578argument to OptionParser::
579
580 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
581
582``"%prog"`` is expanded just like it is in ``usage``. Apart from that,
583``version`` can contain anything you like. When you supply it, :mod:`optparse`
584automatically adds a ``"--version"`` option to your parser. If it encounters
585this option on the command line, it expands your ``version`` string (by
586replacing ``"%prog"``), prints it to stdout, and exits.
587
588For example, if your script is called ``/usr/bin/foo``::
589
590 $ /usr/bin/foo --version
591 foo 1.0
592
593
594.. _optparse-how-optparse-handles-errors:
595
596How :mod:`optparse` handles errors
597^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
598
599There are two broad classes of errors that :mod:`optparse` has to worry about:
600programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandl15a515f2009-09-17 22:11:49 +0000601calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
602option attributes, missing option attributes, etc. These are dealt with in the
603usual way: raise an exception (either :exc:`optparse.OptionError` or
604:exc:`TypeError`) and let the program crash.
Georg Brandl116aa622007-08-15 14:28:22 +0000605
606Handling user errors is much more important, since they are guaranteed to happen
607no matter how stable your code is. :mod:`optparse` can automatically detect
608some user errors, such as bad option arguments (passing ``"-n 4x"`` where
609:option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
610of the command line, where :option:`-n` takes an argument of any type). Also,
Georg Brandl15a515f2009-09-17 22:11:49 +0000611you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl116aa622007-08-15 14:28:22 +0000612condition::
613
614 (options, args) = parser.parse_args()
615 [...]
616 if options.a and options.b:
617 parser.error("options -a and -b are mutually exclusive")
618
619In either case, :mod:`optparse` handles the error the same way: it prints the
620program's usage message and an error message to standard error and exits with
621error status 2.
622
623Consider the first example above, where the user passes ``"4x"`` to an option
624that takes an integer::
625
626 $ /usr/bin/foo -n 4x
627 usage: foo [options]
628
629 foo: error: option -n: invalid integer value: '4x'
630
631Or, where the user fails to pass a value at all::
632
633 $ /usr/bin/foo -n
634 usage: foo [options]
635
636 foo: error: -n option requires an argument
637
638:mod:`optparse`\ -generated error messages take care always to mention the
639option involved in the error; be sure to do the same when calling
Georg Brandl15a515f2009-09-17 22:11:49 +0000640:func:`OptionParser.error` from your application code.
Georg Brandl116aa622007-08-15 14:28:22 +0000641
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000642If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000643you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
644and/or :meth:`~OptionParser.error` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000645
646
647.. _optparse-putting-it-all-together:
648
649Putting it all together
650^^^^^^^^^^^^^^^^^^^^^^^
651
652Here's what :mod:`optparse`\ -based scripts usually look like::
653
654 from optparse import OptionParser
655 [...]
656 def main():
657 usage = "usage: %prog [options] arg"
658 parser = OptionParser(usage)
659 parser.add_option("-f", "--file", dest="filename",
660 help="read data from FILENAME")
661 parser.add_option("-v", "--verbose",
662 action="store_true", dest="verbose")
663 parser.add_option("-q", "--quiet",
664 action="store_false", dest="verbose")
665 [...]
666 (options, args) = parser.parse_args()
667 if len(args) != 1:
668 parser.error("incorrect number of arguments")
669 if options.verbose:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000670 print("reading %s..." % options.filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000671 [...]
672
673 if __name__ == "__main__":
674 main()
675
Georg Brandl116aa622007-08-15 14:28:22 +0000676
677.. _optparse-reference-guide:
678
679Reference Guide
680---------------
681
682
683.. _optparse-creating-parser:
684
685Creating the parser
686^^^^^^^^^^^^^^^^^^^
687
Georg Brandl15a515f2009-09-17 22:11:49 +0000688The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Georg Brandl15a515f2009-09-17 22:11:49 +0000690.. class:: OptionParser(...)
Georg Brandl116aa622007-08-15 14:28:22 +0000691
Georg Brandl15a515f2009-09-17 22:11:49 +0000692 The OptionParser constructor has no required arguments, but a number of
693 optional keyword arguments. You should always pass them as keyword
694 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl116aa622007-08-15 14:28:22 +0000695
696 ``usage`` (default: ``"%prog [options]"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000697 The usage summary to print when your program is run incorrectly or with a
698 help option. When :mod:`optparse` prints the usage string, it expands
699 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
700 passed that keyword argument). To suppress a usage message, pass the
701 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl116aa622007-08-15 14:28:22 +0000702
703 ``option_list`` (default: ``[]``)
704 A list of Option objects to populate the parser with. The options in
Georg Brandl15a515f2009-09-17 22:11:49 +0000705 ``option_list`` are added after any options in ``standard_option_list`` (a
706 class attribute that may be set by OptionParser subclasses), but before
707 any version or help options. Deprecated; use :meth:`add_option` after
708 creating the parser instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000709
710 ``option_class`` (default: optparse.Option)
711 Class to use when adding options to the parser in :meth:`add_option`.
712
713 ``version`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000714 A version string to print when the user supplies a version option. If you
715 supply a true value for ``version``, :mod:`optparse` automatically adds a
716 version option with the single option string ``"--version"``. The
717 substring ``"%prog"`` is expanded the same as for ``usage``.
Georg Brandl116aa622007-08-15 14:28:22 +0000718
719 ``conflict_handler`` (default: ``"error"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000720 Specifies what to do when options with conflicting option strings are
721 added to the parser; see section
722 :ref:`optparse-conflicts-between-options`.
Georg Brandl116aa622007-08-15 14:28:22 +0000723
724 ``description`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000725 A paragraph of text giving a brief overview of your program.
726 :mod:`optparse` reformats this paragraph to fit the current terminal width
727 and prints it when the user requests help (after ``usage``, but before the
728 list of options).
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Georg Brandl15a515f2009-09-17 22:11:49 +0000730 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
731 An instance of optparse.HelpFormatter that will be used for printing help
732 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl116aa622007-08-15 14:28:22 +0000733 IndentedHelpFormatter and TitledHelpFormatter.
734
735 ``add_help_option`` (default: ``True``)
736 If true, :mod:`optparse` will add a help option (with option strings ``"-h"``
737 and ``"--help"``) to the parser.
738
739 ``prog``
740 The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
741 instead of ``os.path.basename(sys.argv[0])``.
742
743
744
745.. _optparse-populating-parser:
746
747Populating the parser
748^^^^^^^^^^^^^^^^^^^^^
749
750There are several ways to populate the parser with options. The preferred way
Georg Brandl15a515f2009-09-17 22:11:49 +0000751is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl116aa622007-08-15 14:28:22 +0000752:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
753
754* pass it an Option instance (as returned by :func:`make_option`)
755
756* pass it any combination of positional and keyword arguments that are
Georg Brandl15a515f2009-09-17 22:11:49 +0000757 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
758 will create the Option instance for you
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760The other alternative is to pass a list of pre-constructed Option instances to
761the OptionParser constructor, as in::
762
763 option_list = [
764 make_option("-f", "--filename",
765 action="store", type="string", dest="filename"),
766 make_option("-q", "--quiet",
767 action="store_false", dest="verbose"),
768 ]
769 parser = OptionParser(option_list=option_list)
770
771(:func:`make_option` is a factory function for creating Option instances;
772currently it is an alias for the Option constructor. A future version of
773:mod:`optparse` may split Option into several classes, and :func:`make_option`
774will pick the right class to instantiate. Do not instantiate Option directly.)
775
776
777.. _optparse-defining-options:
778
779Defining options
780^^^^^^^^^^^^^^^^
781
782Each Option instance represents a set of synonymous command-line option strings,
783e.g. :option:`-f` and :option:`--file`. You can specify any number of short or
784long option strings, but you must specify at least one overall option string.
785
Georg Brandl15a515f2009-09-17 22:11:49 +0000786The canonical way to create an :class:`Option` instance is with the
787:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl116aa622007-08-15 14:28:22 +0000788
Georg Brandl15a515f2009-09-17 22:11:49 +0000789.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000790
Georg Brandl15a515f2009-09-17 22:11:49 +0000791 To define an option with only a short option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000792
Georg Brandl15a515f2009-09-17 22:11:49 +0000793 parser.add_option("-f", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000794
Georg Brandl15a515f2009-09-17 22:11:49 +0000795 And to define an option with only a long option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000796
Georg Brandl15a515f2009-09-17 22:11:49 +0000797 parser.add_option("--foo", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000798
Georg Brandl15a515f2009-09-17 22:11:49 +0000799 The keyword arguments define attributes of the new Option object. The most
800 important option attribute is :attr:`~Option.action`, and it largely
801 determines which other attributes are relevant or required. If you pass
802 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
803 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl116aa622007-08-15 14:28:22 +0000804
Georg Brandl15a515f2009-09-17 22:11:49 +0000805 An option's *action* determines what :mod:`optparse` does when it encounters
806 this option on the command-line. The standard option actions hard-coded into
807 :mod:`optparse` are:
Georg Brandl116aa622007-08-15 14:28:22 +0000808
Georg Brandl15a515f2009-09-17 22:11:49 +0000809 ``"store"``
810 store this option's argument (default)
Georg Brandl116aa622007-08-15 14:28:22 +0000811
Georg Brandl15a515f2009-09-17 22:11:49 +0000812 ``"store_const"``
813 store a constant value
Georg Brandl116aa622007-08-15 14:28:22 +0000814
Georg Brandl15a515f2009-09-17 22:11:49 +0000815 ``"store_true"``
816 store a true value
Georg Brandl116aa622007-08-15 14:28:22 +0000817
Georg Brandl15a515f2009-09-17 22:11:49 +0000818 ``"store_false"``
819 store a false value
Georg Brandl116aa622007-08-15 14:28:22 +0000820
Georg Brandl15a515f2009-09-17 22:11:49 +0000821 ``"append"``
822 append this option's argument to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000823
Georg Brandl15a515f2009-09-17 22:11:49 +0000824 ``"append_const"``
825 append a constant value to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000826
Georg Brandl15a515f2009-09-17 22:11:49 +0000827 ``"count"``
828 increment a counter by one
Georg Brandl116aa622007-08-15 14:28:22 +0000829
Georg Brandl15a515f2009-09-17 22:11:49 +0000830 ``"callback"``
831 call a specified function
Georg Brandl116aa622007-08-15 14:28:22 +0000832
Georg Brandl15a515f2009-09-17 22:11:49 +0000833 ``"help"``
834 print a usage message including all options and the documentation for them
Georg Brandl116aa622007-08-15 14:28:22 +0000835
Georg Brandl15a515f2009-09-17 22:11:49 +0000836 (If you don't supply an action, the default is ``"store"``. For this action,
837 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
838 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000839
840As you can see, most actions involve storing or updating a value somewhere.
841:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandl15a515f2009-09-17 22:11:49 +0000842``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl116aa622007-08-15 14:28:22 +0000843arguments (and various other values) are stored as attributes of this object,
Georg Brandl15a515f2009-09-17 22:11:49 +0000844according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000845
Georg Brandl15a515f2009-09-17 22:11:49 +0000846For example, when you call ::
Georg Brandl116aa622007-08-15 14:28:22 +0000847
848 parser.parse_args()
849
850one of the first things :mod:`optparse` does is create the ``options`` object::
851
852 options = Values()
853
Georg Brandl15a515f2009-09-17 22:11:49 +0000854If one of the options in this parser is defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +0000855
856 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
857
858and the command-line being parsed includes any of the following::
859
860 -ffoo
861 -f foo
862 --file=foo
863 --file foo
864
Georg Brandl15a515f2009-09-17 22:11:49 +0000865then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl116aa622007-08-15 14:28:22 +0000866
867 options.filename = "foo"
868
Georg Brandl15a515f2009-09-17 22:11:49 +0000869The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
870as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
871one that makes sense for *all* options.
872
873
874.. _optparse-option-attributes:
875
876Option attributes
877^^^^^^^^^^^^^^^^^
878
879The following option attributes may be passed as keyword arguments to
880:meth:`OptionParser.add_option`. If you pass an option attribute that is not
881relevant to a particular option, or fail to pass a required option attribute,
882:mod:`optparse` raises :exc:`OptionError`.
883
884.. attribute:: Option.action
885
886 (default: ``"store"``)
887
888 Determines :mod:`optparse`'s behaviour when this option is seen on the
889 command line; the available options are documented :ref:`here
890 <optparse-standard-option-actions>`.
891
892.. attribute:: Option.type
893
894 (default: ``"string"``)
895
896 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
897 the available option types are documented :ref:`here
898 <optparse-standard-option-types>`.
899
900.. attribute:: Option.dest
901
902 (default: derived from option strings)
903
904 If the option's action implies writing or modifying a value somewhere, this
905 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
906 attribute of the ``options`` object that :mod:`optparse` builds as it parses
907 the command line.
908
909.. attribute:: Option.default
910
911 The value to use for this option's destination if the option is not seen on
912 the command line. See also :meth:`OptionParser.set_defaults`.
913
914.. attribute:: Option.nargs
915
916 (default: 1)
917
918 How many arguments of type :attr:`~Option.type` should be consumed when this
919 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
920 :attr:`~Option.dest`.
921
922.. attribute:: Option.const
923
924 For actions that store a constant value, the constant value to store.
925
926.. attribute:: Option.choices
927
928 For options of type ``"choice"``, the list of strings the user may choose
929 from.
930
931.. attribute:: Option.callback
932
933 For options with action ``"callback"``, the callable to call when this option
934 is seen. See section :ref:`optparse-option-callbacks` for detail on the
935 arguments passed to the callable.
936
937.. attribute:: Option.callback_args
938 Option.callback_kwargs
939
940 Additional positional and keyword arguments to pass to ``callback`` after the
941 four standard callback arguments.
942
943.. attribute:: Option.help
944
945 Help text to print for this option when listing all available options after
946 the user supplies a :attr:`~Option.help` option (such as ``"--help"``). If
947 no help text is supplied, the option will be listed without help text. To
948 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
949
950.. attribute:: Option.metavar
951
952 (default: derived from option strings)
953
954 Stand-in for the option argument(s) to use when printing help text. See
955 section :ref:`optparse-tutorial` for an example.
Georg Brandl116aa622007-08-15 14:28:22 +0000956
957
958.. _optparse-standard-option-actions:
959
960Standard option actions
961^^^^^^^^^^^^^^^^^^^^^^^
962
963The various option actions all have slightly different requirements and effects.
964Most actions have several relevant option attributes which you may specify to
965guide :mod:`optparse`'s behaviour; a few have required attributes, which you
966must specify for any option using that action.
967
Georg Brandl15a515f2009-09-17 22:11:49 +0000968* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
969 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +0000970
971 The option must be followed by an argument, which is converted to a value
Georg Brandl15a515f2009-09-17 22:11:49 +0000972 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
973 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
974 command line; all will be converted according to :attr:`~Option.type` and
975 stored to :attr:`~Option.dest` as a tuple. See the
976 :ref:`optparse-standard-option-types` section.
Georg Brandl116aa622007-08-15 14:28:22 +0000977
Georg Brandl15a515f2009-09-17 22:11:49 +0000978 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
979 defaults to ``"choice"``.
Georg Brandl116aa622007-08-15 14:28:22 +0000980
Georg Brandl15a515f2009-09-17 22:11:49 +0000981 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl116aa622007-08-15 14:28:22 +0000982
Georg Brandl15a515f2009-09-17 22:11:49 +0000983 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
984 from the first long option string (e.g., ``"--foo-bar"`` implies
985 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
986 destination from the first short option string (e.g., ``"-f"`` implies ``f``).
Georg Brandl116aa622007-08-15 14:28:22 +0000987
988 Example::
989
990 parser.add_option("-f")
991 parser.add_option("-p", type="float", nargs=3, dest="point")
992
Georg Brandl15a515f2009-09-17 22:11:49 +0000993 As it parses the command line ::
Georg Brandl116aa622007-08-15 14:28:22 +0000994
995 -f foo.txt -p 1 -3.5 4 -fbar.txt
996
Georg Brandl15a515f2009-09-17 22:11:49 +0000997 :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +0000998
999 options.f = "foo.txt"
1000 options.point = (1.0, -3.5, 4.0)
1001 options.f = "bar.txt"
1002
Georg Brandl15a515f2009-09-17 22:11:49 +00001003* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1004 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001005
Georg Brandl15a515f2009-09-17 22:11:49 +00001006 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001007
1008 Example::
1009
1010 parser.add_option("-q", "--quiet",
1011 action="store_const", const=0, dest="verbose")
1012 parser.add_option("-v", "--verbose",
1013 action="store_const", const=1, dest="verbose")
1014 parser.add_option("--noisy",
1015 action="store_const", const=2, dest="verbose")
1016
1017 If ``"--noisy"`` is seen, :mod:`optparse` will set ::
1018
1019 options.verbose = 2
1020
Georg Brandl15a515f2009-09-17 22:11:49 +00001021* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001022
Georg Brandl15a515f2009-09-17 22:11:49 +00001023 A special case of ``"store_const"`` that stores a true value to
1024 :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001025
Georg Brandl15a515f2009-09-17 22:11:49 +00001026* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001027
Georg Brandl15a515f2009-09-17 22:11:49 +00001028 Like ``"store_true"``, but stores a false value.
Georg Brandl116aa622007-08-15 14:28:22 +00001029
1030 Example::
1031
1032 parser.add_option("--clobber", action="store_true", dest="clobber")
1033 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1034
Georg Brandl15a515f2009-09-17 22:11:49 +00001035* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1036 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001037
1038 The option must be followed by an argument, which is appended to the list in
Georg Brandl15a515f2009-09-17 22:11:49 +00001039 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1040 supplied, an empty list is automatically created when :mod:`optparse` first
1041 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1042 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1043 is appended to :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001044
Georg Brandl15a515f2009-09-17 22:11:49 +00001045 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1046 for the ``"store"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001047
1048 Example::
1049
1050 parser.add_option("-t", "--tracks", action="append", type="int")
1051
1052 If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
1053 of::
1054
1055 options.tracks = []
1056 options.tracks.append(int("3"))
1057
1058 If, a little later on, ``"--tracks=4"`` is seen, it does::
1059
1060 options.tracks.append(int("4"))
1061
Georg Brandl15a515f2009-09-17 22:11:49 +00001062* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1063 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001064
Georg Brandl15a515f2009-09-17 22:11:49 +00001065 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1066 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1067 ``None``, and an empty list is automatically created the first time the option
1068 is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +00001069
Georg Brandl15a515f2009-09-17 22:11:49 +00001070* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001071
Georg Brandl15a515f2009-09-17 22:11:49 +00001072 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1073 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1074 first time.
Georg Brandl116aa622007-08-15 14:28:22 +00001075
1076 Example::
1077
1078 parser.add_option("-v", action="count", dest="verbosity")
1079
1080 The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
1081 equivalent of::
1082
1083 options.verbosity = 0
1084 options.verbosity += 1
1085
1086 Every subsequent occurrence of ``"-v"`` results in ::
1087
1088 options.verbosity += 1
1089
Georg Brandl15a515f2009-09-17 22:11:49 +00001090* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1091 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1092 :attr:`~Option.callback_kwargs`]
Georg Brandl116aa622007-08-15 14:28:22 +00001093
Georg Brandl15a515f2009-09-17 22:11:49 +00001094 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001095
1096 func(option, opt_str, value, parser, *args, **kwargs)
1097
1098 See section :ref:`optparse-option-callbacks` for more detail.
1099
Georg Brandl15a515f2009-09-17 22:11:49 +00001100* ``"help"``
Georg Brandl116aa622007-08-15 14:28:22 +00001101
Georg Brandl15a515f2009-09-17 22:11:49 +00001102 Prints a complete help message for all the options in the current option
1103 parser. The help message is constructed from the ``usage`` string passed to
1104 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1105 option.
Georg Brandl116aa622007-08-15 14:28:22 +00001106
Georg Brandl15a515f2009-09-17 22:11:49 +00001107 If no :attr:`~Option.help` string is supplied for an option, it will still be
1108 listed in the help message. To omit an option entirely, use the special value
1109 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl116aa622007-08-15 14:28:22 +00001110
Georg Brandl15a515f2009-09-17 22:11:49 +00001111 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1112 OptionParsers, so you do not normally need to create one.
Georg Brandl116aa622007-08-15 14:28:22 +00001113
1114 Example::
1115
1116 from optparse import OptionParser, SUPPRESS_HELP
1117
Georg Brandlee8783d2009-09-16 16:00:31 +00001118 # usually, a help option is added automatically, but that can
1119 # be suppressed using the add_help_option argument
1120 parser = OptionParser(add_help_option=False)
1121
1122 parser.add_option("-h", "--help", action="help")
Georg Brandl116aa622007-08-15 14:28:22 +00001123 parser.add_option("-v", action="store_true", dest="verbose",
1124 help="Be moderately verbose")
1125 parser.add_option("--file", dest="filename",
Georg Brandlee8783d2009-09-16 16:00:31 +00001126 help="Input file to read data from")
Georg Brandl116aa622007-08-15 14:28:22 +00001127 parser.add_option("--secret", help=SUPPRESS_HELP)
1128
Georg Brandl15a515f2009-09-17 22:11:49 +00001129 If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line,
1130 it will print something like the following help message to stdout (assuming
Georg Brandl116aa622007-08-15 14:28:22 +00001131 ``sys.argv[0]`` is ``"foo.py"``)::
1132
1133 usage: foo.py [options]
1134
1135 options:
1136 -h, --help Show this help message and exit
1137 -v Be moderately verbose
1138 --file=FILENAME Input file to read data from
1139
1140 After printing the help message, :mod:`optparse` terminates your process with
1141 ``sys.exit(0)``.
1142
Georg Brandl15a515f2009-09-17 22:11:49 +00001143* ``"version"``
Georg Brandl116aa622007-08-15 14:28:22 +00001144
Georg Brandl15a515f2009-09-17 22:11:49 +00001145 Prints the version number supplied to the OptionParser to stdout and exits.
1146 The version number is actually formatted and printed by the
1147 ``print_version()`` method of OptionParser. Generally only relevant if the
1148 ``version`` argument is supplied to the OptionParser constructor. As with
1149 :attr:`~Option.help` options, you will rarely create ``version`` options,
1150 since :mod:`optparse` automatically adds them when needed.
Georg Brandl116aa622007-08-15 14:28:22 +00001151
1152
1153.. _optparse-standard-option-types:
1154
1155Standard option types
1156^^^^^^^^^^^^^^^^^^^^^
1157
Georg Brandl15a515f2009-09-17 22:11:49 +00001158:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1159``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1160option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +00001161
1162Arguments to string options are not checked or converted in any way: the text on
1163the command line is stored in the destination (or passed to the callback) as-is.
1164
Georg Brandl15a515f2009-09-17 22:11:49 +00001165Integer arguments (type ``"int"``) are parsed as follows:
Georg Brandl116aa622007-08-15 14:28:22 +00001166
1167* if the number starts with ``0x``, it is parsed as a hexadecimal number
1168
1169* if the number starts with ``0``, it is parsed as an octal number
1170
Georg Brandl9afde1c2007-11-01 20:32:30 +00001171* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl116aa622007-08-15 14:28:22 +00001172
1173* otherwise, the number is parsed as a decimal number
1174
1175
Georg Brandl15a515f2009-09-17 22:11:49 +00001176The conversion is done by calling :func:`int` with the appropriate base (2, 8,
117710, or 16). If this fails, so will :mod:`optparse`, although with a more useful
Georg Brandl5c106642007-11-29 17:41:05 +00001178error message.
Georg Brandl116aa622007-08-15 14:28:22 +00001179
Georg Brandl15a515f2009-09-17 22:11:49 +00001180``"float"`` and ``"complex"`` option arguments are converted directly with
1181:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl116aa622007-08-15 14:28:22 +00001182
Georg Brandl15a515f2009-09-17 22:11:49 +00001183``"choice"`` options are a subtype of ``"string"`` options. The
1184:attr:`~Option.choices`` option attribute (a sequence of strings) defines the
1185set of allowed option arguments. :func:`optparse.check_choice` compares
1186user-supplied option arguments against this master list and raises
1187:exc:`OptionValueError` if an invalid string is given.
Georg Brandl116aa622007-08-15 14:28:22 +00001188
1189
1190.. _optparse-parsing-arguments:
1191
1192Parsing arguments
1193^^^^^^^^^^^^^^^^^
1194
1195The whole point of creating and populating an OptionParser is to call its
1196:meth:`parse_args` method::
1197
1198 (options, args) = parser.parse_args(args=None, values=None)
1199
1200where the input parameters are
1201
1202``args``
1203 the list of arguments to process (default: ``sys.argv[1:]``)
1204
1205``values``
Georg Brandla6053b42009-09-01 08:11:14 +00001206 object to store option arguments in (default: a new instance of
1207 :class:`optparse.Values`)
Georg Brandl116aa622007-08-15 14:28:22 +00001208
1209and the return values are
1210
1211``options``
Georg Brandla6053b42009-09-01 08:11:14 +00001212 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl116aa622007-08-15 14:28:22 +00001213 instance created by :mod:`optparse`
1214
1215``args``
1216 the leftover positional arguments after all options have been processed
1217
1218The most common usage is to supply neither keyword argument. If you supply
Georg Brandl15a515f2009-09-17 22:11:49 +00001219``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl116aa622007-08-15 14:28:22 +00001220for every option argument stored to an option destination) and returned by
1221:meth:`parse_args`.
1222
1223If :meth:`parse_args` encounters any errors in the argument list, it calls the
1224OptionParser's :meth:`error` method with an appropriate end-user error message.
1225This ultimately terminates your process with an exit status of 2 (the
1226traditional Unix exit status for command-line errors).
1227
1228
1229.. _optparse-querying-manipulating-option-parser:
1230
1231Querying and manipulating your option parser
1232^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1233
Georg Brandl15a515f2009-09-17 22:11:49 +00001234The default behavior of the option parser can be customized slightly, and you
1235can also poke around your option parser and see what's there. OptionParser
1236provides several methods to help you out:
Georg Brandl116aa622007-08-15 14:28:22 +00001237
Georg Brandl15a515f2009-09-17 22:11:49 +00001238.. method:: OptionParser.disable_interspersed_args()
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001239
Georg Brandl15a515f2009-09-17 22:11:49 +00001240 Set parsing to stop on the first non-option. For example, if ``"-a"`` and
1241 ``"-b"`` are both simple options that take no arguments, :mod:`optparse`
1242 normally accepts this syntax::
Georg Brandl116aa622007-08-15 14:28:22 +00001243
Georg Brandl15a515f2009-09-17 22:11:49 +00001244 prog -a arg1 -b arg2
1245
1246 and treats it as equivalent to ::
1247
1248 prog -a -b arg1 arg2
1249
1250 To disable this feature, call :meth:`disable_interspersed_args`. This
1251 restores traditional Unix syntax, where option parsing stops with the first
1252 non-option argument.
1253
1254 Use this if you have a command processor which runs another command which has
1255 options of its own and you want to make sure these options don't get
1256 confused. For example, each command might have a different set of options.
1257
1258.. method:: OptionParser.enable_interspersed_args()
1259
1260 Set parsing to not stop on the first non-option, allowing interspersing
1261 switches with command arguments. This is the default behavior.
1262
1263.. method:: OptionParser.get_option(opt_str)
1264
1265 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl116aa622007-08-15 14:28:22 +00001266 no options have that option string.
1267
Georg Brandl15a515f2009-09-17 22:11:49 +00001268.. method:: OptionParser.has_option(opt_str)
1269
1270 Return true if the OptionParser has an option with option string *opt_str*
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001271 (e.g., ``"-q"`` or ``"--verbose"``).
1272
Georg Brandl15a515f2009-09-17 22:11:49 +00001273.. method:: OptionParser.remove_option(opt_str)
1274
1275 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1276 option is removed. If that option provided any other option strings, all of
1277 those option strings become invalid. If *opt_str* does not occur in any
1278 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001279
1280
1281.. _optparse-conflicts-between-options:
1282
1283Conflicts between options
1284^^^^^^^^^^^^^^^^^^^^^^^^^
1285
1286If you're not careful, it's easy to define options with conflicting option
1287strings::
1288
1289 parser.add_option("-n", "--dry-run", ...)
1290 [...]
1291 parser.add_option("-n", "--noisy", ...)
1292
1293(This is particularly true if you've defined your own OptionParser subclass with
1294some standard options.)
1295
1296Every time you add an option, :mod:`optparse` checks for conflicts with existing
1297options. If it finds any, it invokes the current conflict-handling mechanism.
1298You can set the conflict-handling mechanism either in the constructor::
1299
1300 parser = OptionParser(..., conflict_handler=handler)
1301
1302or with a separate call::
1303
1304 parser.set_conflict_handler(handler)
1305
1306The available conflict handlers are:
1307
Georg Brandl15a515f2009-09-17 22:11:49 +00001308 ``"error"`` (default)
1309 assume option conflicts are a programming error and raise
1310 :exc:`OptionConflictError`
Georg Brandl116aa622007-08-15 14:28:22 +00001311
Georg Brandl15a515f2009-09-17 22:11:49 +00001312 ``"resolve"``
Georg Brandl116aa622007-08-15 14:28:22 +00001313 resolve option conflicts intelligently (see below)
1314
1315
Benjamin Petersone5384b02008-10-04 22:00:42 +00001316As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl116aa622007-08-15 14:28:22 +00001317intelligently and add conflicting options to it::
1318
1319 parser = OptionParser(conflict_handler="resolve")
1320 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1321 parser.add_option("-n", "--noisy", ..., help="be noisy")
1322
1323At this point, :mod:`optparse` detects that a previously-added option is already
1324using the ``"-n"`` option string. Since ``conflict_handler`` is ``"resolve"``,
1325it resolves the situation by removing ``"-n"`` from the earlier option's list of
1326option strings. Now ``"--dry-run"`` is the only way for the user to activate
1327that option. If the user asks for help, the help message will reflect that::
1328
1329 options:
1330 --dry-run do no harm
1331 [...]
1332 -n, --noisy be noisy
1333
1334It's possible to whittle away the option strings for a previously-added option
1335until there are none left, and the user has no way of invoking that option from
1336the command-line. In that case, :mod:`optparse` removes that option completely,
1337so it doesn't show up in help text or anywhere else. Carrying on with our
1338existing OptionParser::
1339
1340 parser.add_option("--dry-run", ..., help="new dry-run option")
1341
1342At this point, the original :option:`-n/--dry-run` option is no longer
1343accessible, so :mod:`optparse` removes it, leaving this help text::
1344
1345 options:
1346 [...]
1347 -n, --noisy be noisy
1348 --dry-run new dry-run option
1349
1350
1351.. _optparse-cleanup:
1352
1353Cleanup
1354^^^^^^^
1355
1356OptionParser instances have several cyclic references. This should not be a
1357problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandl15a515f2009-09-17 22:11:49 +00001358references explicitly by calling :meth:`~OptionParser.destroy` on your
1359OptionParser once you are done with it. This is particularly useful in
1360long-running applications where large object graphs are reachable from your
1361OptionParser.
Georg Brandl116aa622007-08-15 14:28:22 +00001362
1363
1364.. _optparse-other-methods:
1365
1366Other methods
1367^^^^^^^^^^^^^
1368
1369OptionParser supports several other public methods:
1370
Georg Brandl15a515f2009-09-17 22:11:49 +00001371.. method:: OptionParser.set_usage(usage)
Georg Brandl116aa622007-08-15 14:28:22 +00001372
Georg Brandl15a515f2009-09-17 22:11:49 +00001373 Set the usage string according to the rules described above for the ``usage``
1374 constructor keyword argument. Passing ``None`` sets the default usage
1375 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl116aa622007-08-15 14:28:22 +00001376
Georg Brandl15a515f2009-09-17 22:11:49 +00001377.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +00001378
Georg Brandl15a515f2009-09-17 22:11:49 +00001379 Set default values for several option destinations at once. Using
1380 :meth:`set_defaults` is the preferred way to set default values for options,
1381 since multiple options can share the same destination. For example, if
1382 several "mode" options all set the same destination, any one of them can set
1383 the default, and the last one wins::
Georg Brandl116aa622007-08-15 14:28:22 +00001384
Georg Brandl15a515f2009-09-17 22:11:49 +00001385 parser.add_option("--advanced", action="store_const",
1386 dest="mode", const="advanced",
1387 default="novice") # overridden below
1388 parser.add_option("--novice", action="store_const",
1389 dest="mode", const="novice",
1390 default="advanced") # overrides above setting
Georg Brandl116aa622007-08-15 14:28:22 +00001391
Georg Brandl15a515f2009-09-17 22:11:49 +00001392 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl116aa622007-08-15 14:28:22 +00001393
Georg Brandl15a515f2009-09-17 22:11:49 +00001394 parser.set_defaults(mode="advanced")
1395 parser.add_option("--advanced", action="store_const",
1396 dest="mode", const="advanced")
1397 parser.add_option("--novice", action="store_const",
1398 dest="mode", const="novice")
Georg Brandl116aa622007-08-15 14:28:22 +00001399
Georg Brandl116aa622007-08-15 14:28:22 +00001400
1401.. _optparse-option-callbacks:
1402
1403Option Callbacks
1404----------------
1405
1406When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1407needs, you have two choices: extend :mod:`optparse` or define a callback option.
1408Extending :mod:`optparse` is more general, but overkill for a lot of simple
1409cases. Quite often a simple callback is all you need.
1410
1411There are two steps to defining a callback option:
1412
Georg Brandl15a515f2009-09-17 22:11:49 +00001413* define the option itself using the ``"callback"`` action
Georg Brandl116aa622007-08-15 14:28:22 +00001414
1415* write the callback; this is a function (or method) that takes at least four
1416 arguments, as described below
1417
1418
1419.. _optparse-defining-callback-option:
1420
1421Defining a callback option
1422^^^^^^^^^^^^^^^^^^^^^^^^^^
1423
1424As always, the easiest way to define a callback option is by using the
Georg Brandl15a515f2009-09-17 22:11:49 +00001425:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1426only option attribute you must specify is ``callback``, the function to call::
Georg Brandl116aa622007-08-15 14:28:22 +00001427
1428 parser.add_option("-c", action="callback", callback=my_callback)
1429
1430``callback`` is a function (or other callable object), so you must have already
1431defined ``my_callback()`` when you create this callback option. In this simple
1432case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,
1433which usually means that the option takes no arguments---the mere presence of
1434:option:`-c` on the command-line is all it needs to know. In some
1435circumstances, though, you might want your callback to consume an arbitrary
1436number of command-line arguments. This is where writing callbacks gets tricky;
1437it's covered later in this section.
1438
1439:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandl15a515f2009-09-17 22:11:49 +00001440will only pass additional arguments if you specify them via
1441:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1442minimal callback function signature is::
Georg Brandl116aa622007-08-15 14:28:22 +00001443
1444 def my_callback(option, opt, value, parser):
1445
1446The four arguments to a callback are described below.
1447
1448There are several other option attributes that you can supply when you define a
1449callback option:
1450
Georg Brandl15a515f2009-09-17 22:11:49 +00001451:attr:`~Option.type`
1452 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1453 instructs :mod:`optparse` to consume one argument and convert it to
1454 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1455 though, :mod:`optparse` passes it to your callback function.
Georg Brandl116aa622007-08-15 14:28:22 +00001456
Georg Brandl15a515f2009-09-17 22:11:49 +00001457:attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001458 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001459 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1460 :attr:`~Option.type`. It then passes a tuple of converted values to your
1461 callback.
Georg Brandl116aa622007-08-15 14:28:22 +00001462
Georg Brandl15a515f2009-09-17 22:11:49 +00001463:attr:`~Option.callback_args`
Georg Brandl116aa622007-08-15 14:28:22 +00001464 a tuple of extra positional arguments to pass to the callback
1465
Georg Brandl15a515f2009-09-17 22:11:49 +00001466:attr:`~Option.callback_kwargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001467 a dictionary of extra keyword arguments to pass to the callback
1468
1469
1470.. _optparse-how-callbacks-called:
1471
1472How callbacks are called
1473^^^^^^^^^^^^^^^^^^^^^^^^
1474
1475All callbacks are called as follows::
1476
1477 func(option, opt_str, value, parser, *args, **kwargs)
1478
1479where
1480
1481``option``
1482 is the Option instance that's calling the callback
1483
1484``opt_str``
1485 is the option string seen on the command-line that's triggering the callback.
Georg Brandl15a515f2009-09-17 22:11:49 +00001486 (If an abbreviated long option was used, ``opt_str`` will be the full,
1487 canonical option string---e.g. if the user puts ``"--foo"`` on the
1488 command-line as an abbreviation for ``"--foobar"``, then ``opt_str`` will be
1489 ``"--foobar"``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001490
1491``value``
1492 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001493 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1494 the type implied by the option's type. If :attr:`~Option.type` for this option is
1495 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001496 > 1, ``value`` will be a tuple of values of the appropriate type.
1497
1498``parser``
Georg Brandl15a515f2009-09-17 22:11:49 +00001499 is the OptionParser instance driving the whole thing, mainly useful because
1500 you can access some other interesting data through its instance attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001501
1502 ``parser.largs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001503 the current list of leftover arguments, ie. arguments that have been
1504 consumed but are neither options nor option arguments. Feel free to modify
1505 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1506 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001507
1508 ``parser.rargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001509 the current list of remaining arguments, ie. with ``opt_str`` and
1510 ``value`` (if applicable) removed, and only the arguments following them
1511 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1512 arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001513
1514 ``parser.values``
1515 the object where option values are by default stored (an instance of
Georg Brandl15a515f2009-09-17 22:11:49 +00001516 optparse.OptionValues). This lets callbacks use the same mechanism as the
1517 rest of :mod:`optparse` for storing option values; you don't need to mess
1518 around with globals or closures. You can also access or modify the
1519 value(s) of any options already encountered on the command-line.
Georg Brandl116aa622007-08-15 14:28:22 +00001520
1521``args``
Georg Brandl15a515f2009-09-17 22:11:49 +00001522 is a tuple of arbitrary positional arguments supplied via the
1523 :attr:`~Option.callback_args` option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001524
1525``kwargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001526 is a dictionary of arbitrary keyword arguments supplied via
1527 :attr:`~Option.callback_kwargs`.
Georg Brandl116aa622007-08-15 14:28:22 +00001528
1529
1530.. _optparse-raising-errors-in-callback:
1531
1532Raising errors in a callback
1533^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1534
Georg Brandl15a515f2009-09-17 22:11:49 +00001535The callback function should raise :exc:`OptionValueError` if there are any
1536problems with the option or its argument(s). :mod:`optparse` catches this and
1537terminates the program, printing the error message you supply to stderr. Your
1538message should be clear, concise, accurate, and mention the option at fault.
1539Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl116aa622007-08-15 14:28:22 +00001540
1541
1542.. _optparse-callback-example-1:
1543
1544Callback example 1: trivial callback
1545^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1546
1547Here's an example of a callback option that takes no arguments, and simply
1548records that the option was seen::
1549
1550 def record_foo_seen(option, opt_str, value, parser):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001551 parser.values.saw_foo = True
Georg Brandl116aa622007-08-15 14:28:22 +00001552
1553 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1554
Georg Brandl15a515f2009-09-17 22:11:49 +00001555Of course, you could do that with the ``"store_true"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001556
1557
1558.. _optparse-callback-example-2:
1559
1560Callback example 2: check option order
1561^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1562
1563Here's a slightly more interesting example: record the fact that ``"-a"`` is
1564seen, but blow up if it comes after ``"-b"`` in the command-line. ::
1565
1566 def check_order(option, opt_str, value, parser):
1567 if parser.values.b:
1568 raise OptionValueError("can't use -a after -b")
1569 parser.values.a = 1
1570 [...]
1571 parser.add_option("-a", action="callback", callback=check_order)
1572 parser.add_option("-b", action="store_true", dest="b")
1573
1574
1575.. _optparse-callback-example-3:
1576
1577Callback example 3: check option order (generalized)
1578^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1579
1580If you want to re-use this callback for several similar options (set a flag, but
1581blow up if ``"-b"`` has already been seen), it needs a bit of work: the error
1582message and the flag that it sets must be generalized. ::
1583
1584 def check_order(option, opt_str, value, parser):
1585 if parser.values.b:
1586 raise OptionValueError("can't use %s after -b" % opt_str)
1587 setattr(parser.values, option.dest, 1)
1588 [...]
1589 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1590 parser.add_option("-b", action="store_true", dest="b")
1591 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1592
1593
1594.. _optparse-callback-example-4:
1595
1596Callback example 4: check arbitrary condition
1597^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1598
1599Of course, you could put any condition in there---you're not limited to checking
1600the values of already-defined options. For example, if you have options that
1601should not be called when the moon is full, all you have to do is this::
1602
1603 def check_moon(option, opt_str, value, parser):
1604 if is_moon_full():
1605 raise OptionValueError("%s option invalid when moon is full"
1606 % opt_str)
1607 setattr(parser.values, option.dest, 1)
1608 [...]
1609 parser.add_option("--foo",
1610 action="callback", callback=check_moon, dest="foo")
1611
1612(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1613
1614
1615.. _optparse-callback-example-5:
1616
1617Callback example 5: fixed arguments
1618^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1619
1620Things get slightly more interesting when you define callback options that take
1621a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandl15a515f2009-09-17 22:11:49 +00001622is similar to defining a ``"store"`` or ``"append"`` option: if you define
1623:attr:`~Option.type`, then the option takes one argument that must be
1624convertible to that type; if you further define :attr:`~Option.nargs`, then the
1625option takes :attr:`~Option.nargs` arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001626
Georg Brandl15a515f2009-09-17 22:11:49 +00001627Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl116aa622007-08-15 14:28:22 +00001628
1629 def store_value(option, opt_str, value, parser):
1630 setattr(parser.values, option.dest, value)
1631 [...]
1632 parser.add_option("--foo",
1633 action="callback", callback=store_value,
1634 type="int", nargs=3, dest="foo")
1635
1636Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1637them to integers for you; all you have to do is store them. (Or whatever;
1638obviously you don't need a callback for this example.)
1639
1640
1641.. _optparse-callback-example-6:
1642
1643Callback example 6: variable arguments
1644^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1645
1646Things get hairy when you want an option to take a variable number of arguments.
1647For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1648built-in capabilities for it. And you have to deal with certain intricacies of
1649conventional Unix command-line parsing that :mod:`optparse` normally handles for
1650you. In particular, callbacks should implement the conventional rules for bare
1651``"--"`` and ``"-"`` arguments:
1652
1653* either ``"--"`` or ``"-"`` can be option arguments
1654
1655* bare ``"--"`` (if not the argument to some option): halt command-line
1656 processing and discard the ``"--"``
1657
1658* bare ``"-"`` (if not the argument to some option): halt command-line
1659 processing but keep the ``"-"`` (append it to ``parser.largs``)
1660
1661If you want an option that takes a variable number of arguments, there are
1662several subtle, tricky issues to worry about. The exact implementation you
1663choose will be based on which trade-offs you're willing to make for your
1664application (which is why :mod:`optparse` doesn't support this sort of thing
1665directly).
1666
1667Nevertheless, here's a stab at a callback for an option with variable
1668arguments::
1669
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001670 def vararg_callback(option, opt_str, value, parser):
1671 assert value is None
1672 value = []
Georg Brandl116aa622007-08-15 14:28:22 +00001673
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001674 def floatable(str):
1675 try:
1676 float(str)
1677 return True
1678 except ValueError:
1679 return False
Georg Brandl116aa622007-08-15 14:28:22 +00001680
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001681 for arg in parser.rargs:
1682 # stop on --foo like options
1683 if arg[:2] == "--" and len(arg) > 2:
1684 break
1685 # stop on -a, but not on -3 or -3.0
1686 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1687 break
1688 value.append(arg)
1689
1690 del parser.rargs[:len(value)]
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001691 setattr(parser.values, option.dest, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001692
1693 [...]
Benjamin Petersonae5360b2008-09-08 23:05:23 +00001694 parser.add_option("-c", "--callback", dest="vararg_attr",
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001695 action="callback", callback=vararg_callback)
Georg Brandl116aa622007-08-15 14:28:22 +00001696
Georg Brandl116aa622007-08-15 14:28:22 +00001697
1698.. _optparse-extending-optparse:
1699
1700Extending :mod:`optparse`
1701-------------------------
1702
1703Since the two major controlling factors in how :mod:`optparse` interprets
1704command-line options are the action and type of each option, the most likely
1705direction of extension is to add new actions and new types.
1706
1707
1708.. _optparse-adding-new-types:
1709
1710Adding new types
1711^^^^^^^^^^^^^^^^
1712
1713To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandl15a515f2009-09-17 22:11:49 +00001714:class:`Option` class. This class has a couple of attributes that define
1715:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl116aa622007-08-15 14:28:22 +00001716
Georg Brandl15a515f2009-09-17 22:11:49 +00001717.. attribute:: Option.TYPES
Georg Brandl116aa622007-08-15 14:28:22 +00001718
Georg Brandl15a515f2009-09-17 22:11:49 +00001719 A tuple of type names; in your subclass, simply define a new tuple
1720 :attr:`TYPES` that builds on the standard one.
Georg Brandl116aa622007-08-15 14:28:22 +00001721
Georg Brandl15a515f2009-09-17 22:11:49 +00001722.. attribute:: Option.TYPE_CHECKER
Georg Brandl116aa622007-08-15 14:28:22 +00001723
Georg Brandl15a515f2009-09-17 22:11:49 +00001724 A dictionary mapping type names to type-checking functions. A type-checking
1725 function has the following signature::
Georg Brandl116aa622007-08-15 14:28:22 +00001726
Georg Brandl15a515f2009-09-17 22:11:49 +00001727 def check_mytype(option, opt, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001728
Georg Brandl15a515f2009-09-17 22:11:49 +00001729 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1730 (e.g., ``"-f"``), and ``value`` is the string from the command line that must
1731 be checked and converted to your desired type. ``check_mytype()`` should
1732 return an object of the hypothetical type ``mytype``. The value returned by
1733 a type-checking function will wind up in the OptionValues instance returned
1734 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1735 ``value`` parameter.
1736
1737 Your type-checking function should raise :exc:`OptionValueError` if it
1738 encounters any problems. :exc:`OptionValueError` takes a single string
1739 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1740 method, which in turn prepends the program name and the string ``"error:"``
1741 and prints everything to stderr before terminating the process.
1742
1743Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl116aa622007-08-15 14:28:22 +00001744parse Python-style complex numbers on the command line. (This is even sillier
1745than it used to be, because :mod:`optparse` 1.3 added built-in support for
1746complex numbers, but never mind.)
1747
1748First, the necessary imports::
1749
1750 from copy import copy
1751 from optparse import Option, OptionValueError
1752
1753You need to define your type-checker first, since it's referred to later (in the
Georg Brandl15a515f2009-09-17 22:11:49 +00001754:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl116aa622007-08-15 14:28:22 +00001755
1756 def check_complex(option, opt, value):
1757 try:
1758 return complex(value)
1759 except ValueError:
1760 raise OptionValueError(
1761 "option %s: invalid complex value: %r" % (opt, value))
1762
1763Finally, the Option subclass::
1764
1765 class MyOption (Option):
1766 TYPES = Option.TYPES + ("complex",)
1767 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1768 TYPE_CHECKER["complex"] = check_complex
1769
1770(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandl15a515f2009-09-17 22:11:49 +00001771up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1772Option class. This being Python, nothing stops you from doing that except good
1773manners and common sense.)
Georg Brandl116aa622007-08-15 14:28:22 +00001774
1775That's it! Now you can write a script that uses the new option type just like
1776any other :mod:`optparse`\ -based script, except you have to instruct your
1777OptionParser to use MyOption instead of Option::
1778
1779 parser = OptionParser(option_class=MyOption)
1780 parser.add_option("-c", type="complex")
1781
1782Alternately, you can build your own option list and pass it to OptionParser; if
1783you don't use :meth:`add_option` in the above way, you don't need to tell
1784OptionParser which option class to use::
1785
1786 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1787 parser = OptionParser(option_list=option_list)
1788
1789
1790.. _optparse-adding-new-actions:
1791
1792Adding new actions
1793^^^^^^^^^^^^^^^^^^
1794
1795Adding new actions is a bit trickier, because you have to understand that
1796:mod:`optparse` has a couple of classifications for actions:
1797
1798"store" actions
1799 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandl15a515f2009-09-17 22:11:49 +00001800 current OptionValues instance; these options require a :attr:`~Option.dest`
1801 attribute to be supplied to the Option constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001802
1803"typed" actions
Georg Brandl15a515f2009-09-17 22:11:49 +00001804 actions that take a value from the command line and expect it to be of a
1805 certain type; or rather, a string that can be converted to a certain type.
1806 These options require a :attr:`~Option.type` attribute to the Option
1807 constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001808
Georg Brandl15a515f2009-09-17 22:11:49 +00001809These are overlapping sets: some default "store" actions are ``"store"``,
1810``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1811actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001812
1813When you add an action, you need to categorize it by listing it in at least one
1814of the following class attributes of Option (all are lists of strings):
1815
Georg Brandl15a515f2009-09-17 22:11:49 +00001816.. attribute:: Option.ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001817
Georg Brandl15a515f2009-09-17 22:11:49 +00001818 All actions must be listed in ACTIONS.
Georg Brandl116aa622007-08-15 14:28:22 +00001819
Georg Brandl15a515f2009-09-17 22:11:49 +00001820.. attribute:: Option.STORE_ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001821
Georg Brandl15a515f2009-09-17 22:11:49 +00001822 "store" actions are additionally listed here.
1823
1824.. attribute:: Option.TYPED_ACTIONS
1825
1826 "typed" actions are additionally listed here.
1827
1828.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1829
1830 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl116aa622007-08-15 14:28:22 +00001831 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001832 assigns the default type, ``"string"``, to options with no explicit type
1833 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001834
1835In order to actually implement your new action, you must override Option's
1836:meth:`take_action` method and add a case that recognizes your action.
1837
Georg Brandl15a515f2009-09-17 22:11:49 +00001838For example, let's add an ``"extend"`` action. This is similar to the standard
1839``"append"`` action, but instead of taking a single value from the command-line
1840and appending it to an existing list, ``"extend"`` will take multiple values in
1841a single comma-delimited string, and extend an existing list with them. That
1842is, if ``"--names"`` is an ``"extend"`` option of type ``"string"``, the command
1843line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001844
1845 --names=foo,bar --names blah --names ding,dong
1846
1847would result in a list ::
1848
1849 ["foo", "bar", "blah", "ding", "dong"]
1850
1851Again we define a subclass of Option::
1852
1853 class MyOption (Option):
1854
1855 ACTIONS = Option.ACTIONS + ("extend",)
1856 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1857 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1858 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1859
1860 def take_action(self, action, dest, opt, value, values, parser):
1861 if action == "extend":
1862 lvalue = value.split(",")
1863 values.ensure_value(dest, []).extend(lvalue)
1864 else:
1865 Option.take_action(
1866 self, action, dest, opt, value, values, parser)
1867
1868Features of note:
1869
Georg Brandl15a515f2009-09-17 22:11:49 +00001870* ``"extend"`` both expects a value on the command-line and stores that value
1871 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1872 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001873
Georg Brandl15a515f2009-09-17 22:11:49 +00001874* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1875 ``"extend"`` actions, we put the ``"extend"`` action in
1876 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001877
1878* :meth:`MyOption.take_action` implements just this one new action, and passes
1879 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001880 actions.
Georg Brandl116aa622007-08-15 14:28:22 +00001881
Georg Brandl15a515f2009-09-17 22:11:49 +00001882* ``values`` is an instance of the optparse_parser.Values class, which provides
1883 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1884 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001885
1886 values.ensure_value(attr, value)
1887
1888 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandl15a515f2009-09-17 22:11:49 +00001889 ensure_value() first sets it to ``value``, and then returns 'value. This is
1890 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
1891 of which accumulate data in a variable and expect that variable to be of a
1892 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl116aa622007-08-15 14:28:22 +00001893 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandl15a515f2009-09-17 22:11:49 +00001894 about setting a default value for the option destinations in question; they
1895 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl116aa622007-08-15 14:28:22 +00001896 getting it right when it's needed.