blob: 9527d35680591ed1f2aa3c60713c320383e16ac3 [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
Benjamin Peterson1baf4652009-12-31 03:11:23 +0000156 help at it either.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158For example, consider this hypothetical command-line::
159
160 prog -v --report /tmp/report.txt foo bar
161
162``"-v"`` and ``"--report"`` are both options. Assuming that :option:`--report`
163takes one argument, ``"/tmp/report.txt"`` is an option argument. ``"foo"`` and
164``"bar"`` are positional arguments.
165
166
167.. _optparse-what-options-for:
168
169What are options for?
170^^^^^^^^^^^^^^^^^^^^^
171
172Options are used to provide extra information to tune or customize the execution
173of a program. In case it wasn't clear, options are usually *optional*. A
174program should be able to run just fine with no options whatsoever. (Pick a
175random program from the Unix or GNU toolsets. Can it run without any options at
176all and still make sense? The main exceptions are ``find``, ``tar``, and
177``dd``\ ---all of which are mutant oddballs that have been rightly criticized
178for their non-standard syntax and confusing interfaces.)
179
180Lots of people want their programs to have "required options". Think about it.
181If it's required, then it's *not optional*! If there is a piece of information
182that your program absolutely requires in order to run successfully, that's what
183positional arguments are for.
184
185As an example of good command-line interface design, consider the humble ``cp``
186utility, for copying files. It doesn't make much sense to try to copy files
187without supplying a destination and at least one source. Hence, ``cp`` fails if
188you run it with no arguments. However, it has a flexible, useful syntax that
189does not require any options at all::
190
191 cp SOURCE DEST
192 cp SOURCE ... DEST-DIR
193
194You can get pretty far with just that. Most ``cp`` implementations provide a
195bunch of options to tweak exactly how the files are copied: you can preserve
196mode and modification time, avoid following symlinks, ask before clobbering
197existing files, etc. But none of this distracts from the core mission of
198``cp``, which is to copy either one file to another, or several files to another
199directory.
200
201
202.. _optparse-what-positional-arguments-for:
203
204What are positional arguments for?
205^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
206
207Positional arguments are for those pieces of information that your program
208absolutely, positively requires to run.
209
210A good user interface should have as few absolute requirements as possible. If
211your program requires 17 distinct pieces of information in order to run
212successfully, it doesn't much matter *how* you get that information from the
213user---most people will give up and walk away before they successfully run the
214program. This applies whether the user interface is a command-line, a
215configuration file, or a GUI: if you make that many demands on your users, most
216of them will simply give up.
217
218In short, try to minimize the amount of information that users are absolutely
219required to supply---use sensible defaults whenever possible. Of course, you
220also want to make your programs reasonably flexible. That's what options are
221for. Again, it doesn't matter if they are entries in a config file, widgets in
222the "Preferences" dialog of a GUI, or command-line options---the more options
223you implement, the more flexible your program is, and the more complicated its
224implementation becomes. Too much flexibility has drawbacks as well, of course;
225too many options can overwhelm users and make your code much harder to maintain.
226
Georg Brandl116aa622007-08-15 14:28:22 +0000227
228.. _optparse-tutorial:
229
230Tutorial
231--------
232
233While :mod:`optparse` is quite flexible and powerful, it's also straightforward
234to use in most cases. This section covers the code patterns that are common to
235any :mod:`optparse`\ -based program.
236
237First, you need to import the OptionParser class; then, early in the main
238program, create an OptionParser instance::
239
240 from optparse import OptionParser
241 [...]
242 parser = OptionParser()
243
244Then you can start defining options. The basic syntax is::
245
246 parser.add_option(opt_str, ...,
247 attr=value, ...)
248
249Each option has one or more option strings, such as ``"-f"`` or ``"--file"``,
250and several option attributes that tell :mod:`optparse` what to expect and what
251to do when it encounters that option on the command line.
252
253Typically, each option will have one short option string and one long option
254string, e.g.::
255
256 parser.add_option("-f", "--file", ...)
257
258You're free to define as many short option strings and as many long option
259strings as you like (including zero), as long as there is at least one option
260string overall.
261
262The option strings passed to :meth:`add_option` are effectively labels for the
263option defined by that call. For brevity, we will frequently refer to
264*encountering an option* on the command line; in reality, :mod:`optparse`
265encounters *option strings* and looks up options from them.
266
267Once all of your options are defined, instruct :mod:`optparse` to parse your
268program's command line::
269
270 (options, args) = parser.parse_args()
271
272(If you like, you can pass a custom argument list to :meth:`parse_args`, but
273that's rarely necessary: by default it uses ``sys.argv[1:]``.)
274
275:meth:`parse_args` returns two values:
276
277* ``options``, an object containing values for all of your options---e.g. if
278 ``"--file"`` takes a single string argument, then ``options.file`` will be the
279 filename supplied by the user, or ``None`` if the user did not supply that
280 option
281
282* ``args``, the list of positional arguments leftover after parsing options
283
284This tutorial section only covers the four most important option attributes:
Georg Brandl15a515f2009-09-17 22:11:49 +0000285:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
286(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
287most fundamental.
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289
290.. _optparse-understanding-option-actions:
291
292Understanding option actions
293^^^^^^^^^^^^^^^^^^^^^^^^^^^^
294
295Actions tell :mod:`optparse` what to do when it encounters an option on the
296command line. There is a fixed set of actions hard-coded into :mod:`optparse`;
297adding new actions is an advanced topic covered in section
Georg Brandl15a515f2009-09-17 22:11:49 +0000298:ref:`optparse-extending-optparse`. Most actions tell :mod:`optparse` to store
299a value in some variable---for example, take a string from the command line and
300store it in an attribute of ``options``.
Georg Brandl116aa622007-08-15 14:28:22 +0000301
302If you don't specify an option action, :mod:`optparse` defaults to ``store``.
303
304
305.. _optparse-store-action:
306
307The store action
308^^^^^^^^^^^^^^^^
309
310The most common option action is ``store``, which tells :mod:`optparse` to take
311the next argument (or the remainder of the current argument), ensure that it is
312of the correct type, and store it to your chosen destination.
313
314For example::
315
316 parser.add_option("-f", "--file",
317 action="store", type="string", dest="filename")
318
319Now let's make up a fake command line and ask :mod:`optparse` to parse it::
320
321 args = ["-f", "foo.txt"]
322 (options, args) = parser.parse_args(args)
323
324When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
325argument, ``"foo.txt"``, and stores it in ``options.filename``. So, after this
326call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
327
328Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
329Here's an option that expects an integer argument::
330
331 parser.add_option("-n", type="int", dest="num")
332
333Note that this option has no long option string, which is perfectly acceptable.
334Also, there's no explicit action, since the default is ``store``.
335
336Let's parse another fake command-line. This time, we'll jam the option argument
337right up against the option: since ``"-n42"`` (one argument) is equivalent to
Georg Brandl15a515f2009-09-17 22:11:49 +0000338``"-n 42"`` (two arguments), the code ::
Georg Brandl116aa622007-08-15 14:28:22 +0000339
340 (options, args) = parser.parse_args(["-n42"])
Georg Brandl6911e3c2007-09-04 07:15:32 +0000341 print(options.num)
Georg Brandl116aa622007-08-15 14:28:22 +0000342
343will print ``"42"``.
344
345If you don't specify a type, :mod:`optparse` assumes ``string``. Combined with
346the fact that the default action is ``store``, that means our first example can
347be a lot shorter::
348
349 parser.add_option("-f", "--file", dest="filename")
350
351If you don't supply a destination, :mod:`optparse` figures out a sensible
352default from the option strings: if the first long option string is
353``"--foo-bar"``, then the default destination is ``foo_bar``. If there are no
354long option strings, :mod:`optparse` looks at the first short option string: the
355default destination for ``"-f"`` is ``f``.
356
Georg Brandl5c106642007-11-29 17:41:05 +0000357:mod:`optparse` also includes the built-in ``complex`` type. Adding
Georg Brandl116aa622007-08-15 14:28:22 +0000358types is covered in section :ref:`optparse-extending-optparse`.
359
360
361.. _optparse-handling-boolean-options:
362
363Handling boolean (flag) options
364^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
365
366Flag options---set a variable to true or false when a particular option is seen
367---are quite common. :mod:`optparse` supports them with two separate actions,
368``store_true`` and ``store_false``. For example, you might have a ``verbose``
369flag that is turned on with ``"-v"`` and off with ``"-q"``::
370
371 parser.add_option("-v", action="store_true", dest="verbose")
372 parser.add_option("-q", action="store_false", dest="verbose")
373
374Here we have two different options with the same destination, which is perfectly
375OK. (It just means you have to be a bit careful when setting default values---
376see below.)
377
378When :mod:`optparse` encounters ``"-v"`` on the command line, it sets
379``options.verbose`` to ``True``; when it encounters ``"-q"``,
380``options.verbose`` is set to ``False``.
381
382
383.. _optparse-other-actions:
384
385Other actions
386^^^^^^^^^^^^^
387
388Some other actions supported by :mod:`optparse` are:
389
Georg Brandl15a515f2009-09-17 22:11:49 +0000390``"store_const"``
Georg Brandl116aa622007-08-15 14:28:22 +0000391 store a constant value
392
Georg Brandl15a515f2009-09-17 22:11:49 +0000393``"append"``
Georg Brandl116aa622007-08-15 14:28:22 +0000394 append this option's argument to a list
395
Georg Brandl15a515f2009-09-17 22:11:49 +0000396``"count"``
Georg Brandl116aa622007-08-15 14:28:22 +0000397 increment a counter by one
398
Georg Brandl15a515f2009-09-17 22:11:49 +0000399``"callback"``
Georg Brandl116aa622007-08-15 14:28:22 +0000400 call a specified function
401
402These are covered in section :ref:`optparse-reference-guide`, Reference Guide
403and section :ref:`optparse-option-callbacks`.
404
405
406.. _optparse-default-values:
407
408Default values
409^^^^^^^^^^^^^^
410
411All of the above examples involve setting some variable (the "destination") when
412certain command-line options are seen. What happens if those options are never
413seen? Since we didn't supply any defaults, they are all set to ``None``. This
414is usually fine, but sometimes you want more control. :mod:`optparse` lets you
415supply a default value for each destination, which is assigned before the
416command line is parsed.
417
418First, consider the verbose/quiet example. If we want :mod:`optparse` to set
419``verbose`` to ``True`` unless ``"-q"`` is seen, then we can do this::
420
421 parser.add_option("-v", action="store_true", dest="verbose", default=True)
422 parser.add_option("-q", action="store_false", dest="verbose")
423
424Since default values apply to the *destination* rather than to any particular
425option, and these two options happen to have the same destination, this is
426exactly equivalent::
427
428 parser.add_option("-v", action="store_true", dest="verbose")
429 parser.add_option("-q", action="store_false", dest="verbose", default=True)
430
431Consider this::
432
433 parser.add_option("-v", action="store_true", dest="verbose", default=False)
434 parser.add_option("-q", action="store_false", dest="verbose", default=True)
435
436Again, the default value for ``verbose`` will be ``True``: the last default
437value supplied for any particular destination is the one that counts.
438
439A clearer way to specify default values is the :meth:`set_defaults` method of
440OptionParser, which you can call at any time before calling :meth:`parse_args`::
441
442 parser.set_defaults(verbose=True)
443 parser.add_option(...)
444 (options, args) = parser.parse_args()
445
446As before, the last value specified for a given option destination is the one
447that counts. For clarity, try to use one method or the other of setting default
448values, not both.
449
450
451.. _optparse-generating-help:
452
453Generating help
454^^^^^^^^^^^^^^^
455
456:mod:`optparse`'s ability to generate help and usage text automatically is
457useful for creating user-friendly command-line interfaces. All you have to do
Georg Brandl15a515f2009-09-17 22:11:49 +0000458is supply a :attr:`~Option.help` value for each option, and optionally a short
459usage message for your whole program. Here's an OptionParser populated with
Georg Brandl116aa622007-08-15 14:28:22 +0000460user-friendly (documented) options::
461
462 usage = "usage: %prog [options] arg1 arg2"
463 parser = OptionParser(usage=usage)
464 parser.add_option("-v", "--verbose",
465 action="store_true", dest="verbose", default=True,
466 help="make lots of noise [default]")
467 parser.add_option("-q", "--quiet",
Benjamin Petersonae5360b2008-09-08 23:05:23 +0000468 action="store_false", dest="verbose",
Georg Brandl116aa622007-08-15 14:28:22 +0000469 help="be vewwy quiet (I'm hunting wabbits)")
470 parser.add_option("-f", "--filename",
Georg Brandlee8783d2009-09-16 16:00:31 +0000471 metavar="FILE", help="write output to FILE")
Georg Brandl116aa622007-08-15 14:28:22 +0000472 parser.add_option("-m", "--mode",
473 default="intermediate",
474 help="interaction mode: novice, intermediate, "
475 "or expert [default: %default]")
476
477If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
478command-line, or if you just call :meth:`parser.print_help`, it prints the
479following to standard output::
480
481 usage: <yourscript> [options] arg1 arg2
482
483 options:
484 -h, --help show this help message and exit
485 -v, --verbose make lots of noise [default]
486 -q, --quiet be vewwy quiet (I'm hunting wabbits)
487 -f FILE, --filename=FILE
488 write output to FILE
489 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
490 expert [default: intermediate]
491
492(If the help output is triggered by a help option, :mod:`optparse` exits after
493printing the help text.)
494
495There's a lot going on here to help :mod:`optparse` generate the best possible
496help message:
497
498* the script defines its own usage message::
499
500 usage = "usage: %prog [options] arg1 arg2"
501
502 :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
Georg Brandl15a515f2009-09-17 22:11:49 +0000503 current program, i.e. ``os.path.basename(sys.argv[0])``. The expanded string
504 is then printed before the detailed option help.
Georg Brandl116aa622007-08-15 14:28:22 +0000505
506 If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
Georg Brandl15a515f2009-09-17 22:11:49 +0000507 default: ``"usage: %prog [options]"``, which is fine if your script doesn't
508 take any positional arguments.
Georg Brandl116aa622007-08-15 14:28:22 +0000509
510* every option defines a help string, and doesn't worry about line-wrapping---
511 :mod:`optparse` takes care of wrapping lines and making the help output look
512 good.
513
514* options that take a value indicate this fact in their automatically-generated
515 help message, e.g. for the "mode" option::
516
517 -m MODE, --mode=MODE
518
519 Here, "MODE" is called the meta-variable: it stands for the argument that the
520 user is expected to supply to :option:`-m`/:option:`--mode`. By default,
521 :mod:`optparse` converts the destination variable name to uppercase and uses
Georg Brandl15a515f2009-09-17 22:11:49 +0000522 that for the meta-variable. Sometimes, that's not what you want---for
523 example, the :option:`--filename` option explicitly sets ``metavar="FILE"``,
524 resulting in this automatically-generated option description::
Georg Brandl116aa622007-08-15 14:28:22 +0000525
526 -f FILE, --filename=FILE
527
Georg Brandl15a515f2009-09-17 22:11:49 +0000528 This is important for more than just saving space, though: the manually
529 written help text uses the meta-variable "FILE" to clue the user in that
530 there's a connection between the semi-formal syntax "-f FILE" and the informal
531 semantic description "write output to FILE". This is a simple but effective
532 way to make your help text a lot clearer and more useful for end users.
Georg Brandl116aa622007-08-15 14:28:22 +0000533
534* options that have a default value can include ``%default`` in the help
535 string---\ :mod:`optparse` will replace it with :func:`str` of the option's
536 default value. If an option has no default value (or the default value is
537 ``None``), ``%default`` expands to ``none``.
538
Georg Brandl15a515f2009-09-17 22:11:49 +0000539When dealing with many options, it is convenient to group these options for
540better help output. An :class:`OptionParser` can contain several option groups,
541each of which can contain several options.
Christian Heimesfdab48e2008-01-20 09:06:41 +0000542
Georg Brandl15a515f2009-09-17 22:11:49 +0000543Continuing with the parser defined above, adding an :class:`OptionGroup` to a
544parser is easy::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000545
546 group = OptionGroup(parser, "Dangerous Options",
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000547 "Caution: use these options at your own risk. "
548 "It is believed that some of them bite.")
Christian Heimesfdab48e2008-01-20 09:06:41 +0000549 group.add_option("-g", action="store_true", help="Group option.")
550 parser.add_option_group(group)
551
552This would result in the following help output::
553
554 usage: [options] arg1 arg2
555
556 options:
557 -h, --help show this help message and exit
558 -v, --verbose make lots of noise [default]
559 -q, --quiet be vewwy quiet (I'm hunting wabbits)
560 -fFILE, --file=FILE write output to FILE
561 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000562 [default], 'expert'
Christian Heimesfdab48e2008-01-20 09:06:41 +0000563
564 Dangerous Options:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000565 Caution: use of these options is at your own risk. It is believed that
566 some of them bite.
567 -g Group option.
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569.. _optparse-printing-version-string:
570
571Printing a version string
572^^^^^^^^^^^^^^^^^^^^^^^^^
573
574Similar to the brief usage string, :mod:`optparse` can also print a version
575string for your program. You have to supply the string as the ``version``
576argument to OptionParser::
577
578 parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
579
580``"%prog"`` is expanded just like it is in ``usage``. Apart from that,
581``version`` can contain anything you like. When you supply it, :mod:`optparse`
582automatically adds a ``"--version"`` option to your parser. If it encounters
583this option on the command line, it expands your ``version`` string (by
584replacing ``"%prog"``), prints it to stdout, and exits.
585
586For example, if your script is called ``/usr/bin/foo``::
587
588 $ /usr/bin/foo --version
589 foo 1.0
590
591
592.. _optparse-how-optparse-handles-errors:
593
594How :mod:`optparse` handles errors
595^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
596
597There are two broad classes of errors that :mod:`optparse` has to worry about:
598programmer errors and user errors. Programmer errors are usually erroneous
Georg Brandl15a515f2009-09-17 22:11:49 +0000599calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
600option attributes, missing option attributes, etc. These are dealt with in the
601usual way: raise an exception (either :exc:`optparse.OptionError` or
602:exc:`TypeError`) and let the program crash.
Georg Brandl116aa622007-08-15 14:28:22 +0000603
604Handling user errors is much more important, since they are guaranteed to happen
605no matter how stable your code is. :mod:`optparse` can automatically detect
606some user errors, such as bad option arguments (passing ``"-n 4x"`` where
607:option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
608of the command line, where :option:`-n` takes an argument of any type). Also,
Georg Brandl15a515f2009-09-17 22:11:49 +0000609you can call :func:`OptionParser.error` to signal an application-defined error
Georg Brandl116aa622007-08-15 14:28:22 +0000610condition::
611
612 (options, args) = parser.parse_args()
613 [...]
614 if options.a and options.b:
615 parser.error("options -a and -b are mutually exclusive")
616
617In either case, :mod:`optparse` handles the error the same way: it prints the
618program's usage message and an error message to standard error and exits with
619error status 2.
620
621Consider the first example above, where the user passes ``"4x"`` to an option
622that takes an integer::
623
624 $ /usr/bin/foo -n 4x
625 usage: foo [options]
626
627 foo: error: option -n: invalid integer value: '4x'
628
629Or, where the user fails to pass a value at all::
630
631 $ /usr/bin/foo -n
632 usage: foo [options]
633
634 foo: error: -n option requires an argument
635
636:mod:`optparse`\ -generated error messages take care always to mention the
637option involved in the error; be sure to do the same when calling
Georg Brandl15a515f2009-09-17 22:11:49 +0000638:func:`OptionParser.error` from your application code.
Georg Brandl116aa622007-08-15 14:28:22 +0000639
Amaury Forgeot d'Arc35c86582008-06-17 21:11:29 +0000640If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000641you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
642and/or :meth:`~OptionParser.error` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000643
644
645.. _optparse-putting-it-all-together:
646
647Putting it all together
648^^^^^^^^^^^^^^^^^^^^^^^
649
650Here's what :mod:`optparse`\ -based scripts usually look like::
651
652 from optparse import OptionParser
653 [...]
654 def main():
655 usage = "usage: %prog [options] arg"
656 parser = OptionParser(usage)
657 parser.add_option("-f", "--file", dest="filename",
658 help="read data from FILENAME")
659 parser.add_option("-v", "--verbose",
660 action="store_true", dest="verbose")
661 parser.add_option("-q", "--quiet",
662 action="store_false", dest="verbose")
663 [...]
664 (options, args) = parser.parse_args()
665 if len(args) != 1:
666 parser.error("incorrect number of arguments")
667 if options.verbose:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000668 print("reading %s..." % options.filename)
Georg Brandl116aa622007-08-15 14:28:22 +0000669 [...]
670
671 if __name__ == "__main__":
672 main()
673
Georg Brandl116aa622007-08-15 14:28:22 +0000674
675.. _optparse-reference-guide:
676
677Reference Guide
678---------------
679
680
681.. _optparse-creating-parser:
682
683Creating the parser
684^^^^^^^^^^^^^^^^^^^
685
Georg Brandl15a515f2009-09-17 22:11:49 +0000686The first step in using :mod:`optparse` is to create an OptionParser instance.
Georg Brandl116aa622007-08-15 14:28:22 +0000687
Georg Brandl15a515f2009-09-17 22:11:49 +0000688.. class:: OptionParser(...)
Georg Brandl116aa622007-08-15 14:28:22 +0000689
Georg Brandl15a515f2009-09-17 22:11:49 +0000690 The OptionParser constructor has no required arguments, but a number of
691 optional keyword arguments. You should always pass them as keyword
692 arguments, i.e. do not rely on the order in which the arguments are declared.
Georg Brandl116aa622007-08-15 14:28:22 +0000693
694 ``usage`` (default: ``"%prog [options]"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000695 The usage summary to print when your program is run incorrectly or with a
696 help option. When :mod:`optparse` prints the usage string, it expands
697 ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
698 passed that keyword argument). To suppress a usage message, pass the
699 special value :data:`optparse.SUPPRESS_USAGE`.
Georg Brandl116aa622007-08-15 14:28:22 +0000700
701 ``option_list`` (default: ``[]``)
702 A list of Option objects to populate the parser with. The options in
Georg Brandl15a515f2009-09-17 22:11:49 +0000703 ``option_list`` are added after any options in ``standard_option_list`` (a
704 class attribute that may be set by OptionParser subclasses), but before
705 any version or help options. Deprecated; use :meth:`add_option` after
706 creating the parser instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000707
708 ``option_class`` (default: optparse.Option)
709 Class to use when adding options to the parser in :meth:`add_option`.
710
711 ``version`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000712 A version string to print when the user supplies a version option. If you
713 supply a true value for ``version``, :mod:`optparse` automatically adds a
714 version option with the single option string ``"--version"``. The
715 substring ``"%prog"`` is expanded the same as for ``usage``.
Georg Brandl116aa622007-08-15 14:28:22 +0000716
717 ``conflict_handler`` (default: ``"error"``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000718 Specifies what to do when options with conflicting option strings are
719 added to the parser; see section
720 :ref:`optparse-conflicts-between-options`.
Georg Brandl116aa622007-08-15 14:28:22 +0000721
722 ``description`` (default: ``None``)
Georg Brandl15a515f2009-09-17 22:11:49 +0000723 A paragraph of text giving a brief overview of your program.
724 :mod:`optparse` reformats this paragraph to fit the current terminal width
725 and prints it when the user requests help (after ``usage``, but before the
726 list of options).
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Georg Brandl15a515f2009-09-17 22:11:49 +0000728 ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
729 An instance of optparse.HelpFormatter that will be used for printing help
730 text. :mod:`optparse` provides two concrete classes for this purpose:
Georg Brandl116aa622007-08-15 14:28:22 +0000731 IndentedHelpFormatter and TitledHelpFormatter.
732
733 ``add_help_option`` (default: ``True``)
734 If true, :mod:`optparse` will add a help option (with option strings ``"-h"``
735 and ``"--help"``) to the parser.
736
737 ``prog``
738 The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
739 instead of ``os.path.basename(sys.argv[0])``.
740
741
742
743.. _optparse-populating-parser:
744
745Populating the parser
746^^^^^^^^^^^^^^^^^^^^^
747
748There are several ways to populate the parser with options. The preferred way
Georg Brandl15a515f2009-09-17 22:11:49 +0000749is by using :meth:`OptionParser.add_option`, as shown in section
Georg Brandl116aa622007-08-15 14:28:22 +0000750:ref:`optparse-tutorial`. :meth:`add_option` can be called in one of two ways:
751
752* pass it an Option instance (as returned by :func:`make_option`)
753
754* pass it any combination of positional and keyword arguments that are
Georg Brandl15a515f2009-09-17 22:11:49 +0000755 acceptable to :func:`make_option` (i.e., to the Option constructor), and it
756 will create the Option instance for you
Georg Brandl116aa622007-08-15 14:28:22 +0000757
758The other alternative is to pass a list of pre-constructed Option instances to
759the OptionParser constructor, as in::
760
761 option_list = [
762 make_option("-f", "--filename",
763 action="store", type="string", dest="filename"),
764 make_option("-q", "--quiet",
765 action="store_false", dest="verbose"),
766 ]
767 parser = OptionParser(option_list=option_list)
768
769(:func:`make_option` is a factory function for creating Option instances;
770currently it is an alias for the Option constructor. A future version of
771:mod:`optparse` may split Option into several classes, and :func:`make_option`
772will pick the right class to instantiate. Do not instantiate Option directly.)
773
774
775.. _optparse-defining-options:
776
777Defining options
778^^^^^^^^^^^^^^^^
779
780Each Option instance represents a set of synonymous command-line option strings,
781e.g. :option:`-f` and :option:`--file`. You can specify any number of short or
782long option strings, but you must specify at least one overall option string.
783
Georg Brandl15a515f2009-09-17 22:11:49 +0000784The canonical way to create an :class:`Option` instance is with the
785:meth:`add_option` method of :class:`OptionParser`.
Georg Brandl116aa622007-08-15 14:28:22 +0000786
Georg Brandl15a515f2009-09-17 22:11:49 +0000787.. method:: OptionParser.add_option(opt_str[, ...], attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000788
Georg Brandl15a515f2009-09-17 22:11:49 +0000789 To define an option with only a short option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000790
Georg Brandl15a515f2009-09-17 22:11:49 +0000791 parser.add_option("-f", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000792
Georg Brandl15a515f2009-09-17 22:11:49 +0000793 And to define an option with only a long option string::
Georg Brandl116aa622007-08-15 14:28:22 +0000794
Georg Brandl15a515f2009-09-17 22:11:49 +0000795 parser.add_option("--foo", attr=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +0000796
Georg Brandl15a515f2009-09-17 22:11:49 +0000797 The keyword arguments define attributes of the new Option object. The most
798 important option attribute is :attr:`~Option.action`, and it largely
799 determines which other attributes are relevant or required. If you pass
800 irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
801 raises an :exc:`OptionError` exception explaining your mistake.
Georg Brandl116aa622007-08-15 14:28:22 +0000802
Georg Brandl15a515f2009-09-17 22:11:49 +0000803 An option's *action* determines what :mod:`optparse` does when it encounters
804 this option on the command-line. The standard option actions hard-coded into
805 :mod:`optparse` are:
Georg Brandl116aa622007-08-15 14:28:22 +0000806
Georg Brandl15a515f2009-09-17 22:11:49 +0000807 ``"store"``
808 store this option's argument (default)
Georg Brandl116aa622007-08-15 14:28:22 +0000809
Georg Brandl15a515f2009-09-17 22:11:49 +0000810 ``"store_const"``
811 store a constant value
Georg Brandl116aa622007-08-15 14:28:22 +0000812
Georg Brandl15a515f2009-09-17 22:11:49 +0000813 ``"store_true"``
814 store a true value
Georg Brandl116aa622007-08-15 14:28:22 +0000815
Georg Brandl15a515f2009-09-17 22:11:49 +0000816 ``"store_false"``
817 store a false value
Georg Brandl116aa622007-08-15 14:28:22 +0000818
Georg Brandl15a515f2009-09-17 22:11:49 +0000819 ``"append"``
820 append this option's argument to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000821
Georg Brandl15a515f2009-09-17 22:11:49 +0000822 ``"append_const"``
823 append a constant value to a list
Georg Brandl116aa622007-08-15 14:28:22 +0000824
Georg Brandl15a515f2009-09-17 22:11:49 +0000825 ``"count"``
826 increment a counter by one
Georg Brandl116aa622007-08-15 14:28:22 +0000827
Georg Brandl15a515f2009-09-17 22:11:49 +0000828 ``"callback"``
829 call a specified function
Georg Brandl116aa622007-08-15 14:28:22 +0000830
Georg Brandl15a515f2009-09-17 22:11:49 +0000831 ``"help"``
832 print a usage message including all options and the documentation for them
Georg Brandl116aa622007-08-15 14:28:22 +0000833
Georg Brandl15a515f2009-09-17 22:11:49 +0000834 (If you don't supply an action, the default is ``"store"``. For this action,
835 you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
836 attributes; see :ref:`optparse-standard-option-actions`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000837
838As you can see, most actions involve storing or updating a value somewhere.
839:mod:`optparse` always creates a special object for this, conventionally called
Georg Brandl15a515f2009-09-17 22:11:49 +0000840``options`` (it happens to be an instance of :class:`optparse.Values`). Option
Georg Brandl116aa622007-08-15 14:28:22 +0000841arguments (and various other values) are stored as attributes of this object,
Georg Brandl15a515f2009-09-17 22:11:49 +0000842according to the :attr:`~Option.dest` (destination) option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +0000843
Georg Brandl15a515f2009-09-17 22:11:49 +0000844For example, when you call ::
Georg Brandl116aa622007-08-15 14:28:22 +0000845
846 parser.parse_args()
847
848one of the first things :mod:`optparse` does is create the ``options`` object::
849
850 options = Values()
851
Georg Brandl15a515f2009-09-17 22:11:49 +0000852If one of the options in this parser is defined with ::
Georg Brandl116aa622007-08-15 14:28:22 +0000853
854 parser.add_option("-f", "--file", action="store", type="string", dest="filename")
855
856and the command-line being parsed includes any of the following::
857
858 -ffoo
859 -f foo
860 --file=foo
861 --file foo
862
Georg Brandl15a515f2009-09-17 22:11:49 +0000863then :mod:`optparse`, on seeing this option, will do the equivalent of ::
Georg Brandl116aa622007-08-15 14:28:22 +0000864
865 options.filename = "foo"
866
Georg Brandl15a515f2009-09-17 22:11:49 +0000867The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
868as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
869one that makes sense for *all* options.
870
871
872.. _optparse-option-attributes:
873
874Option attributes
875^^^^^^^^^^^^^^^^^
876
877The following option attributes may be passed as keyword arguments to
878:meth:`OptionParser.add_option`. If you pass an option attribute that is not
879relevant to a particular option, or fail to pass a required option attribute,
880:mod:`optparse` raises :exc:`OptionError`.
881
882.. attribute:: Option.action
883
884 (default: ``"store"``)
885
886 Determines :mod:`optparse`'s behaviour when this option is seen on the
887 command line; the available options are documented :ref:`here
888 <optparse-standard-option-actions>`.
889
890.. attribute:: Option.type
891
892 (default: ``"string"``)
893
894 The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
895 the available option types are documented :ref:`here
896 <optparse-standard-option-types>`.
897
898.. attribute:: Option.dest
899
900 (default: derived from option strings)
901
902 If the option's action implies writing or modifying a value somewhere, this
903 tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
904 attribute of the ``options`` object that :mod:`optparse` builds as it parses
905 the command line.
906
907.. attribute:: Option.default
908
909 The value to use for this option's destination if the option is not seen on
910 the command line. See also :meth:`OptionParser.set_defaults`.
911
912.. attribute:: Option.nargs
913
914 (default: 1)
915
916 How many arguments of type :attr:`~Option.type` should be consumed when this
917 option is seen. If > 1, :mod:`optparse` will store a tuple of values to
918 :attr:`~Option.dest`.
919
920.. attribute:: Option.const
921
922 For actions that store a constant value, the constant value to store.
923
924.. attribute:: Option.choices
925
926 For options of type ``"choice"``, the list of strings the user may choose
927 from.
928
929.. attribute:: Option.callback
930
931 For options with action ``"callback"``, the callable to call when this option
932 is seen. See section :ref:`optparse-option-callbacks` for detail on the
933 arguments passed to the callable.
934
935.. attribute:: Option.callback_args
936 Option.callback_kwargs
937
938 Additional positional and keyword arguments to pass to ``callback`` after the
939 four standard callback arguments.
940
941.. attribute:: Option.help
942
943 Help text to print for this option when listing all available options after
944 the user supplies a :attr:`~Option.help` option (such as ``"--help"``). If
945 no help text is supplied, the option will be listed without help text. To
946 hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
947
948.. attribute:: Option.metavar
949
950 (default: derived from option strings)
951
952 Stand-in for the option argument(s) to use when printing help text. See
953 section :ref:`optparse-tutorial` for an example.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955
956.. _optparse-standard-option-actions:
957
958Standard option actions
959^^^^^^^^^^^^^^^^^^^^^^^
960
961The various option actions all have slightly different requirements and effects.
962Most actions have several relevant option attributes which you may specify to
963guide :mod:`optparse`'s behaviour; a few have required attributes, which you
964must specify for any option using that action.
965
Georg Brandl15a515f2009-09-17 22:11:49 +0000966* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
967 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +0000968
969 The option must be followed by an argument, which is converted to a value
Georg Brandl15a515f2009-09-17 22:11:49 +0000970 according to :attr:`~Option.type` and stored in :attr:`~Option.dest`. If
971 :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
972 command line; all will be converted according to :attr:`~Option.type` and
973 stored to :attr:`~Option.dest` as a tuple. See the
974 :ref:`optparse-standard-option-types` section.
Georg Brandl116aa622007-08-15 14:28:22 +0000975
Georg Brandl15a515f2009-09-17 22:11:49 +0000976 If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
977 defaults to ``"choice"``.
Georg Brandl116aa622007-08-15 14:28:22 +0000978
Georg Brandl15a515f2009-09-17 22:11:49 +0000979 If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
Georg Brandl116aa622007-08-15 14:28:22 +0000980
Georg Brandl15a515f2009-09-17 22:11:49 +0000981 If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
982 from the first long option string (e.g., ``"--foo-bar"`` implies
983 ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
984 destination from the first short option string (e.g., ``"-f"`` implies ``f``).
Georg Brandl116aa622007-08-15 14:28:22 +0000985
986 Example::
987
988 parser.add_option("-f")
989 parser.add_option("-p", type="float", nargs=3, dest="point")
990
Georg Brandl15a515f2009-09-17 22:11:49 +0000991 As it parses the command line ::
Georg Brandl116aa622007-08-15 14:28:22 +0000992
993 -f foo.txt -p 1 -3.5 4 -fbar.txt
994
Georg Brandl15a515f2009-09-17 22:11:49 +0000995 :mod:`optparse` will set ::
Georg Brandl116aa622007-08-15 14:28:22 +0000996
997 options.f = "foo.txt"
998 options.point = (1.0, -3.5, 4.0)
999 options.f = "bar.txt"
1000
Georg Brandl15a515f2009-09-17 22:11:49 +00001001* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
1002 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001003
Georg Brandl15a515f2009-09-17 22:11:49 +00001004 The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001005
1006 Example::
1007
1008 parser.add_option("-q", "--quiet",
1009 action="store_const", const=0, dest="verbose")
1010 parser.add_option("-v", "--verbose",
1011 action="store_const", const=1, dest="verbose")
1012 parser.add_option("--noisy",
1013 action="store_const", const=2, dest="verbose")
1014
1015 If ``"--noisy"`` is seen, :mod:`optparse` will set ::
1016
1017 options.verbose = 2
1018
Georg Brandl15a515f2009-09-17 22:11:49 +00001019* ``"store_true"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001020
Georg Brandl15a515f2009-09-17 22:11:49 +00001021 A special case of ``"store_const"`` that stores a true value to
1022 :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001023
Georg Brandl15a515f2009-09-17 22:11:49 +00001024* ``"store_false"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001025
Georg Brandl15a515f2009-09-17 22:11:49 +00001026 Like ``"store_true"``, but stores a false value.
Georg Brandl116aa622007-08-15 14:28:22 +00001027
1028 Example::
1029
1030 parser.add_option("--clobber", action="store_true", dest="clobber")
1031 parser.add_option("--no-clobber", action="store_false", dest="clobber")
1032
Georg Brandl15a515f2009-09-17 22:11:49 +00001033* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
1034 :attr:`~Option.nargs`, :attr:`~Option.choices`]
Georg Brandl116aa622007-08-15 14:28:22 +00001035
1036 The option must be followed by an argument, which is appended to the list in
Georg Brandl15a515f2009-09-17 22:11:49 +00001037 :attr:`~Option.dest`. If no default value for :attr:`~Option.dest` is
1038 supplied, an empty list is automatically created when :mod:`optparse` first
1039 encounters this option on the command-line. If :attr:`~Option.nargs` > 1,
1040 multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
1041 is appended to :attr:`~Option.dest`.
Georg Brandl116aa622007-08-15 14:28:22 +00001042
Georg Brandl15a515f2009-09-17 22:11:49 +00001043 The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
1044 for the ``"store"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001045
1046 Example::
1047
1048 parser.add_option("-t", "--tracks", action="append", type="int")
1049
1050 If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
1051 of::
1052
1053 options.tracks = []
1054 options.tracks.append(int("3"))
1055
1056 If, a little later on, ``"--tracks=4"`` is seen, it does::
1057
1058 options.tracks.append(int("4"))
1059
Georg Brandl15a515f2009-09-17 22:11:49 +00001060* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
1061 :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Georg Brandl15a515f2009-09-17 22:11:49 +00001063 Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
1064 :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
1065 ``None``, and an empty list is automatically created the first time the option
1066 is encountered.
Georg Brandl116aa622007-08-15 14:28:22 +00001067
Georg Brandl15a515f2009-09-17 22:11:49 +00001068* ``"count"`` [relevant: :attr:`~Option.dest`]
Georg Brandl116aa622007-08-15 14:28:22 +00001069
Georg Brandl15a515f2009-09-17 22:11:49 +00001070 Increment the integer stored at :attr:`~Option.dest`. If no default value is
1071 supplied, :attr:`~Option.dest` is set to zero before being incremented the
1072 first time.
Georg Brandl116aa622007-08-15 14:28:22 +00001073
1074 Example::
1075
1076 parser.add_option("-v", action="count", dest="verbosity")
1077
1078 The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
1079 equivalent of::
1080
1081 options.verbosity = 0
1082 options.verbosity += 1
1083
1084 Every subsequent occurrence of ``"-v"`` results in ::
1085
1086 options.verbosity += 1
1087
Georg Brandl15a515f2009-09-17 22:11:49 +00001088* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
1089 :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
1090 :attr:`~Option.callback_kwargs`]
Georg Brandl116aa622007-08-15 14:28:22 +00001091
Georg Brandl15a515f2009-09-17 22:11:49 +00001092 Call the function specified by :attr:`~Option.callback`, which is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001093
1094 func(option, opt_str, value, parser, *args, **kwargs)
1095
1096 See section :ref:`optparse-option-callbacks` for more detail.
1097
Georg Brandl15a515f2009-09-17 22:11:49 +00001098* ``"help"``
Georg Brandl116aa622007-08-15 14:28:22 +00001099
Georg Brandl15a515f2009-09-17 22:11:49 +00001100 Prints a complete help message for all the options in the current option
1101 parser. The help message is constructed from the ``usage`` string passed to
1102 OptionParser's constructor and the :attr:`~Option.help` string passed to every
1103 option.
Georg Brandl116aa622007-08-15 14:28:22 +00001104
Georg Brandl15a515f2009-09-17 22:11:49 +00001105 If no :attr:`~Option.help` string is supplied for an option, it will still be
1106 listed in the help message. To omit an option entirely, use the special value
1107 :data:`optparse.SUPPRESS_HELP`.
Georg Brandl116aa622007-08-15 14:28:22 +00001108
Georg Brandl15a515f2009-09-17 22:11:49 +00001109 :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
1110 OptionParsers, so you do not normally need to create one.
Georg Brandl116aa622007-08-15 14:28:22 +00001111
1112 Example::
1113
1114 from optparse import OptionParser, SUPPRESS_HELP
1115
Georg Brandlee8783d2009-09-16 16:00:31 +00001116 # usually, a help option is added automatically, but that can
1117 # be suppressed using the add_help_option argument
1118 parser = OptionParser(add_help_option=False)
1119
1120 parser.add_option("-h", "--help", action="help")
Georg Brandl116aa622007-08-15 14:28:22 +00001121 parser.add_option("-v", action="store_true", dest="verbose",
1122 help="Be moderately verbose")
1123 parser.add_option("--file", dest="filename",
Georg Brandlee8783d2009-09-16 16:00:31 +00001124 help="Input file to read data from")
Georg Brandl116aa622007-08-15 14:28:22 +00001125 parser.add_option("--secret", help=SUPPRESS_HELP)
1126
Georg Brandl15a515f2009-09-17 22:11:49 +00001127 If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line,
1128 it will print something like the following help message to stdout (assuming
Georg Brandl116aa622007-08-15 14:28:22 +00001129 ``sys.argv[0]`` is ``"foo.py"``)::
1130
1131 usage: foo.py [options]
1132
1133 options:
1134 -h, --help Show this help message and exit
1135 -v Be moderately verbose
1136 --file=FILENAME Input file to read data from
1137
1138 After printing the help message, :mod:`optparse` terminates your process with
1139 ``sys.exit(0)``.
1140
Georg Brandl15a515f2009-09-17 22:11:49 +00001141* ``"version"``
Georg Brandl116aa622007-08-15 14:28:22 +00001142
Georg Brandl15a515f2009-09-17 22:11:49 +00001143 Prints the version number supplied to the OptionParser to stdout and exits.
1144 The version number is actually formatted and printed by the
1145 ``print_version()`` method of OptionParser. Generally only relevant if the
1146 ``version`` argument is supplied to the OptionParser constructor. As with
1147 :attr:`~Option.help` options, you will rarely create ``version`` options,
1148 since :mod:`optparse` automatically adds them when needed.
Georg Brandl116aa622007-08-15 14:28:22 +00001149
1150
1151.. _optparse-standard-option-types:
1152
1153Standard option types
1154^^^^^^^^^^^^^^^^^^^^^
1155
Georg Brandl15a515f2009-09-17 22:11:49 +00001156:mod:`optparse` has five built-in option types: ``"string"``, ``"int"``,
1157``"choice"``, ``"float"`` and ``"complex"``. If you need to add new
1158option types, see section :ref:`optparse-extending-optparse`.
Georg Brandl116aa622007-08-15 14:28:22 +00001159
1160Arguments to string options are not checked or converted in any way: the text on
1161the command line is stored in the destination (or passed to the callback) as-is.
1162
Georg Brandl15a515f2009-09-17 22:11:49 +00001163Integer arguments (type ``"int"``) are parsed as follows:
Georg Brandl116aa622007-08-15 14:28:22 +00001164
1165* if the number starts with ``0x``, it is parsed as a hexadecimal number
1166
1167* if the number starts with ``0``, it is parsed as an octal number
1168
Georg Brandl9afde1c2007-11-01 20:32:30 +00001169* if the number starts with ``0b``, it is parsed as a binary number
Georg Brandl116aa622007-08-15 14:28:22 +00001170
1171* otherwise, the number is parsed as a decimal number
1172
1173
Georg Brandl15a515f2009-09-17 22:11:49 +00001174The conversion is done by calling :func:`int` with the appropriate base (2, 8,
117510, or 16). If this fails, so will :mod:`optparse`, although with a more useful
Georg Brandl5c106642007-11-29 17:41:05 +00001176error message.
Georg Brandl116aa622007-08-15 14:28:22 +00001177
Georg Brandl15a515f2009-09-17 22:11:49 +00001178``"float"`` and ``"complex"`` option arguments are converted directly with
1179:func:`float` and :func:`complex`, with similar error-handling.
Georg Brandl116aa622007-08-15 14:28:22 +00001180
Georg Brandl15a515f2009-09-17 22:11:49 +00001181``"choice"`` options are a subtype of ``"string"`` options. The
1182:attr:`~Option.choices`` option attribute (a sequence of strings) defines the
1183set of allowed option arguments. :func:`optparse.check_choice` compares
1184user-supplied option arguments against this master list and raises
1185:exc:`OptionValueError` if an invalid string is given.
Georg Brandl116aa622007-08-15 14:28:22 +00001186
1187
1188.. _optparse-parsing-arguments:
1189
1190Parsing arguments
1191^^^^^^^^^^^^^^^^^
1192
1193The whole point of creating and populating an OptionParser is to call its
1194:meth:`parse_args` method::
1195
1196 (options, args) = parser.parse_args(args=None, values=None)
1197
1198where the input parameters are
1199
1200``args``
1201 the list of arguments to process (default: ``sys.argv[1:]``)
1202
1203``values``
Georg Brandla6053b42009-09-01 08:11:14 +00001204 object to store option arguments in (default: a new instance of
1205 :class:`optparse.Values`)
Georg Brandl116aa622007-08-15 14:28:22 +00001206
1207and the return values are
1208
1209``options``
Georg Brandla6053b42009-09-01 08:11:14 +00001210 the same object that was passed in as ``values``, or the optparse.Values
Georg Brandl116aa622007-08-15 14:28:22 +00001211 instance created by :mod:`optparse`
1212
1213``args``
1214 the leftover positional arguments after all options have been processed
1215
1216The most common usage is to supply neither keyword argument. If you supply
Georg Brandl15a515f2009-09-17 22:11:49 +00001217``values``, it will be modified with repeated :func:`setattr` calls (roughly one
Georg Brandl116aa622007-08-15 14:28:22 +00001218for every option argument stored to an option destination) and returned by
1219:meth:`parse_args`.
1220
1221If :meth:`parse_args` encounters any errors in the argument list, it calls the
1222OptionParser's :meth:`error` method with an appropriate end-user error message.
1223This ultimately terminates your process with an exit status of 2 (the
1224traditional Unix exit status for command-line errors).
1225
1226
1227.. _optparse-querying-manipulating-option-parser:
1228
1229Querying and manipulating your option parser
1230^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1231
Georg Brandl15a515f2009-09-17 22:11:49 +00001232The default behavior of the option parser can be customized slightly, and you
1233can also poke around your option parser and see what's there. OptionParser
1234provides several methods to help you out:
Georg Brandl116aa622007-08-15 14:28:22 +00001235
Georg Brandl15a515f2009-09-17 22:11:49 +00001236.. method:: OptionParser.disable_interspersed_args()
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001237
Georg Brandl15a515f2009-09-17 22:11:49 +00001238 Set parsing to stop on the first non-option. For example, if ``"-a"`` and
1239 ``"-b"`` are both simple options that take no arguments, :mod:`optparse`
1240 normally accepts this syntax::
Georg Brandl116aa622007-08-15 14:28:22 +00001241
Georg Brandl15a515f2009-09-17 22:11:49 +00001242 prog -a arg1 -b arg2
1243
1244 and treats it as equivalent to ::
1245
1246 prog -a -b arg1 arg2
1247
1248 To disable this feature, call :meth:`disable_interspersed_args`. This
1249 restores traditional Unix syntax, where option parsing stops with the first
1250 non-option argument.
1251
1252 Use this if you have a command processor which runs another command which has
1253 options of its own and you want to make sure these options don't get
1254 confused. For example, each command might have a different set of options.
1255
1256.. method:: OptionParser.enable_interspersed_args()
1257
1258 Set parsing to not stop on the first non-option, allowing interspersing
1259 switches with command arguments. This is the default behavior.
1260
1261.. method:: OptionParser.get_option(opt_str)
1262
1263 Returns the Option instance with the option string *opt_str*, or ``None`` if
Georg Brandl116aa622007-08-15 14:28:22 +00001264 no options have that option string.
1265
Georg Brandl15a515f2009-09-17 22:11:49 +00001266.. method:: OptionParser.has_option(opt_str)
1267
1268 Return true if the OptionParser has an option with option string *opt_str*
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001269 (e.g., ``"-q"`` or ``"--verbose"``).
1270
Georg Brandl15a515f2009-09-17 22:11:49 +00001271.. method:: OptionParser.remove_option(opt_str)
1272
1273 If the :class:`OptionParser` has an option corresponding to *opt_str*, that
1274 option is removed. If that option provided any other option strings, all of
1275 those option strings become invalid. If *opt_str* does not occur in any
1276 option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.
Georg Brandl116aa622007-08-15 14:28:22 +00001277
1278
1279.. _optparse-conflicts-between-options:
1280
1281Conflicts between options
1282^^^^^^^^^^^^^^^^^^^^^^^^^
1283
1284If you're not careful, it's easy to define options with conflicting option
1285strings::
1286
1287 parser.add_option("-n", "--dry-run", ...)
1288 [...]
1289 parser.add_option("-n", "--noisy", ...)
1290
1291(This is particularly true if you've defined your own OptionParser subclass with
1292some standard options.)
1293
1294Every time you add an option, :mod:`optparse` checks for conflicts with existing
1295options. If it finds any, it invokes the current conflict-handling mechanism.
1296You can set the conflict-handling mechanism either in the constructor::
1297
1298 parser = OptionParser(..., conflict_handler=handler)
1299
1300or with a separate call::
1301
1302 parser.set_conflict_handler(handler)
1303
1304The available conflict handlers are:
1305
Georg Brandl15a515f2009-09-17 22:11:49 +00001306 ``"error"`` (default)
1307 assume option conflicts are a programming error and raise
1308 :exc:`OptionConflictError`
Georg Brandl116aa622007-08-15 14:28:22 +00001309
Georg Brandl15a515f2009-09-17 22:11:49 +00001310 ``"resolve"``
Georg Brandl116aa622007-08-15 14:28:22 +00001311 resolve option conflicts intelligently (see below)
1312
1313
Benjamin Petersone5384b02008-10-04 22:00:42 +00001314As an example, let's define an :class:`OptionParser` that resolves conflicts
Georg Brandl116aa622007-08-15 14:28:22 +00001315intelligently and add conflicting options to it::
1316
1317 parser = OptionParser(conflict_handler="resolve")
1318 parser.add_option("-n", "--dry-run", ..., help="do no harm")
1319 parser.add_option("-n", "--noisy", ..., help="be noisy")
1320
1321At this point, :mod:`optparse` detects that a previously-added option is already
1322using the ``"-n"`` option string. Since ``conflict_handler`` is ``"resolve"``,
1323it resolves the situation by removing ``"-n"`` from the earlier option's list of
1324option strings. Now ``"--dry-run"`` is the only way for the user to activate
1325that option. If the user asks for help, the help message will reflect that::
1326
1327 options:
1328 --dry-run do no harm
1329 [...]
1330 -n, --noisy be noisy
1331
1332It's possible to whittle away the option strings for a previously-added option
1333until there are none left, and the user has no way of invoking that option from
1334the command-line. In that case, :mod:`optparse` removes that option completely,
1335so it doesn't show up in help text or anywhere else. Carrying on with our
1336existing OptionParser::
1337
1338 parser.add_option("--dry-run", ..., help="new dry-run option")
1339
1340At this point, the original :option:`-n/--dry-run` option is no longer
1341accessible, so :mod:`optparse` removes it, leaving this help text::
1342
1343 options:
1344 [...]
1345 -n, --noisy be noisy
1346 --dry-run new dry-run option
1347
1348
1349.. _optparse-cleanup:
1350
1351Cleanup
1352^^^^^^^
1353
1354OptionParser instances have several cyclic references. This should not be a
1355problem for Python's garbage collector, but you may wish to break the cyclic
Georg Brandl15a515f2009-09-17 22:11:49 +00001356references explicitly by calling :meth:`~OptionParser.destroy` on your
1357OptionParser once you are done with it. This is particularly useful in
1358long-running applications where large object graphs are reachable from your
1359OptionParser.
Georg Brandl116aa622007-08-15 14:28:22 +00001360
1361
1362.. _optparse-other-methods:
1363
1364Other methods
1365^^^^^^^^^^^^^
1366
1367OptionParser supports several other public methods:
1368
Georg Brandl15a515f2009-09-17 22:11:49 +00001369.. method:: OptionParser.set_usage(usage)
Georg Brandl116aa622007-08-15 14:28:22 +00001370
Georg Brandl15a515f2009-09-17 22:11:49 +00001371 Set the usage string according to the rules described above for the ``usage``
1372 constructor keyword argument. Passing ``None`` sets the default usage
1373 string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.
Georg Brandl116aa622007-08-15 14:28:22 +00001374
Georg Brandl15a515f2009-09-17 22:11:49 +00001375.. method:: OptionParser.set_defaults(dest=value, ...)
Georg Brandl116aa622007-08-15 14:28:22 +00001376
Georg Brandl15a515f2009-09-17 22:11:49 +00001377 Set default values for several option destinations at once. Using
1378 :meth:`set_defaults` is the preferred way to set default values for options,
1379 since multiple options can share the same destination. For example, if
1380 several "mode" options all set the same destination, any one of them can set
1381 the default, and the last one wins::
Georg Brandl116aa622007-08-15 14:28:22 +00001382
Georg Brandl15a515f2009-09-17 22:11:49 +00001383 parser.add_option("--advanced", action="store_const",
1384 dest="mode", const="advanced",
1385 default="novice") # overridden below
1386 parser.add_option("--novice", action="store_const",
1387 dest="mode", const="novice",
1388 default="advanced") # overrides above setting
Georg Brandl116aa622007-08-15 14:28:22 +00001389
Georg Brandl15a515f2009-09-17 22:11:49 +00001390 To avoid this confusion, use :meth:`set_defaults`::
Georg Brandl116aa622007-08-15 14:28:22 +00001391
Georg Brandl15a515f2009-09-17 22:11:49 +00001392 parser.set_defaults(mode="advanced")
1393 parser.add_option("--advanced", action="store_const",
1394 dest="mode", const="advanced")
1395 parser.add_option("--novice", action="store_const",
1396 dest="mode", const="novice")
Georg Brandl116aa622007-08-15 14:28:22 +00001397
Georg Brandl116aa622007-08-15 14:28:22 +00001398
1399.. _optparse-option-callbacks:
1400
1401Option Callbacks
1402----------------
1403
1404When :mod:`optparse`'s built-in actions and types aren't quite enough for your
1405needs, you have two choices: extend :mod:`optparse` or define a callback option.
1406Extending :mod:`optparse` is more general, but overkill for a lot of simple
1407cases. Quite often a simple callback is all you need.
1408
1409There are two steps to defining a callback option:
1410
Georg Brandl15a515f2009-09-17 22:11:49 +00001411* define the option itself using the ``"callback"`` action
Georg Brandl116aa622007-08-15 14:28:22 +00001412
1413* write the callback; this is a function (or method) that takes at least four
1414 arguments, as described below
1415
1416
1417.. _optparse-defining-callback-option:
1418
1419Defining a callback option
1420^^^^^^^^^^^^^^^^^^^^^^^^^^
1421
1422As always, the easiest way to define a callback option is by using the
Georg Brandl15a515f2009-09-17 22:11:49 +00001423:meth:`OptionParser.add_option` method. Apart from :attr:`~Option.action`, the
1424only option attribute you must specify is ``callback``, the function to call::
Georg Brandl116aa622007-08-15 14:28:22 +00001425
1426 parser.add_option("-c", action="callback", callback=my_callback)
1427
1428``callback`` is a function (or other callable object), so you must have already
1429defined ``my_callback()`` when you create this callback option. In this simple
1430case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,
1431which usually means that the option takes no arguments---the mere presence of
1432:option:`-c` on the command-line is all it needs to know. In some
1433circumstances, though, you might want your callback to consume an arbitrary
1434number of command-line arguments. This is where writing callbacks gets tricky;
1435it's covered later in this section.
1436
1437:mod:`optparse` always passes four particular arguments to your callback, and it
Georg Brandl15a515f2009-09-17 22:11:49 +00001438will only pass additional arguments if you specify them via
1439:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`. Thus, the
1440minimal callback function signature is::
Georg Brandl116aa622007-08-15 14:28:22 +00001441
1442 def my_callback(option, opt, value, parser):
1443
1444The four arguments to a callback are described below.
1445
1446There are several other option attributes that you can supply when you define a
1447callback option:
1448
Georg Brandl15a515f2009-09-17 22:11:49 +00001449:attr:`~Option.type`
1450 has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
1451 instructs :mod:`optparse` to consume one argument and convert it to
1452 :attr:`~Option.type`. Rather than storing the converted value(s) anywhere,
1453 though, :mod:`optparse` passes it to your callback function.
Georg Brandl116aa622007-08-15 14:28:22 +00001454
Georg Brandl15a515f2009-09-17 22:11:49 +00001455:attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001456 also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001457 consume :attr:`~Option.nargs` arguments, each of which must be convertible to
1458 :attr:`~Option.type`. It then passes a tuple of converted values to your
1459 callback.
Georg Brandl116aa622007-08-15 14:28:22 +00001460
Georg Brandl15a515f2009-09-17 22:11:49 +00001461:attr:`~Option.callback_args`
Georg Brandl116aa622007-08-15 14:28:22 +00001462 a tuple of extra positional arguments to pass to the callback
1463
Georg Brandl15a515f2009-09-17 22:11:49 +00001464:attr:`~Option.callback_kwargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001465 a dictionary of extra keyword arguments to pass to the callback
1466
1467
1468.. _optparse-how-callbacks-called:
1469
1470How callbacks are called
1471^^^^^^^^^^^^^^^^^^^^^^^^
1472
1473All callbacks are called as follows::
1474
1475 func(option, opt_str, value, parser, *args, **kwargs)
1476
1477where
1478
1479``option``
1480 is the Option instance that's calling the callback
1481
1482``opt_str``
1483 is the option string seen on the command-line that's triggering the callback.
Georg Brandl15a515f2009-09-17 22:11:49 +00001484 (If an abbreviated long option was used, ``opt_str`` will be the full,
1485 canonical option string---e.g. if the user puts ``"--foo"`` on the
1486 command-line as an abbreviation for ``"--foobar"``, then ``opt_str`` will be
1487 ``"--foobar"``.)
Georg Brandl116aa622007-08-15 14:28:22 +00001488
1489``value``
1490 is the argument to this option seen on the command-line. :mod:`optparse` will
Georg Brandl15a515f2009-09-17 22:11:49 +00001491 only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
1492 the type implied by the option's type. If :attr:`~Option.type` for this option is
1493 ``None`` (no argument expected), then ``value`` will be ``None``. If :attr:`~Option.nargs`
Georg Brandl116aa622007-08-15 14:28:22 +00001494 > 1, ``value`` will be a tuple of values of the appropriate type.
1495
1496``parser``
Georg Brandl15a515f2009-09-17 22:11:49 +00001497 is the OptionParser instance driving the whole thing, mainly useful because
1498 you can access some other interesting data through its instance attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001499
1500 ``parser.largs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001501 the current list of leftover arguments, ie. arguments that have been
1502 consumed but are neither options nor option arguments. Feel free to modify
1503 ``parser.largs``, e.g. by adding more arguments to it. (This list will
1504 become ``args``, the second return value of :meth:`parse_args`.)
Georg Brandl116aa622007-08-15 14:28:22 +00001505
1506 ``parser.rargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001507 the current list of remaining arguments, ie. with ``opt_str`` and
1508 ``value`` (if applicable) removed, and only the arguments following them
1509 still there. Feel free to modify ``parser.rargs``, e.g. by consuming more
1510 arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001511
1512 ``parser.values``
1513 the object where option values are by default stored (an instance of
Georg Brandl15a515f2009-09-17 22:11:49 +00001514 optparse.OptionValues). This lets callbacks use the same mechanism as the
1515 rest of :mod:`optparse` for storing option values; you don't need to mess
1516 around with globals or closures. You can also access or modify the
1517 value(s) of any options already encountered on the command-line.
Georg Brandl116aa622007-08-15 14:28:22 +00001518
1519``args``
Georg Brandl15a515f2009-09-17 22:11:49 +00001520 is a tuple of arbitrary positional arguments supplied via the
1521 :attr:`~Option.callback_args` option attribute.
Georg Brandl116aa622007-08-15 14:28:22 +00001522
1523``kwargs``
Georg Brandl15a515f2009-09-17 22:11:49 +00001524 is a dictionary of arbitrary keyword arguments supplied via
1525 :attr:`~Option.callback_kwargs`.
Georg Brandl116aa622007-08-15 14:28:22 +00001526
1527
1528.. _optparse-raising-errors-in-callback:
1529
1530Raising errors in a callback
1531^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1532
Georg Brandl15a515f2009-09-17 22:11:49 +00001533The callback function should raise :exc:`OptionValueError` if there are any
1534problems with the option or its argument(s). :mod:`optparse` catches this and
1535terminates the program, printing the error message you supply to stderr. Your
1536message should be clear, concise, accurate, and mention the option at fault.
1537Otherwise, the user will have a hard time figuring out what he did wrong.
Georg Brandl116aa622007-08-15 14:28:22 +00001538
1539
1540.. _optparse-callback-example-1:
1541
1542Callback example 1: trivial callback
1543^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1544
1545Here's an example of a callback option that takes no arguments, and simply
1546records that the option was seen::
1547
1548 def record_foo_seen(option, opt_str, value, parser):
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001549 parser.values.saw_foo = True
Georg Brandl116aa622007-08-15 14:28:22 +00001550
1551 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1552
Georg Brandl15a515f2009-09-17 22:11:49 +00001553Of course, you could do that with the ``"store_true"`` action.
Georg Brandl116aa622007-08-15 14:28:22 +00001554
1555
1556.. _optparse-callback-example-2:
1557
1558Callback example 2: check option order
1559^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1560
1561Here's a slightly more interesting example: record the fact that ``"-a"`` is
1562seen, but blow up if it comes after ``"-b"`` in the command-line. ::
1563
1564 def check_order(option, opt_str, value, parser):
1565 if parser.values.b:
1566 raise OptionValueError("can't use -a after -b")
1567 parser.values.a = 1
1568 [...]
1569 parser.add_option("-a", action="callback", callback=check_order)
1570 parser.add_option("-b", action="store_true", dest="b")
1571
1572
1573.. _optparse-callback-example-3:
1574
1575Callback example 3: check option order (generalized)
1576^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1577
1578If you want to re-use this callback for several similar options (set a flag, but
1579blow up if ``"-b"`` has already been seen), it needs a bit of work: the error
1580message and the flag that it sets must be generalized. ::
1581
1582 def check_order(option, opt_str, value, parser):
1583 if parser.values.b:
1584 raise OptionValueError("can't use %s after -b" % opt_str)
1585 setattr(parser.values, option.dest, 1)
1586 [...]
1587 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1588 parser.add_option("-b", action="store_true", dest="b")
1589 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1590
1591
1592.. _optparse-callback-example-4:
1593
1594Callback example 4: check arbitrary condition
1595^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1596
1597Of course, you could put any condition in there---you're not limited to checking
1598the values of already-defined options. For example, if you have options that
1599should not be called when the moon is full, all you have to do is this::
1600
1601 def check_moon(option, opt_str, value, parser):
1602 if is_moon_full():
1603 raise OptionValueError("%s option invalid when moon is full"
1604 % opt_str)
1605 setattr(parser.values, option.dest, 1)
1606 [...]
1607 parser.add_option("--foo",
1608 action="callback", callback=check_moon, dest="foo")
1609
1610(The definition of ``is_moon_full()`` is left as an exercise for the reader.)
1611
1612
1613.. _optparse-callback-example-5:
1614
1615Callback example 5: fixed arguments
1616^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1617
1618Things get slightly more interesting when you define callback options that take
1619a fixed number of arguments. Specifying that a callback option takes arguments
Georg Brandl15a515f2009-09-17 22:11:49 +00001620is similar to defining a ``"store"`` or ``"append"`` option: if you define
1621:attr:`~Option.type`, then the option takes one argument that must be
1622convertible to that type; if you further define :attr:`~Option.nargs`, then the
1623option takes :attr:`~Option.nargs` arguments.
Georg Brandl116aa622007-08-15 14:28:22 +00001624
Georg Brandl15a515f2009-09-17 22:11:49 +00001625Here's an example that just emulates the standard ``"store"`` action::
Georg Brandl116aa622007-08-15 14:28:22 +00001626
1627 def store_value(option, opt_str, value, parser):
1628 setattr(parser.values, option.dest, value)
1629 [...]
1630 parser.add_option("--foo",
1631 action="callback", callback=store_value,
1632 type="int", nargs=3, dest="foo")
1633
1634Note that :mod:`optparse` takes care of consuming 3 arguments and converting
1635them to integers for you; all you have to do is store them. (Or whatever;
1636obviously you don't need a callback for this example.)
1637
1638
1639.. _optparse-callback-example-6:
1640
1641Callback example 6: variable arguments
1642^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1643
1644Things get hairy when you want an option to take a variable number of arguments.
1645For this case, you must write a callback, as :mod:`optparse` doesn't provide any
1646built-in capabilities for it. And you have to deal with certain intricacies of
1647conventional Unix command-line parsing that :mod:`optparse` normally handles for
1648you. In particular, callbacks should implement the conventional rules for bare
1649``"--"`` and ``"-"`` arguments:
1650
1651* either ``"--"`` or ``"-"`` can be option arguments
1652
1653* bare ``"--"`` (if not the argument to some option): halt command-line
1654 processing and discard the ``"--"``
1655
1656* bare ``"-"`` (if not the argument to some option): halt command-line
1657 processing but keep the ``"-"`` (append it to ``parser.largs``)
1658
1659If you want an option that takes a variable number of arguments, there are
1660several subtle, tricky issues to worry about. The exact implementation you
1661choose will be based on which trade-offs you're willing to make for your
1662application (which is why :mod:`optparse` doesn't support this sort of thing
1663directly).
1664
1665Nevertheless, here's a stab at a callback for an option with variable
1666arguments::
1667
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001668 def vararg_callback(option, opt_str, value, parser):
1669 assert value is None
1670 value = []
Georg Brandl116aa622007-08-15 14:28:22 +00001671
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001672 def floatable(str):
1673 try:
1674 float(str)
1675 return True
1676 except ValueError:
1677 return False
Georg Brandl116aa622007-08-15 14:28:22 +00001678
Benjamin Peterson6ebe78f2008-12-21 00:06:59 +00001679 for arg in parser.rargs:
1680 # stop on --foo like options
1681 if arg[:2] == "--" and len(arg) > 2:
1682 break
1683 # stop on -a, but not on -3 or -3.0
1684 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
1685 break
1686 value.append(arg)
1687
1688 del parser.rargs[:len(value)]
Benjamin Peterson5c6d7872009-02-06 02:40:07 +00001689 setattr(parser.values, option.dest, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001690
1691 [...]
Benjamin Petersonae5360b2008-09-08 23:05:23 +00001692 parser.add_option("-c", "--callback", dest="vararg_attr",
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001693 action="callback", callback=vararg_callback)
Georg Brandl116aa622007-08-15 14:28:22 +00001694
Georg Brandl116aa622007-08-15 14:28:22 +00001695
1696.. _optparse-extending-optparse:
1697
1698Extending :mod:`optparse`
1699-------------------------
1700
1701Since the two major controlling factors in how :mod:`optparse` interprets
1702command-line options are the action and type of each option, the most likely
1703direction of extension is to add new actions and new types.
1704
1705
1706.. _optparse-adding-new-types:
1707
1708Adding new types
1709^^^^^^^^^^^^^^^^
1710
1711To add new types, you need to define your own subclass of :mod:`optparse`'s
Georg Brandl15a515f2009-09-17 22:11:49 +00001712:class:`Option` class. This class has a couple of attributes that define
1713:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.
Georg Brandl116aa622007-08-15 14:28:22 +00001714
Georg Brandl15a515f2009-09-17 22:11:49 +00001715.. attribute:: Option.TYPES
Georg Brandl116aa622007-08-15 14:28:22 +00001716
Georg Brandl15a515f2009-09-17 22:11:49 +00001717 A tuple of type names; in your subclass, simply define a new tuple
1718 :attr:`TYPES` that builds on the standard one.
Georg Brandl116aa622007-08-15 14:28:22 +00001719
Georg Brandl15a515f2009-09-17 22:11:49 +00001720.. attribute:: Option.TYPE_CHECKER
Georg Brandl116aa622007-08-15 14:28:22 +00001721
Georg Brandl15a515f2009-09-17 22:11:49 +00001722 A dictionary mapping type names to type-checking functions. A type-checking
1723 function has the following signature::
Georg Brandl116aa622007-08-15 14:28:22 +00001724
Georg Brandl15a515f2009-09-17 22:11:49 +00001725 def check_mytype(option, opt, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001726
Georg Brandl15a515f2009-09-17 22:11:49 +00001727 where ``option`` is an :class:`Option` instance, ``opt`` is an option string
1728 (e.g., ``"-f"``), and ``value`` is the string from the command line that must
1729 be checked and converted to your desired type. ``check_mytype()`` should
1730 return an object of the hypothetical type ``mytype``. The value returned by
1731 a type-checking function will wind up in the OptionValues instance returned
1732 by :meth:`OptionParser.parse_args`, or be passed to a callback as the
1733 ``value`` parameter.
1734
1735 Your type-checking function should raise :exc:`OptionValueError` if it
1736 encounters any problems. :exc:`OptionValueError` takes a single string
1737 argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
1738 method, which in turn prepends the program name and the string ``"error:"``
1739 and prints everything to stderr before terminating the process.
1740
1741Here's a silly example that demonstrates adding a ``"complex"`` option type to
Georg Brandl116aa622007-08-15 14:28:22 +00001742parse Python-style complex numbers on the command line. (This is even sillier
1743than it used to be, because :mod:`optparse` 1.3 added built-in support for
1744complex numbers, but never mind.)
1745
1746First, the necessary imports::
1747
1748 from copy import copy
1749 from optparse import Option, OptionValueError
1750
1751You need to define your type-checker first, since it's referred to later (in the
Georg Brandl15a515f2009-09-17 22:11:49 +00001752:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::
Georg Brandl116aa622007-08-15 14:28:22 +00001753
1754 def check_complex(option, opt, value):
1755 try:
1756 return complex(value)
1757 except ValueError:
1758 raise OptionValueError(
1759 "option %s: invalid complex value: %r" % (opt, value))
1760
1761Finally, the Option subclass::
1762
1763 class MyOption (Option):
1764 TYPES = Option.TYPES + ("complex",)
1765 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1766 TYPE_CHECKER["complex"] = check_complex
1767
1768(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
Georg Brandl15a515f2009-09-17 22:11:49 +00001769up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
1770Option class. This being Python, nothing stops you from doing that except good
1771manners and common sense.)
Georg Brandl116aa622007-08-15 14:28:22 +00001772
1773That's it! Now you can write a script that uses the new option type just like
1774any other :mod:`optparse`\ -based script, except you have to instruct your
1775OptionParser to use MyOption instead of Option::
1776
1777 parser = OptionParser(option_class=MyOption)
1778 parser.add_option("-c", type="complex")
1779
1780Alternately, you can build your own option list and pass it to OptionParser; if
1781you don't use :meth:`add_option` in the above way, you don't need to tell
1782OptionParser which option class to use::
1783
1784 option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1785 parser = OptionParser(option_list=option_list)
1786
1787
1788.. _optparse-adding-new-actions:
1789
1790Adding new actions
1791^^^^^^^^^^^^^^^^^^
1792
1793Adding new actions is a bit trickier, because you have to understand that
1794:mod:`optparse` has a couple of classifications for actions:
1795
1796"store" actions
1797 actions that result in :mod:`optparse` storing a value to an attribute of the
Georg Brandl15a515f2009-09-17 22:11:49 +00001798 current OptionValues instance; these options require a :attr:`~Option.dest`
1799 attribute to be supplied to the Option constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001800
1801"typed" actions
Georg Brandl15a515f2009-09-17 22:11:49 +00001802 actions that take a value from the command line and expect it to be of a
1803 certain type; or rather, a string that can be converted to a certain type.
1804 These options require a :attr:`~Option.type` attribute to the Option
1805 constructor.
Georg Brandl116aa622007-08-15 14:28:22 +00001806
Georg Brandl15a515f2009-09-17 22:11:49 +00001807These are overlapping sets: some default "store" actions are ``"store"``,
1808``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
1809actions are ``"store"``, ``"append"``, and ``"callback"``.
Georg Brandl116aa622007-08-15 14:28:22 +00001810
1811When you add an action, you need to categorize it by listing it in at least one
1812of the following class attributes of Option (all are lists of strings):
1813
Georg Brandl15a515f2009-09-17 22:11:49 +00001814.. attribute:: Option.ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001815
Georg Brandl15a515f2009-09-17 22:11:49 +00001816 All actions must be listed in ACTIONS.
Georg Brandl116aa622007-08-15 14:28:22 +00001817
Georg Brandl15a515f2009-09-17 22:11:49 +00001818.. attribute:: Option.STORE_ACTIONS
Georg Brandl116aa622007-08-15 14:28:22 +00001819
Georg Brandl15a515f2009-09-17 22:11:49 +00001820 "store" actions are additionally listed here.
1821
1822.. attribute:: Option.TYPED_ACTIONS
1823
1824 "typed" actions are additionally listed here.
1825
1826.. attribute:: Option.ALWAYS_TYPED_ACTIONS
1827
1828 Actions that always take a type (i.e. whose options always take a value) are
Georg Brandl116aa622007-08-15 14:28:22 +00001829 additionally listed here. The only effect of this is that :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001830 assigns the default type, ``"string"``, to options with no explicit type
1831 whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001832
1833In order to actually implement your new action, you must override Option's
1834:meth:`take_action` method and add a case that recognizes your action.
1835
Georg Brandl15a515f2009-09-17 22:11:49 +00001836For example, let's add an ``"extend"`` action. This is similar to the standard
1837``"append"`` action, but instead of taking a single value from the command-line
1838and appending it to an existing list, ``"extend"`` will take multiple values in
1839a single comma-delimited string, and extend an existing list with them. That
1840is, if ``"--names"`` is an ``"extend"`` option of type ``"string"``, the command
1841line ::
Georg Brandl116aa622007-08-15 14:28:22 +00001842
1843 --names=foo,bar --names blah --names ding,dong
1844
1845would result in a list ::
1846
1847 ["foo", "bar", "blah", "ding", "dong"]
1848
1849Again we define a subclass of Option::
1850
1851 class MyOption (Option):
1852
1853 ACTIONS = Option.ACTIONS + ("extend",)
1854 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1855 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1856 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1857
1858 def take_action(self, action, dest, opt, value, values, parser):
1859 if action == "extend":
1860 lvalue = value.split(",")
1861 values.ensure_value(dest, []).extend(lvalue)
1862 else:
1863 Option.take_action(
1864 self, action, dest, opt, value, values, parser)
1865
1866Features of note:
1867
Georg Brandl15a515f2009-09-17 22:11:49 +00001868* ``"extend"`` both expects a value on the command-line and stores that value
1869 somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
1870 :attr:`~Option.TYPED_ACTIONS`.
Georg Brandl116aa622007-08-15 14:28:22 +00001871
Georg Brandl15a515f2009-09-17 22:11:49 +00001872* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
1873 ``"extend"`` actions, we put the ``"extend"`` action in
1874 :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.
Georg Brandl116aa622007-08-15 14:28:22 +00001875
1876* :meth:`MyOption.take_action` implements just this one new action, and passes
1877 control back to :meth:`Option.take_action` for the standard :mod:`optparse`
Georg Brandl15a515f2009-09-17 22:11:49 +00001878 actions.
Georg Brandl116aa622007-08-15 14:28:22 +00001879
Georg Brandl15a515f2009-09-17 22:11:49 +00001880* ``values`` is an instance of the optparse_parser.Values class, which provides
1881 the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
1882 essentially :func:`getattr` with a safety valve; it is called as ::
Georg Brandl116aa622007-08-15 14:28:22 +00001883
1884 values.ensure_value(attr, value)
1885
1886 If the ``attr`` attribute of ``values`` doesn't exist or is None, then
Georg Brandl15a515f2009-09-17 22:11:49 +00001887 ensure_value() first sets it to ``value``, and then returns 'value. This is
1888 very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
1889 of which accumulate data in a variable and expect that variable to be of a
1890 certain type (a list for the first two, an integer for the latter). Using
Georg Brandl116aa622007-08-15 14:28:22 +00001891 :meth:`ensure_value` means that scripts using your action don't have to worry
Georg Brandl15a515f2009-09-17 22:11:49 +00001892 about setting a default value for the option destinations in question; they
1893 can just leave the default as None and :meth:`ensure_value` will take care of
Georg Brandl116aa622007-08-15 14:28:22 +00001894 getting it right when it's needed.