blob: 026239ed48295b9b05a9a65ff167b67d0d21779d [file] [log] [blame]
Neal Norwitz488609e2003-01-06 16:51:37 +00001\section{\module{optparse} ---
2 Powerful parser for command line options.}
3
4\declaremodule{standard}{optparse}
5\moduleauthor{Greg Ward}{gward@python.net}
6\sectionauthor{Johannes Gijsbers}{jlgijsbers@users.sf.net}
7\sectionauthor{Greg Ward}{gward@python.net}
8
9\modulesynopsis{Powerful, flexible, extensible, easy-to-use command-line
10 parsing library.}
11
12\versionadded{2.3}
13
14The \module{optparse} module is a powerful, flexible, extensible,
15easy-to-use command-line parsing library for Python. Using
16\module{optparse}, you can add intelligent, sophisticated handling of
17command-line options to your scripts with very little overhead.
18
19Here's an example of using \module{optparse} to add some command-line
20options to a simple script:
21
22\begin{verbatim}
23from optparse import OptionParser
Fred Drakecf6d74a2003-04-18 15:50:13 +000024
Neal Norwitz488609e2003-01-06 16:51:37 +000025parser = OptionParser()
26parser.add_option("-f", "--file", dest="filename",
27 help="write report to FILE", metavar="FILE")
28parser.add_option("-q", "--quiet",
Greg Ward1f535172003-05-03 20:13:08 +000029 action="store_false", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +000030 help="don't print status messages to stdout")
31
32(options, args) = parser.parse_args()
33\end{verbatim}
34
35With these few lines of code, users of your script can now do the
Greg Wardbf8f1b52003-05-03 19:41:45 +000036``usual thing'' on the command-line:
Neal Norwitz488609e2003-01-06 16:51:37 +000037
38\begin{verbatim}
39$ <yourscript> -f outfile --quiet
40$ <yourscript> -qfoutfile
41$ <yourscript> --file=outfile -q
42$ <yourscript> --quiet --file outfile
43\end{verbatim}
44
45(All of these result in \code{options.filename == "outfile"} and
Greg Ward1f535172003-05-03 20:13:08 +000046\code{options.verbose == False}, just as you might expect.)
Neal Norwitz488609e2003-01-06 16:51:37 +000047
48Even niftier, users can run one of
49\begin{verbatim}
50$ <yourscript> -h
51$ <yourscript> --help
52\end{verbatim}
53and \module{optparse} will print out a brief summary of your script's
54options:
55
56\begin{verbatim}
57usage: <yourscript> [options]
58
59options:
60 -h, --help show this help message and exit
61 -fFILE, --file=FILE write report to FILE
62 -q, --quiet don't print status messages to stdout
63\end{verbatim}
64
65That's just a taste of the flexibility \module{optparse} gives you in
66parsing your command-line.
67
Greg Ward649625b2003-05-03 20:41:37 +000068\subsection{Philosophy\label{optparse-philosophy}}
Neal Norwitz488609e2003-01-06 16:51:37 +000069
Greg Ward649625b2003-05-03 20:41:37 +000070The purpose of \module{optparse} is to make it very easy to provide the
71most standard, obvious, straightforward, and user-friendly user
72interface for \UNIX{} command-line programs. The \module{optparse}
73philosophy is heavily influenced by the \UNIX{} and GNU toolkits, and
74this section is meant to explain that philosophy.
Neal Norwitz488609e2003-01-06 16:51:37 +000075
76\subsubsection{Terminology\label{optparse-terminology}}
77
78First, we need to establish some terminology.
79
80\begin{definitions}
81\term{argument}
82a chunk of text that a user enters on the command-line, and that the
83shell passes to \cfunction{execl()} or \cfunction{execv()}. In
84Python, arguments are elements of
85\var{sys.argv[1:]}. (\var{sys.argv[0]} is the name of the program
86being executed; in the context of parsing arguments, it's not very
Fred Drakecf6d74a2003-04-18 15:50:13 +000087important.) \UNIX{} shells also use the term ``word''.
Neal Norwitz488609e2003-01-06 16:51:37 +000088
Greg Ward649625b2003-05-03 20:41:37 +000089It is occasionally desirable to use an argument list other than
90\var{sys.argv[1:]}, so you should read ``argument'' as ``an element of
Neal Norwitz488609e2003-01-06 16:51:37 +000091\var{sys.argv[1:]}, or of some other list provided as a substitute for
92\var{sys.argv[1:]}''.
93
94\term{option}
95 an argument used to supply extra information to guide or customize
96 the execution of a program. There are many different syntaxes for
Fred Drakecf6d74a2003-04-18 15:50:13 +000097 options; the traditional \UNIX{} syntax is \programopt{-} followed by a
Neal Norwitz488609e2003-01-06 16:51:37 +000098 single letter, e.g. \programopt{-x} or \programopt{-F}. Also,
Fred Drakecf6d74a2003-04-18 15:50:13 +000099 traditional \UNIX{} syntax allows multiple options to be merged into a
Neal Norwitz488609e2003-01-06 16:51:37 +0000100 single argument, e.g. \programopt{-x -F} is equivalent to
101 \programopt{-xF}. The GNU project introduced \longprogramopt{}
102 followed by a series of hyphen-separated words,
103 e.g. \longprogramopt{file} or \longprogramopt{dry-run}. These are
104 the only two option syntaxes provided by \module{optparse}.
105
106 Some other option syntaxes that the world has seen include:
107
108\begin{itemize}
109\item a hyphen followed by a few letters, e.g. \programopt{-pf} (this is
Greg Wardb4e33192003-05-03 19:16:36 +0000110 \emph{not} the same as multiple options merged into a single
Neal Norwitz488609e2003-01-06 16:51:37 +0000111 argument.)
112\item a hyphen followed by a whole word, e.g. \programopt{-file} (this is
113 technically equivalent to the previous syntax, but they aren't
114 usually seen in the same program.)
115\item a plus sign followed by a single letter, or a few letters,
116 or a word, e.g. \programopt{+f}, \programopt{+rgb}.
117\item a slash followed by a letter, or a few letters, or a word, e.g.
118 \programopt{/f}, \programopt{/file}.
119\end{itemize}
120
Greg Ward649625b2003-05-03 20:41:37 +0000121\module{optparse} does not support these option syntaxes, and it never
122will. (If you really want to use one of those option syntaxes, you'll
123have to subclass \class{OptionParser} and override all the difficult
124bits. But please don't! \module{optparse} does things the traditional
125\UNIX/GNU way deliberately; the first three are non-standard anywhere,
126and the last one makes sense only if you're exclusively targeting
127MS-DOS/Windows and/or VMS.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000128
129\term{option argument}
130an argument that follows an option, is closely associated with that
131option, and is consumed from the argument list when the option is.
132Often, option arguments may also be included in the same argument as
133the option, e.g. :
134
135\begin{verbatim}
136 ["-f", "foo"]
137\end{verbatim}
138
139may be equivalent to:
140
141\begin{verbatim}
142 ["-ffoo"]
143\end{verbatim}
144
145(\module{optparse} supports this syntax.)
146
147Some options never take an argument. Some options always take an
148argument. Lots of people want an ``optional option arguments'' feature,
149meaning that some options will take an argument if they see it, and
150won't if they don't. This is somewhat controversial, because it makes
Greg Ward649625b2003-05-03 20:41:37 +0000151parsing ambiguous: if \programopt{-a} and \programopt{-b} are both
152options, and \programopt{-a} takes an optional argument, how do we
153interpret \programopt{-ab}? \module{optparse} does not support optional
154option arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +0000155
156\term{positional argument}
157something leftover in the argument list after options have been
Greg Ward649625b2003-05-03 20:41:37 +0000158parsed, i.e., after options and their arguments have been parsed and
Neal Norwitz488609e2003-01-06 16:51:37 +0000159removed from the argument list.
160
161\term{required option}
Greg Ward649625b2003-05-03 20:41:37 +0000162an option that must be supplied on the command-line. The phrase
163``required option'' is an oxymoron; the presence of ``required options''
164in a program is usually a sign of careless user interface design.
165\module{optparse} doesn't prevent you from implementing required
166options, but doesn't give you much help with it either. See ``Extending
167Examples'' (section~\ref{optparse-extending-examples}) for two ways to
168implement required options with \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000169
170\end{definitions}
171
172For example, consider this hypothetical command-line:
173
174\begin{verbatim}
175 prog -v --report /tmp/report.txt foo bar
176\end{verbatim}
177
178\programopt{-v} and \longprogramopt{report} are both options. Assuming
179the \longprogramopt{report} option takes one argument,
Greg Ward649625b2003-05-03 20:41:37 +0000180\code{/tmp/report.txt} is an option argument. \code{foo} and \code{bar}
181are positional arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +0000182
183\subsubsection{What are options for?\label{optparse-options}}
184
185Options are used to provide extra information to tune or customize the
Greg Ward649625b2003-05-03 20:41:37 +0000186execution of a program. In case it wasn't clear, options should be
Neal Norwitz488609e2003-01-06 16:51:37 +0000187\emph{optional}. A program should be able to run just fine with no
Fred Drakecf6d74a2003-04-18 15:50:13 +0000188options whatsoever. (Pick a random program from the \UNIX{} or GNU
Neal Norwitz488609e2003-01-06 16:51:37 +0000189toolsets. Can it run without any options at all and still make sense?
Fred Drakecf6d74a2003-04-18 15:50:13 +0000190The only exceptions I can think of are \program{find}, \program{tar},
Greg Wardbf8f1b52003-05-03 19:41:45 +0000191and \program{dd}---all of which are mutant oddballs that have been
Fred Drakecf6d74a2003-04-18 15:50:13 +0000192rightly criticized for their non-standard syntax and confusing
193interfaces.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000194
195Lots of people want their programs to have ``required options''.
196Think about it. If it's required, then it's \emph{not optional}! If
197there is a piece of information that your program absolutely requires
198in order to run successfully, that's what positional arguments are
199for. (However, if you insist on adding ``required options'' to your
Fred Drakecf6d74a2003-04-18 15:50:13 +0000200programs, look in ``Extending Examples''
201(section~\ref{optparse-extending-examples}) for two ways of
202implementing them with \module{optparse}.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000203
204Consider the humble \program{cp} utility, for copying files. It
205doesn't make much sense to try to copy files without supplying a
206destination and at least one source. Hence, \program{cp} fails if you
207run it with no arguments. However, it has a flexible, useful syntax
208that does not rely on options at all:
209
210\begin{verbatim}
211$ cp SOURCE DEST
212$ cp SOURCE ... DEST-DIR
213\end{verbatim}
214
215You can get pretty far with just that. Most \program{cp}
216implementations provide a bunch of options to tweak exactly how the
217files are copied: you can preserve mode and modification time, avoid
218following symlinks, ask before clobbering existing files, etc. But
219none of this distracts from the core mission of \program{cp}, which is
220to copy one file to another, or N files to another directory.
221
222\subsubsection{What are positional arguments for? \label{optparse-positional-arguments}}
223
224In case it wasn't clear from the above example: positional arguments
225are for those pieces of information that your program absolutely,
226positively requires to run.
227
228A good user interface should have as few absolute requirements as
229possible. If your program requires 17 distinct pieces of information in
230order to run successfully, it doesn't much matter \emph{how} you get that
Greg Wardbf8f1b52003-05-03 19:41:45 +0000231information from the user---most people will give up and walk away
Neal Norwitz488609e2003-01-06 16:51:37 +0000232before they successfully run the program. This applies whether the user
233interface is a command-line, a configuration file, a GUI, or whatever:
234if you make that many demands on your users, most of them will just give
235up.
236
237In short, try to minimize the amount of information that users are
Greg Wardbf8f1b52003-05-03 19:41:45 +0000238absolutely required to supply---use sensible defaults whenever
Neal Norwitz488609e2003-01-06 16:51:37 +0000239possible. Of course, you also want to make your programs reasonably
240flexible. That's what options are for. Again, it doesn't matter if
241they are entries in a config file, checkboxes in the ``Preferences''
Greg Wardbf8f1b52003-05-03 19:41:45 +0000242dialog of a GUI, or command-line options---the more options you
Neal Norwitz488609e2003-01-06 16:51:37 +0000243implement, the more flexible your program is, and the more complicated
244its implementation becomes. It's quite easy to overwhelm users (and
245yourself!) with too much flexibility, so be careful there.
246
247\subsection{Basic Usage\label{optparse-basic-usage}}
248
249While \module{optparse} is quite flexible and powerful, you don't have
250to jump through hoops or read reams of documentation to get it working
251in basic cases. This document aims to demonstrate some simple usage
252patterns that will get you started using \module{optparse} in your
253scripts.
254
255To parse a command line with \module{optparse}, you must create an
256\class{OptionParser} instance and populate it. Obviously, you'll have
257to import the \class{OptionParser} classes in any script that uses
258\module{optparse}:
259
260\begin{verbatim}
261from optparse import OptionParser
262\end{verbatim}
263
264Early on in the main program, create a parser:
265
266\begin{verbatim}
267parser = OptionParser()
268\end{verbatim}
269
270Then you can start populating the parser with options. Each option is
271really a set of synonymous option strings; most commonly, you'll have
Fred Drakecf6d74a2003-04-18 15:50:13 +0000272one short option string and one long option string ---
Neal Norwitz488609e2003-01-06 16:51:37 +0000273e.g. \programopt{-f} and \longprogramopt{file}:
274
275\begin{verbatim}
276parser.add_option("-f", "--file", ...)
277\end{verbatim}
278
279The interesting stuff, of course, is what comes after the option
Greg Wardd7231282003-05-03 21:22:58 +0000280strings. For now, we'll only cover four of the things you can put
Fred Drake3ec4dfd2003-05-09 18:18:46 +0000281there: \emph{action}, \emph{type}, \emph{dest} (destination), and
282\emph{help}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000283
Fred Drake3ec4dfd2003-05-09 18:18:46 +0000284\subsubsection{The \emph{store} action%
285 \label{optparse-store-action}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000286
287The action tells \module{optparse} what to do when it sees one of the
288option strings for this option on the command-line. For example, the
Fred Drake3ec4dfd2003-05-09 18:18:46 +0000289action \emph{store} means: take the next argument (or the remainder of
Neal Norwitz488609e2003-01-06 16:51:37 +0000290the current argument), ensure that it is of the correct type, and
291store it to your chosen destination.
292
Greg Wardbf8f1b52003-05-03 19:41:45 +0000293For example, let's fill in the ``...'' of that last option:
Neal Norwitz488609e2003-01-06 16:51:37 +0000294
295\begin{verbatim}
296parser.add_option("-f", "--file",
297 action="store", type="string", dest="filename")
298\end{verbatim}
299
300Now let's make up a fake command-line and ask \module{optparse} to
301parse it:
302
303\begin{verbatim}
304args = ["-f", "foo.txt"]
305(options, args) = parser.parse_args(args)
306\end{verbatim}
307
308(Note that if you don't pass an argument list to
309\function{parse_args()}, it automatically uses \var{sys.argv[1:]}.)
310
Greg Wardd7231282003-05-03 21:22:58 +0000311When \module{optparse} sees the \programopt{-f}, it consumes the next
Greg Wardbf8f1b52003-05-03 19:41:45 +0000312argument---\code{foo.txt}---and stores it in the \var{filename}
Neal Norwitz488609e2003-01-06 16:51:37 +0000313attribute of a special object. That object is the first return value
Fred Drakecf6d74a2003-04-18 15:50:13 +0000314from \function{parse_args()}, so:
Neal Norwitz488609e2003-01-06 16:51:37 +0000315
316\begin{verbatim}
317print options.filename
318\end{verbatim}
319
Greg Wardbf8f1b52003-05-03 19:41:45 +0000320will print \code{foo.txt}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000321
Greg Wardbf8f1b52003-05-03 19:41:45 +0000322Other option types supported by \module{optparse} are \code{int} and
323\code{float}. Here's an option that expects an integer argument:
Neal Norwitz488609e2003-01-06 16:51:37 +0000324
325\begin{verbatim}
326parser.add_option("-n", type="int", dest="num")
327\end{verbatim}
328
Greg Wardd7231282003-05-03 21:22:58 +0000329This example doesn't provide a long option, which is perfectly
330acceptable. It also doesn't specify the action---it defaults to
331``store''.
Neal Norwitz488609e2003-01-06 16:51:37 +0000332
Greg Wardd7231282003-05-03 21:22:58 +0000333Let's parse another fake command-line. This time, we'll jam the option
334argument right up against the option, since \programopt{-n42} (one
335argument) is equivalent to \programopt{-n 42} (two arguments).
Neal Norwitz488609e2003-01-06 16:51:37 +0000336
337\begin{verbatim}
338(options, args) = parser.parse_args(["-n42"])
339print options.num
340\end{verbatim}
341
Greg Wardd7231282003-05-03 21:22:58 +0000342This prints \code{42}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000343
344Trying out the ``float'' type is left as an exercise for the reader.
345
346If you don't specify a type, \module{optparse} assumes ``string''.
347Combined with the fact that the default action is ``store'', that
348means our first example can be a lot shorter:
349
350\begin{verbatim}
351parser.add_option("-f", "--file", dest="filename")
352\end{verbatim}
353
354If you don't supply a destination, \module{optparse} figures out a
355sensible default from the option strings: if the first long option
356string is \longprogramopt{foo-bar}, then the default destination is
357\var{foo_bar}. If there are no long option strings,
358\module{optparse} looks at the first short option: the default
359destination for \programopt{-f} is \var{f}.
360
Fred Drakecf6d74a2003-04-18 15:50:13 +0000361Adding types is fairly easy; please refer to
362section~\ref{optparse-adding-types}, ``Adding new types.''
Neal Norwitz488609e2003-01-06 16:51:37 +0000363
Fred Drake3ec4dfd2003-05-09 18:18:46 +0000364\subsubsection{Other \emph{store_*} actions%
365 \label{optparse-other-store-actions}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000366
Greg Wardbf8f1b52003-05-03 19:41:45 +0000367Flag options---set a variable to true or false when a particular
368option is seen---are quite common. \module{optparse} supports them
Neal Norwitz488609e2003-01-06 16:51:37 +0000369with two separate actions, ``store_true'' and ``store_false''. For
370example, you might have a \var{verbose} flag that is turned on with
371\programopt{-v} and off with \programopt{-q}:
372
373\begin{verbatim}
374parser.add_option("-v", action="store_true", dest="verbose")
375parser.add_option("-q", action="store_false", dest="verbose")
376\end{verbatim}
377
378Here we have two different options with the same destination, which is
379perfectly OK. (It just means you have to be a bit careful when setting
Greg Wardbf8f1b52003-05-03 19:41:45 +0000380default values---see below.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000381
Greg Wardd7231282003-05-03 21:22:58 +0000382When \module{optparse} sees \programopt{-v} on the command line, it sets
383\var{options.verbose} to \code{True}; when it sees \programopt{-q}, it
384sets \var{options.verbose} to \code{False}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000385
386\subsubsection{Setting default values\label{optparse-setting-default-values}}
387
388All of the above examples involve setting some variable (the
389``destination'') when certain command-line options are seen. What
390happens if those options are never seen? Since we didn't supply any
Greg Wardd7231282003-05-03 21:22:58 +0000391defaults, they are all set to \code{None}. Sometimes, this is just fine (which
392is why it's the default), but sometimes, you want more control. To
393address that need, \module{optparse} lets you supply a default value for
394each destination, which is assigned before the command-line is parsed.
Neal Norwitz488609e2003-01-06 16:51:37 +0000395
396First, consider the verbose/quiet example. If we want
Greg Ward1f535172003-05-03 20:13:08 +0000397\module{optparse} to set \var{verbose} to \code{True} unless
398\programopt{-q} is seen, then we can do this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000399
400\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000401parser.add_option("-v", action="store_true", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000402parser.add_option("-q", action="store_false", dest="verbose")
403\end{verbatim}
404
405Oddly enough, this is exactly equivalent:
406
407\begin{verbatim}
408parser.add_option("-v", action="store_true", dest="verbose")
Greg Ward1f535172003-05-03 20:13:08 +0000409parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000410\end{verbatim}
411
412Those are equivalent because you're supplying a default value for the
413option's \emph{destination}, and these two options happen to have the same
414destination (the \var{verbose} variable).
415
416Consider this:
417
418\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000419parser.add_option("-v", action="store_true", dest="verbose", default=False)
420parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000421\end{verbatim}
422
Greg Ward1f535172003-05-03 20:13:08 +0000423Again, the default value for \var{verbose} will be \code{True}: the last
Greg Wardd7231282003-05-03 21:22:58 +0000424default value supplied for any particular destination is the one that
425counts.
Neal Norwitz488609e2003-01-06 16:51:37 +0000426
427\subsubsection{Generating help\label{optparse-generating-help}}
428
429The last feature that you will use in every script is
430\module{optparse}'s ability to generate help messages. All you have
431to do is supply a \var{help} value when you add an option. Let's
432create a new parser and populate it with user-friendly (documented)
433options:
434
435\begin{verbatim}
436usage = "usage: %prog [options] arg1 arg2"
437parser = OptionParser(usage=usage)
438parser.add_option("-v", "--verbose",
Greg Ward1f535172003-05-03 20:13:08 +0000439 action="store_true", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +0000440 help="make lots of noise [default]")
441parser.add_option("-q", "--quiet",
442 action="store_false", dest="verbose",
443 help="be vewwy quiet (I'm hunting wabbits)")
444parser.add_option("-f", "--file", dest="filename",
445 metavar="FILE", help="write output to FILE"),
446parser.add_option("-m", "--mode",
447 default="intermediate",
448 help="interaction mode: one of 'novice', "
449 "'intermediate' [default], 'expert'")
450\end{verbatim}
451
452If \module{optparse} encounters either \programopt{-h} or
Greg Wardb4e33192003-05-03 19:16:36 +0000453\longprogramopt{help} on the command-line, or if you just call
Neal Norwitz488609e2003-01-06 16:51:37 +0000454\method{parser.print_help()}, it prints the following to stdout:
455
456\begin{verbatim}
457usage: <yourscript> [options] arg1 arg2
458
459options:
460 -h, --help show this help message and exit
461 -v, --verbose make lots of noise [default]
462 -q, --quiet be vewwy quiet (I'm hunting wabbits)
463 -fFILE, --file=FILE write output to FILE
464 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
465 [default], 'expert'
466\end{verbatim}
467
468There's a lot going on here to help \module{optparse} generate the
469best possible help message:
470
471\begin{itemize}
472\item the script defines its own usage message:
473
474\begin{verbatim}
475usage = "usage: %prog [options] arg1 arg2"
476\end{verbatim}
477
Greg Wardbf8f1b52003-05-03 19:41:45 +0000478\module{optparse} expands \samp{\%prog} in the usage string to the name of the
Greg Wardd7231282003-05-03 21:22:58 +0000479current script, i.e. \code{os.path.basename(sys.argv[0])}. The
Neal Norwitz488609e2003-01-06 16:51:37 +0000480expanded string is then printed before the detailed option help.
481
482If you don't supply a usage string, \module{optparse} uses a bland but
Greg Wardbf8f1b52003-05-03 19:41:45 +0000483sensible default: \code{"usage: \%prog [options]"}, which is fine if your
Neal Norwitz488609e2003-01-06 16:51:37 +0000484script doesn't take any positional arguments.
485
486\item every option defines a help string, and doesn't worry about
Greg Wardbf8f1b52003-05-03 19:41:45 +0000487line-wrapping---\module{optparse} takes care of wrapping lines and
Neal Norwitz488609e2003-01-06 16:51:37 +0000488making the help output look good.
489
490\item options that take a value indicate this fact in their
491automatically-generated help message, e.g. for the ``mode'' option:
492
493\begin{verbatim}
494-mMODE, --mode=MODE
495\end{verbatim}
496
497Here, ``MODE'' is called the meta-variable: it stands for the argument
498that the user is expected to supply to
499\programopt{-m}/\longprogramopt{mode}. By default, \module{optparse}
500converts the destination variable name to uppercase and uses that for
Greg Wardbf8f1b52003-05-03 19:41:45 +0000501the meta-variable. Sometimes, that's not what you want---for
Neal Norwitz488609e2003-01-06 16:51:37 +0000502example, the \var{filename} option explicitly sets
503\code{metavar="FILE"}, resulting in this automatically-generated
504option description:
505
506\begin{verbatim}
507-fFILE, --file=FILE
508\end{verbatim}
509
510This is important for more than just saving space, though: the
511manually written help text uses the meta-variable ``FILE'', to clue
512the user in that there's a connection between the formal syntax
513``-fFILE'' and the informal semantic description ``write output to
514FILE''. This is a simple but effective way to make your help text a
515lot clearer and more useful for end users.
516\end{itemize}
517
Fred Drakecf6d74a2003-04-18 15:50:13 +0000518When dealing with many options, it is convenient to group these
519options for better help output. An \class{OptionParser} can contain
520several option groups, each of which can contain several options.
521
522Continuing with the parser defined above, adding an
523\class{OptionGroup} to a parser is easy:
524
525\begin{verbatim}
526group = OptionGroup(parser, "Dangerous Options",
Greg Wardd7231282003-05-03 21:22:58 +0000527 "Caution: use these options at your own risk. "
528 "It is believed that some of them bite.")
Fred Drakecf6d74a2003-04-18 15:50:13 +0000529group.add_option("-g", action="store_true", help="Group option.")
530parser.add_option_group(group)
531\end{verbatim}
532
533This would result in the following help output:
534
535\begin{verbatim}
536usage: [options] arg1 arg2
537
538options:
539 -h, --help show this help message and exit
540 -v, --verbose make lots of noise [default]
541 -q, --quiet be vewwy quiet (I'm hunting wabbits)
542 -fFILE, --file=FILE write output to FILE
543 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
544 [default], 'expert'
545
546 Dangerous Options:
547 Caution: use of these options is at your own risk. It is believed that
548 some of them bite.
549 -g Group option.
550\end{verbatim}
551
552
Neal Norwitz488609e2003-01-06 16:51:37 +0000553\subsubsection{Print a version number\label{optparse-print-version}}
554
555Similar to the brief usage string, \module{optparse} can also print a
556version string for your program. You have to supply the string, as
557the \var{version} argument to \class{OptionParser}:
558
559\begin{verbatim}
560parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
561\end{verbatim}
562
Greg Wardd7231282003-05-03 21:22:58 +0000563\var{version} can contain anything you like; \code{\%prog} is expanded
564in \var{version} just as with \var{usage}. When you supply it,
565\module{optparse} automatically adds a \longprogramopt{version} option
566to your parser. If it encounters this option on the command line, it
567expands your \var{version} string (by replacing \code{\%prog}), prints
568it to stdout, and exits.
Neal Norwitz488609e2003-01-06 16:51:37 +0000569
570For example, if your script is called /usr/bin/foo, a user might do:
571
572\begin{verbatim}
573$ /usr/bin/foo --version
574foo 1.0
Greg Wardd7231282003-05-03 21:22:58 +0000575\end{verbatim} % $ (avoid confusing emacs)
Neal Norwitz488609e2003-01-06 16:51:37 +0000576
577\subsubsection{Error-handling\label{optparse-error-handling}}
578
579The one thing you need to know for basic usage is how
580\module{optparse} behaves when it encounters an error on the
Greg Wardd7231282003-05-03 21:22:58 +0000581command-line---e.g. \programopt{-n 4x} where \programopt{-n} is an
582integer-valued option. In this case, \module{optparse} prints your
583usage message to stderr, followed by a useful and human-readable error
584message. Then it terminates (calls \function{sys.exit()}) with a
585non-zero exit status.
Neal Norwitz488609e2003-01-06 16:51:37 +0000586
587If you don't like this, subclass \class{OptionParser} and override the
Fred Drakecf6d74a2003-04-18 15:50:13 +0000588\method{error()} method. See section~\ref{optparse-extending},
589``Extending \module{optparse}.''
Neal Norwitz488609e2003-01-06 16:51:37 +0000590
591\subsubsection{Putting it all together\label{optparse-basic-summary}}
592
Greg Wardd7231282003-05-03 21:22:58 +0000593Here's what \module{optparse}-based scripts typically look like:
Neal Norwitz488609e2003-01-06 16:51:37 +0000594
595\begin{verbatim}
596from optparse import OptionParser
Greg Wardd7231282003-05-03 21:22:58 +0000597[...]
598def main():
599 usage = "usage: \%prog [-f] [-v] [-q] firstarg secondarg"
Neal Norwitz488609e2003-01-06 16:51:37 +0000600 parser = OptionParser(usage)
601 parser.add_option("-f", "--file", type="string", dest="filename",
602 help="read data from FILENAME")
603 parser.add_option("-v", "--verbose",
604 action="store_true", dest="verbose")
605 parser.add_option("-q", "--quiet",
606 action="store_false", dest="verbose")
Neal Norwitz488609e2003-01-06 16:51:37 +0000607
608 (options, args) = parser.parse_args()
609 if len(args) != 1:
610 parser.error("incorrect number of arguments")
611
612 if options.verbose:
Greg Wardd7231282003-05-03 21:22:58 +0000613 print "reading \%s..." \% options.filename
614 [... go to work ...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000615
616if __name__ == "__main__":
617 main()
618\end{verbatim}
619
620\subsection{Advanced Usage\label{optparse-advanced-usage}}
621
Fred Drakecf6d74a2003-04-18 15:50:13 +0000622\subsubsection{Creating and populating the
623 parser\label{optparse-creating-the-parser}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000624
625There are several ways to populate the parser with options. One way
626is to pass a list of \class{Options} to the \class{OptionParser}
627constructor:
628
629\begin{verbatim}
Greg Wardd7231282003-05-03 21:22:58 +0000630from optparse import OptionParser, make_option
631[...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000632parser = OptionParser(option_list=[
633 make_option("-f", "--filename",
634 action="store", type="string", dest="filename"),
635 make_option("-q", "--quiet",
636 action="store_false", dest="verbose")])
637\end{verbatim}
638
Greg Wardd7231282003-05-03 21:22:58 +0000639(\function{make_option()} is a factory function for generating
640\class{Option} objects.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000641
Greg Wardd7231282003-05-03 21:22:58 +0000642For long option lists, it may be more convenient/readable to create the
Neal Norwitz488609e2003-01-06 16:51:37 +0000643list separately:
644
645\begin{verbatim}
646option_list = [make_option("-f", "--filename",
647 action="store", type="string", dest="filename"),
Greg Wardd7231282003-05-03 21:22:58 +0000648 [... more options ...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000649 make_option("-q", "--quiet",
650 action="store_false", dest="verbose")]
651parser = OptionParser(option_list=option_list)
652\end{verbatim}
653
654Or, you can use the \method{add_option()} method of
655\class{OptionParser} to add options one-at-a-time:
656
657\begin{verbatim}
658parser = OptionParser()
659parser.add_option("-f", "--filename",
660 action="store", type="string", dest="filename")
661parser.add_option("-q", "--quiet",
662 action="store_false", dest="verbose")
663\end{verbatim}
664
665This method makes it easier to track down exceptions raised by the
666\class{Option} constructor, which are common because of the complicated
Greg Wardd7231282003-05-03 21:22:58 +0000667interdependencies among the various keyword arguments. (If you get it
668wrong, \module{optparse} raises \exception{OptionError}.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000669
670\method{add_option()} can be called in one of two ways:
671
672\begin{itemize}
673\item pass it an \class{Option} instance (as returned by \function{make_option()})
674\item pass it any combination of positional and keyword arguments that
Greg Wardd7231282003-05-03 21:22:58 +0000675are acceptable to \function{make_option()} (i.e., to the \class{Option}
Neal Norwitz488609e2003-01-06 16:51:37 +0000676constructor), and it will create the \class{Option} instance for you
677(shown above).
678\end{itemize}
679
680\subsubsection{Defining options\label{optparse-defining-options}}
681
682Each \class{Option} instance represents a set of synonymous
Greg Wardd7231282003-05-03 21:22:58 +0000683command-line options, i.e. options that have the same meaning and
Neal Norwitz488609e2003-01-06 16:51:37 +0000684effect, but different spellings. You can specify any number of short
685or long option strings, but you must specify at least one option
686string.
687
688To define an option with only a short option string:
689
690\begin{verbatim}
691make_option("-f", ...)
692\end{verbatim}
693
694And to define an option with only a long option string:
695
696\begin{verbatim}
697make_option("--foo", ...)
698\end{verbatim}
699
Greg Wardd7231282003-05-03 21:22:58 +0000700The ``...'' represents a set of keyword arguments that define attributes
701of the \class{Option} object. The rules governing which keyword args
702you must supply for a given \class{Option} are fairly complicated, but
703you always have to supply \emph{some}. If you get it wrong,
704\module{optparse} raises an \exception{OptionError} exception explaining
705your mistake.
Neal Norwitz488609e2003-01-06 16:51:37 +0000706
Greg Wardd7231282003-05-03 21:22:58 +0000707The most important attribute of an option is its action, i.e. what to do
Neal Norwitz488609e2003-01-06 16:51:37 +0000708when we encounter this option on the command-line. The possible actions
709are:
710
Greg Wardd7231282003-05-03 21:22:58 +0000711\begin{tableii}{l|l}{code}{Action}{Meaning}
712\lineii{store}{store this option's argument (default)}
713\lineii{store_const}{store a constant value}
714\lineii{store_true}{store a true value}
715\lineii{store_false}{store a false value}
716\lineii{append}{append this option's argument to a list}
717\lineii{count}{increment a counter by one}
718\lineii{callback}{call a specified function}
719\lineii{help}{print a usage message including all options and the
720 documentation for them}
721\end{tableii}
Neal Norwitz488609e2003-01-06 16:51:37 +0000722
723(If you don't supply an action, the default is ``store''. For this
724action, you may also supply \var{type} and \var{dest} keywords; see
725below.)
726
727As you can see, most actions involve storing or updating a value
728somewhere. \module{optparse} always creates a particular object (an
729instance of the \class{Values} class) specifically for this
730purpose. Option arguments (and various other values) are stored as
731attributes of this object, according to the \var{dest} (destination)
732argument to \function{make_option()}/\method{add_option()}.
733
734For example, when you call:
735
736\begin{verbatim}
737parser.parse_args()
738\end{verbatim}
739
740one of the first things \module{optparse} does is create a
741\var{values} object:
742
743\begin{verbatim}
744values = Values()
745\end{verbatim}
746
747If one of the options in this parser is defined with:
748
749\begin{verbatim}
750make_option("-f", "--file", action="store", type="string", dest="filename")
751\end{verbatim}
752
753and the command-line being parsed includes any of the following:
754
755\begin{verbatim}
756-ffoo
757-f foo
758--file=foo
759--file foo
760\end{verbatim}
761
762then \module{optparse}, on seeing the \programopt{-f} or
763\longprogramopt{file} option, will do the equivalent of this:
764
765\begin{verbatim}
766 values.filename = "foo"
767\end{verbatim}
768
Greg Wardd7231282003-05-03 21:22:58 +0000769Clearly, the \var{type} and \var{dest} arguments are almost
Neal Norwitz488609e2003-01-06 16:51:37 +0000770as important as \var{action}. \var{action} is the only attribute that
Greg Wardb4e33192003-05-03 19:16:36 +0000771is meaningful for \emph{all} options, though, so it is the most
772important.
Neal Norwitz488609e2003-01-06 16:51:37 +0000773
774\subsubsection{Option actions\label{optparse-option-actions}}
775
776The various option actions all have slightly different requirements
777and effects. Except for the ``help'' action, you must supply at least
778one other keyword argument when creating the \class{Option}; the exact
779requirements for each action are listed here.
780
781\begin{definitions}
782\term{store} [relevant: \var{type}, \var{dest}, \var{nargs}, \var{choices}]
783
784The option must be followed by an argument, which is converted to a
785value according to \var{type} and stored in \var{dest}. If
Greg Wardd7231282003-05-03 21:22:58 +0000786\code{nargs > 1}, multiple arguments will be consumed from the command
Neal Norwitz488609e2003-01-06 16:51:37 +0000787line; all will be converted according to \var{type} and stored to
Fred Drakecf6d74a2003-04-18 15:50:13 +0000788\var{dest} as a tuple. See section~\ref{optparse-option-types},
789``Option types'' below.
Neal Norwitz488609e2003-01-06 16:51:37 +0000790
Greg Wardd7231282003-05-03 21:22:58 +0000791If \var{choices} (a sequence of strings) is supplied, the type
Neal Norwitz488609e2003-01-06 16:51:37 +0000792defaults to ``choice''.
793
794If \var{type} is not supplied, it defaults to ``string''.
795
796If \var{dest} is not supplied, \module{optparse} derives a
797destination from the first long option strings (e.g.,
Greg Wardb4e33192003-05-03 19:16:36 +0000798\longprogramopt{foo-bar} becomes \var{foo_bar}). If there are no long
Neal Norwitz488609e2003-01-06 16:51:37 +0000799option strings, \module{optparse} derives a destination from the first
Greg Wardb4e33192003-05-03 19:16:36 +0000800short option string (e.g., \programopt{-f} becomes \var{f}).
Neal Norwitz488609e2003-01-06 16:51:37 +0000801
802Example:
803
804\begin{verbatim}
805make_option("-f")
806make_option("-p", type="float", nargs=3, dest="point")
807\end{verbatim}
808
809Given the following command line:
810
811\begin{verbatim}
812-f foo.txt -p 1 -3.5 4 -fbar.txt
813\end{verbatim}
814
815\module{optparse} will set:
816
817\begin{verbatim}
818values.f = "bar.txt"
819values.point = (1.0, -3.5, 4.0)
820\end{verbatim}
821
822(Actually, \member{values.f} will be set twice, but only the second
823time is visible in the end.)
824
825\term{store_const} [required: \var{const}, \var{dest}]
826
827The \var{const} value supplied to the \class{Option} constructor is
828stored in \var{dest}.
829
830Example:
831
832\begin{verbatim}
833make_option("-q", "--quiet",
834 action="store_const", const=0, dest="verbose"),
835make_option("-v", "--verbose",
836 action="store_const", const=1, dest="verbose"),
Greg Wardd7231282003-05-03 21:22:58 +0000837make_option("--noisy",
Neal Norwitz488609e2003-01-06 16:51:37 +0000838 action="store_const", const=2, dest="verbose"),
839\end{verbatim}
840
841If \longprogramopt{noisy} is seen, \module{optparse} will set:
842
843\begin{verbatim}
844values.verbose = 2
845\end{verbatim}
846
847\term{store_true} [required: \var{dest}]
848
Greg Ward1f535172003-05-03 20:13:08 +0000849A special case of ``store_const'' that stores \code{True} to \var{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000850
851\term{store_false} [required: \var{dest}]
852
Greg Wardd7231282003-05-03 21:22:58 +0000853Like ``store_true'', but stores \code{False}
Neal Norwitz488609e2003-01-06 16:51:37 +0000854
855Example:
856
857\begin{verbatim}
858make_option(None, "--clobber", action="store_true", dest="clobber")
859make_option(None, "--no-clobber", action="store_false", dest="clobber")
860\end{verbatim}
861
862\term{append} [relevant: \var{type}, \var{dest}, \var{nargs}, \var{choices}]
863
864The option must be followed by an argument, which is appended to the
865list in \var{dest}. If no default value for \var{dest} is supplied
Greg Wardd7231282003-05-03 21:22:58 +0000866(i.e. the default is \code{None}), an empty list is automatically created when
Neal Norwitz488609e2003-01-06 16:51:37 +0000867\module{optparse} first encounters this option on the command-line.
Greg Wardd7231282003-05-03 21:22:58 +0000868If \code{nargs > 1}, multiple arguments are consumed, and a tuple of
Neal Norwitz488609e2003-01-06 16:51:37 +0000869length \var{nargs} is appended to \var{dest}.
870
871The defaults for \var{type} and \var{dest} are the same as for the
872``store'' action.
873
874Example:
875
876\begin{verbatim}
877make_option("-t", "--tracks", action="append", type="int")
878\end{verbatim}
879
880If \programopt{-t3} is seen on the command-line, \module{optparse} does the equivalent of:
881
882\begin{verbatim}
883values.tracks = []
884values.tracks.append(int("3"))
885\end{verbatim}
886
Greg Wardb4e33192003-05-03 19:16:36 +0000887If, a little later on, \longprogramopt{tracks=4} is seen, it does:
Neal Norwitz488609e2003-01-06 16:51:37 +0000888
889\begin{verbatim}
890values.tracks.append(int("4"))
891\end{verbatim}
892
Fred Drakecf6d74a2003-04-18 15:50:13 +0000893See ``Error handling'' (section~\ref{optparse-error-handling}) for
Neal Norwitz488609e2003-01-06 16:51:37 +0000894information on how \module{optparse} deals with something like
Greg Wardb4e33192003-05-03 19:16:36 +0000895\longprogramopt{tracks=x}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000896
897\term{count} [required: \var{dest}]
898
899Increment the integer stored at \var{dest}. \var{dest} is set to zero
900before being incremented the first time (unless you supply a default
901value).
902
903Example:
904
905\begin{verbatim}
906make_option("-v", action="count", dest="verbosity")
907\end{verbatim}
908
909The first time \programopt{-v} is seen on the command line,
910\module{optparse} does the equivalent of:
911
912\begin{verbatim}
913values.verbosity = 0
914values.verbosity += 1
915\end{verbatim}
916
917Every subsequent occurrence of \programopt{-v} results in:
918
919\begin{verbatim}
920values.verbosity += 1
921\end{verbatim}
922
Greg Wardd7231282003-05-03 21:22:58 +0000923\term{callback} [required: \var{callback};
Neal Norwitz488609e2003-01-06 16:51:37 +0000924 relevant: \var{type}, \var{nargs}, \var{callback_args},
925 \var{callback_kwargs}]
926
927Call the function specified by \var{callback}. The signature of
928this function should be:
929
930\begin{verbatim}
931func(option : Option,
932 opt : string,
933 value : any,
934 parser : OptionParser,
935 *args, **kwargs)
936\end{verbatim}
937
Fred Drakecf6d74a2003-04-18 15:50:13 +0000938Callback options are covered in detail in
Greg Wardd7231282003-05-03 21:22:58 +0000939section~\ref{optparse-callback-options}, ``Callback Options.''
Neal Norwitz488609e2003-01-06 16:51:37 +0000940
941\term{help} [required: none]
942
943Prints a complete help message for all the options in the current
944option parser. The help message is constructed from the \var{usage}
945string passed to \class{OptionParser}'s constructor and the \var{help}
946string passed to every option.
947
948If no \var{help} string is supplied for an option, it will still be
949listed in the help message. To omit an option entirely, use the
950special value \constant{optparse.SUPPRESS_HELP}.
951
952Example:
953
954\begin{verbatim}
955from optparse import Option, OptionParser, SUPPRESS_HELP
956
957usage = "usage: %prog [options]"
958parser = OptionParser(usage, option_list=[
959 make_option("-h", "--help", action="help"),
960 make_option("-v", action="store_true", dest="verbose",
961 help="Be moderately verbose")
962 make_option("--file", dest="filename",
963 help="Input file to read data from"),
964 make_option("--secret", help=SUPPRESS_HELP)
965\end{verbatim}
966
Greg Wardb4e33192003-05-03 19:16:36 +0000967If \module{optparse} sees either \programopt{-h} or
968\longprogramopt{help} on the command line, it will print something
969like the following help message to stdout:
Neal Norwitz488609e2003-01-06 16:51:37 +0000970
971\begin{verbatim}
972usage: <yourscript> [options]
973
974options:
975 -h, --help Show this help message and exit
976 -v Be moderately verbose
977 --file=FILENAME Input file to read data from
978\end{verbatim}
979
980After printing the help message, \module{optparse} terminates your process
981with \code{sys.exit(0)}.
982
983\term{version} [required: none]
984
985Prints the version number supplied to the \class{OptionParser} to
986stdout and exits. The version number is actually formatted and
987printed by the \method{print_version()} method of
988\class{OptionParser}. Generally only relevant if the \var{version}
989argument is supplied to the \class{OptionParser} constructor.
990\end{definitions}
991
992\subsubsection{Option types\label{optparse-option-types}}
993
994\module{optparse} supports six option types out of the box: \dfn{string},
995\dfn{int}, \dfn{long}, \dfn{choice}, \dfn{float} and \dfn{complex}.
996(Of these, string, int, float, and choice are the most commonly used
Greg Wardd7231282003-05-03 21:22:58 +0000997---long and complex are there mainly for completeness.) It's easy to
Neal Norwitz488609e2003-01-06 16:51:37 +0000998add new option types by subclassing the \class{Option} class; see
Fred Drakecf6d74a2003-04-18 15:50:13 +0000999section~\ref{optparse-extending}, ``Extending \module{optparse}.''
Neal Norwitz488609e2003-01-06 16:51:37 +00001000
1001Arguments to string options are not checked or converted in any way:
1002the text on the command line is stored in the destination (or passed
1003to the callback) as-is.
1004
1005Integer arguments are passed to \function{int()} to convert them to
1006Python integers. If \function{int()} fails, so will
1007\module{optparse}, although with a more useful error message.
1008Internally, \module{optparse} raises \exception{OptionValueError} in
1009\function{optparse.check_builtin()}; at a higher level (in
Greg Wardd7231282003-05-03 21:22:58 +00001010\class{OptionParser}), \module{optparse} catches this exception and
1011terminates your program with a useful error message.
Neal Norwitz488609e2003-01-06 16:51:37 +00001012
1013Likewise, float arguments are passed to \function{float()} for
1014conversion, long arguments to \function{long()}, and complex arguments
1015to \function{complex()}. Apart from that, they are handled
1016identically to integer arguments.
1017
1018Choice options are a subtype of string options. A master list or
1019tuple of choices (strings) must be passed to the option constructor
1020(\function{make_option()} or \method{OptionParser.add_option()}) as
Greg Wardd7231282003-05-03 21:22:58 +00001021the \var{choices} keyword argument. Choice option arguments are
Neal Norwitz488609e2003-01-06 16:51:37 +00001022compared against this master list in
1023\function{optparse.check_choice()}, and \exception{OptionValueError}
1024is raised if an unknown string is given.
1025
1026\subsubsection{Querying and manipulating your option parser\label{optparse-querying-and-manipulating}}
1027
1028Sometimes, it's useful to poke around your option parser and see what's
1029there. \class{OptionParser} provides a couple of methods to help you out:
1030
1031\begin{methoddesc}{has_option}{opt_str}
1032 Given an option string such as \programopt{-q} or
1033 \longprogramopt{verbose}, returns true if the \class{OptionParser}
1034 has an option with that option string.
1035\end{methoddesc}
1036
1037\begin{methoddesc}{get_option}{opt_str}
1038 Returns the \class{Option} instance that implements the option
Greg Wardd7231282003-05-03 21:22:58 +00001039 string you supplied, or \code{None} if no options implement it.
Neal Norwitz488609e2003-01-06 16:51:37 +00001040\end{methoddesc}
1041
1042\begin{methoddesc}{remove_option}{opt_str}
1043 If the \class{OptionParser} has an option corresponding to
1044 \var{opt_str}, that option is removed. If that option provided
1045 any other option strings, all of those option strings become
1046 invalid.
1047
1048 If \var{opt_str} does not occur in any option belonging to this
1049 \class{OptionParser}, raises \exception{ValueError}.
1050\end{methoddesc}
1051
1052\subsubsection{Conflicts between options\label{optparse-conflicts}}
1053
1054If you're not careful, it's easy to define conflicting options:
1055
1056\begin{verbatim}
1057parser.add_option("-n", "--dry-run", ...)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001058...
Neal Norwitz488609e2003-01-06 16:51:37 +00001059parser.add_option("-n", "--noisy", ...)
1060\end{verbatim}
1061
1062(This is even easier to do if you've defined your own
1063\class{OptionParser} subclass with some standard options.)
1064
1065On the assumption that this is usually a mistake, \module{optparse}
Fred Drakecf6d74a2003-04-18 15:50:13 +00001066raises an exception (\exception{OptionConflictError}) by default when
1067this happens. Since this is an easily-fixed programming error, you
Greg Wardbf8f1b52003-05-03 19:41:45 +00001068shouldn't try to catch this exception---fix your mistake and get on
Fred Drakecf6d74a2003-04-18 15:50:13 +00001069with life.
Neal Norwitz488609e2003-01-06 16:51:37 +00001070
1071Sometimes, you want newer options to deliberately replace the option
1072strings used by older options. You can achieve this by calling:
1073
1074\begin{verbatim}
1075parser.set_conflict_handler("resolve")
1076\end{verbatim}
1077
1078which instructs \module{optparse} to resolve option conflicts
1079intelligently.
1080
1081Here's how it works: every time you add an option, \module{optparse}
1082checks for conflicts with previously-added options. If it finds any,
1083it invokes the conflict-handling mechanism you specify either to the
1084\class{OptionParser} constructor:
1085
1086\begin{verbatim}
1087parser = OptionParser(..., conflict_handler="resolve")
1088\end{verbatim}
1089
1090or via the \method{set_conflict_handler()} method.
1091
Greg Wardd7231282003-05-03 21:22:58 +00001092The default conflict-handling mechanism is \code{error}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001093
1094Here's an example: first, define an \class{OptionParser} set to
1095resolve conflicts intelligently:
1096
1097\begin{verbatim}
1098parser = OptionParser(conflict_handler="resolve")
1099\end{verbatim}
1100
1101Now add all of our options:
1102
1103\begin{verbatim}
1104parser.add_option("-n", "--dry-run", ..., help="original dry-run option")
Fred Drakecf6d74a2003-04-18 15:50:13 +00001105...
Neal Norwitz488609e2003-01-06 16:51:37 +00001106parser.add_option("-n", "--noisy", ..., help="be noisy")
1107\end{verbatim}
1108
1109At this point, \module{optparse} detects that a previously-added option is already
1110using the \programopt{-n} option string. Since \code{conflict_handler
1111== "resolve"}, it resolves the situation by removing \programopt{-n}
1112from the earlier option's list of option strings. Now,
1113\longprogramopt{dry-run} is the only way for the user to activate that
1114option. If the user asks for help, the help message will reflect
1115that, e.g.:
1116
1117\begin{verbatim}
1118options:
1119 --dry-run original dry-run option
Fred Drakecf6d74a2003-04-18 15:50:13 +00001120 ...
Neal Norwitz488609e2003-01-06 16:51:37 +00001121 -n, --noisy be noisy
1122\end{verbatim}
1123
1124Note that it's possible to whittle away the option strings for a
1125previously-added option until there are none left, and the user has no
1126way of invoking that option from the command-line. In that case,
1127\module{optparse} removes that option completely, so it doesn't show
1128up in help text or anywhere else. E.g. if we carry on with our
1129existing \class{OptionParser}:
1130
1131\begin{verbatim}
1132parser.add_option("--dry-run", ..., help="new dry-run option")
1133\end{verbatim}
1134
1135At this point, the first \programopt{-n}/\longprogramopt{dry-run}
1136option is no longer accessible, so \module{optparse} removes it. If
1137the user asks for help, they'll get something like this:
1138
1139\begin{verbatim}
1140options:
Fred Drakecf6d74a2003-04-18 15:50:13 +00001141 ...
Neal Norwitz488609e2003-01-06 16:51:37 +00001142 -n, --noisy be noisy
1143 --dry-run new dry-run option
1144\end{verbatim}
1145
1146\subsection{Callback Options\label{optparse-callback-options}}
1147
1148If \module{optparse}'s built-in actions and types just don't fit the
1149bill for you, but it's not worth extending \module{optparse} to define
1150your own actions or types, you'll probably need to define a callback
1151option. Defining callback options is quite easy; the tricky part is
1152writing a good callback (the function that is called when
1153\module{optparse} encounters the option on the command line).
1154
1155\subsubsection{Defining a callback option\label{optparse-defining-callback-option}}
1156
1157As always, you can define a callback option either by directly
1158instantiating the \class{Option} class, or by using the
1159\method{add_option()} method of your \class{OptionParser} object. The
1160only option attribute you must specify is \var{callback}, the function
1161to call:
1162
1163\begin{verbatim}
1164parser.add_option("-c", callback=my_callback)
1165\end{verbatim}
1166
Greg Wardbf8f1b52003-05-03 19:41:45 +00001167Note that you supply a function object here---so you must have
Neal Norwitz488609e2003-01-06 16:51:37 +00001168already defined a function \function{my_callback()} when you define
1169the callback option. In this simple case, \module{optparse} knows
1170nothing about the arguments the \programopt{-c} option expects to
1171take. Usually, this means that the option doesn't take any arguments
1172-- the mere presence of \programopt{-c} on the command-line is all it
1173needs to know. In some circumstances, though, you might want your
1174callback to consume an arbitrary number of command-line arguments.
1175This is where writing callbacks gets tricky; it's covered later in
1176this document.
1177
1178There are several other option attributes that you can supply when you
1179define an option attribute:
1180
1181\begin{definitions}
1182\term{type}
1183has its usual meaning: as with the ``store'' or ``append'' actions, it
1184instructs \module{optparse} to consume one argument that must be
1185convertible to \var{type}. Rather than storing the value(s) anywhere,
1186though, \module{optparse} converts it to \var{type} and passes it to
1187your callback function.
1188
1189\term{nargs}
1190also has its usual meaning: if it is supplied and \samp{nargs > 1},
1191\module{optparse} will consume \var{nargs} arguments, each of which
1192must be convertible to \var{type}. It then passes a tuple of
1193converted values to your callback.
1194
1195\term{callback_args}
1196a tuple of extra positional arguments to pass to the callback.
1197
1198\term{callback_kwargs}
1199a dictionary of extra keyword arguments to pass to the callback.
1200\end{definitions}
1201
1202\subsubsection{How callbacks are called\label{optparse-callbacks-called}}
1203
1204All callbacks are called as follows:
1205
1206\begin{verbatim}
1207func(option, opt, value, parser, *args, **kwargs)
1208\end{verbatim}
1209
1210where
1211
1212\begin{definitions}
1213\term{option}
1214is the \class{Option} instance that's calling the callback.
1215
1216\term{opt}
1217is the option string seen on the command-line that's triggering the
1218callback. (If an abbreviated long option was used, \var{opt} will be
Greg Wardbf8f1b52003-05-03 19:41:45 +00001219the full, canonical option string---e.g. if the user puts
Neal Norwitz488609e2003-01-06 16:51:37 +00001220\longprogramopt{foo} on the command-line as an abbreviation for
1221\longprogramopt{foobar}, then \var{opt} will be
1222\longprogramopt{foobar}.)
1223
1224\term{value}
1225is the argument to this option seen on the command-line.
1226\module{optparse} will only expect an argument if \var{type} is
1227set; the type of \var{value} will be the type implied by the
Fred Drakecf6d74a2003-04-18 15:50:13 +00001228option's type (see~\ref{optparse-option-types}, ``Option types''). If
Greg Wardd7231282003-05-03 21:22:58 +00001229\var{type} for this option is \code{None} (no argument expected), then
1230\var{value} will be \code{None}. If \samp{nargs > 1}, \var{value} will
Neal Norwitz488609e2003-01-06 16:51:37 +00001231be a tuple of values of the appropriate type.
1232
1233\term{parser}
1234is the \class{OptionParser} instance driving the whole thing, mainly
1235useful because you can access some other interesting data through it,
1236as instance attributes:
1237
1238\begin{definitions}
1239\term{parser.rargs}
Greg Wardd7231282003-05-03 21:22:58 +00001240the current remaining argument list, i.e. with \var{opt} (and
Neal Norwitz488609e2003-01-06 16:51:37 +00001241\var{value}, if any) removed, and only the arguments following
1242them still there. Feel free to modify \member{parser.rargs},
1243e.g. by consuming more arguments.
1244
1245\term{parser.largs}
Greg Wardd7231282003-05-03 21:22:58 +00001246the current set of leftover arguments, i.e. arguments that have been
Neal Norwitz488609e2003-01-06 16:51:37 +00001247processed but have not been consumed as options (or arguments to
1248options). Feel free to modify \member{parser.largs} e.g. by adding
1249more arguments to it.
1250
1251\term{parser.values}
1252the object where option values are by default stored. This is useful
1253because it lets callbacks use the same mechanism as the rest of
1254\module{optparse} for storing option values; you don't need to mess
1255around with globals or closures. You can also access the value(s) of
1256any options already encountered on the command-line.
1257\end{definitions}
1258
1259\term{args}
1260is a tuple of arbitrary positional arguments supplied via the
1261\var{callback}_args option attribute.
1262
1263\term{kwargs}
1264is a dictionary of arbitrary keyword arguments supplied via
1265\var{callback_kwargs}.
1266\end{definitions}
1267
1268Since \var{args} and \var{kwargs} are optional (they are only passed
1269if you supply \var{callback_args} and/or \var{callback_kwargs} when
1270you define your callback option), the minimal callback function is:
1271
1272\begin{verbatim}
1273def my_callback (option, opt, value, parser):
1274 pass
1275\end{verbatim}
1276
1277\subsubsection{Error handling\label{optparse-callback-error-handling}}
1278
1279The callback function should raise \exception{OptionValueError} if
1280there are any problems with the option or its
1281argument(s). \module{optparse} catches this and terminates the
1282program, printing the error message you supply to stderr. Your
1283message should be clear, concise, accurate, and mention the option at
1284fault. Otherwise, the user will have a hard time figuring out what he
1285did wrong.
1286
1287\subsubsection{Examples\label{optparse-callback-examples}}
1288
1289Here's an example of a callback option that takes no arguments, and
1290simply records that the option was seen:
1291
1292\begin{verbatim}
1293def record_foo_seen (option, opt, value, parser):
1294 parser.saw_foo = 1
1295
1296parser.add_option("--foo", action="callback", callback=record_foo_seen)
1297\end{verbatim}
1298
1299Of course, you could do that with the ``store_true'' action. Here's a
1300slightly more interesting example: record the fact that
1301\programopt{-a} is seen, but blow up if it comes after \programopt{-b}
1302in the command-line.
1303
1304\begin{verbatim}
1305def check_order (option, opt, value, parser):
1306 if parser.values.b:
1307 raise OptionValueError("can't use -a after -b")
1308 parser.values.a = 1
Fred Drakecf6d74a2003-04-18 15:50:13 +00001309...
Neal Norwitz488609e2003-01-06 16:51:37 +00001310parser.add_option("-a", action="callback", callback=check_order)
1311parser.add_option("-b", action="store_true", dest="b")
1312\end{verbatim}
1313
1314If you want to reuse this callback for several similar options (set a
1315flag, but blow up if \programopt{-b} has already been seen), it needs
1316a bit of work: the error message and the flag that it sets must be
1317generalized.
1318
1319\begin{verbatim}
1320def check_order (option, opt, value, parser):
1321 if parser.values.b:
1322 raise OptionValueError("can't use %s after -b" % opt)
1323 setattr(parser.values, option.dest, 1)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001324...
Neal Norwitz488609e2003-01-06 16:51:37 +00001325parser.add_option("-a", action="callback", callback=check_order, dest='a')
1326parser.add_option("-b", action="store_true", dest="b")
1327parser.add_option("-c", action="callback", callback=check_order, dest='c')
1328\end{verbatim}
1329
Greg Wardbf8f1b52003-05-03 19:41:45 +00001330Of course, you could put any condition in there---you're not limited
Neal Norwitz488609e2003-01-06 16:51:37 +00001331to checking the values of already-defined options. For example, if
1332you have options that should not be called when the moon is full, all
1333you have to do is this:
1334
1335\begin{verbatim}
1336def check_moon (option, opt, value, parser):
1337 if is_full_moon():
1338 raise OptionValueError("%s option invalid when moon full" % opt)
1339 setattr(parser.values, option.dest, 1)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001340...
Neal Norwitz488609e2003-01-06 16:51:37 +00001341parser.add_option("--foo",
1342 action="callback", callback=check_moon, dest="foo")
1343\end{verbatim}
1344
Greg Wardbf8f1b52003-05-03 19:41:45 +00001345(The definition of \code{is_full_moon()} is left as an exercise for the
Neal Norwitz488609e2003-01-06 16:51:37 +00001346reader.)
1347
1348\strong{Fixed arguments}
1349
1350Things get slightly more interesting when you define callback options
1351that take a fixed number of arguments. Specifying that a callback
1352option takes arguments is similar to defining a ``store'' or
1353``append'' option: if you define \var{type}, then the option takes one
1354argument that must be convertible to that type; if you further define
1355\var{nargs}, then the option takes that many arguments.
1356
1357Here's an example that just emulates the standard ``store'' action:
1358
1359\begin{verbatim}
1360def store_value (option, opt, value, parser):
1361 setattr(parser.values, option.dest, value)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001362...
Neal Norwitz488609e2003-01-06 16:51:37 +00001363parser.add_option("--foo",
1364 action="callback", callback=store_value,
1365 type="int", nargs=3, dest="foo")
1366\end{verbatim}
1367
1368Note that \module{optparse} takes care of consuming 3 arguments and
1369converting them to integers for you; all you have to do is store them.
1370(Or whatever: obviously you don't need a callback for this example.
1371Use your imagination!)
1372
1373\strong{Variable arguments}
1374
1375Things get hairy when you want an option to take a variable number of
1376arguments. For this case, you have to write a callback;
1377\module{optparse} doesn't provide any built-in capabilities for it.
Fred Drakecf6d74a2003-04-18 15:50:13 +00001378You have to deal with the full-blown syntax for conventional \UNIX{}
Neal Norwitz488609e2003-01-06 16:51:37 +00001379command-line parsing. (Previously, \module{optparse} took care of
1380this for you, but I got it wrong. It was fixed at the cost of making
1381this kind of callback more complex.) In particular, callbacks have to
1382worry about bare \longprogramopt{} and \programopt{-} arguments; the
1383convention is:
1384
1385\begin{itemize}
1386\item bare \longprogramopt{}, if not the argument to some option,
1387causes command-line processing to halt and the \longprogramopt{}
1388itself is lost.
1389
1390\item bare \programopt{-} similarly causes command-line processing to
1391halt, but the \programopt{-} itself is kept.
1392
1393\item either \longprogramopt{} or \programopt{-} can be option
1394arguments.
1395\end{itemize}
1396
1397If you want an option that takes a variable number of arguments, there
1398are several subtle, tricky issues to worry about. The exact
1399implementation you choose will be based on which trade-offs you're
1400willing to make for your application (which is why \module{optparse}
1401doesn't support this sort of thing directly).
1402
1403Nevertheless, here's a stab at a callback for an option with variable
1404arguments:
1405
1406\begin{verbatim}
1407def varargs (option, opt, value, parser):
1408 assert value is None
1409 done = 0
1410 value = []
1411 rargs = parser.rargs
1412 while rargs:
1413 arg = rargs[0]
1414
1415 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1416 # etc. Note that this also stops on "-3" or "-3.0", so if
1417 # your option takes numeric values, you will need to handle
1418 # this.
1419 if ((arg[:2] == "--" and len(arg) > 2) or
1420 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1421 break
1422 else:
1423 value.append(arg)
1424 del rargs[0]
1425
1426 setattr(parser.values, option.dest, value)
1427
Fred Drakecf6d74a2003-04-18 15:50:13 +00001428...
Neal Norwitz488609e2003-01-06 16:51:37 +00001429parser.add_option("-c", "--callback",
1430 action="callback", callback=varargs)
1431\end{verbatim}
1432
1433The main weakness with this particular implementation is that negative
1434numbers in the arguments following \programopt{-c} will be interpreted
1435as further options, rather than as arguments to \programopt{-c}.
1436Fixing this is left as an exercise for the reader.
1437
1438\subsection{Extending \module{optparse}\label{optparse-extending}}
1439
1440Since the two major controlling factors in how \module{optparse}
1441interprets command-line options are the action and type of each
1442option, the most likely direction of extension is to add new actions
1443and new types.
1444
1445Also, the examples section includes several demonstrations of
Greg Wardd7231282003-05-03 21:22:58 +00001446extending \module{optparse} in different ways: e.g. a case-insensitive
Neal Norwitz488609e2003-01-06 16:51:37 +00001447option parser, or two kinds of option parsers that implement
1448``required options''.
1449
1450\subsubsection{Adding new types\label{optparse-adding-types}}
1451
1452To add new types, you need to define your own subclass of
1453\module{optparse}'s \class{Option} class. This class has a couple of
1454attributes that define \module{optparse}'s types: \member{TYPES} and
1455\member{TYPE_CHECKER}.
1456
1457\member{TYPES} is a tuple of type names; in your subclass, simply
1458define a new tuple \member{TYPES} that builds on the standard one.
1459
1460\member{TYPE_CHECKER} is a dictionary mapping type names to
1461type-checking functions. A type-checking function has the following
1462signature:
1463
1464\begin{verbatim}
1465def check_foo (option : Option, opt : string, value : string)
1466 -> foo
1467\end{verbatim}
1468
1469You can name it whatever you like, and make it return any type you
1470like. The value returned by a type-checking function will wind up in
1471the \class{OptionValues} instance returned by
1472\method{OptionParser.parse_args()}, or be passed to callbacks as the
1473\var{value} parameter.
1474
1475Your type-checking function should raise \exception{OptionValueError}
1476if it encounters any problems. \exception{OptionValueError} takes a
1477single string argument, which is passed as-is to
1478\class{OptionParser}'s \method{error()} method, which in turn prepends
1479the program name and the string ``error:'' and prints everything to
1480stderr before terminating the process.
1481
1482Here's a silly example that demonstrates adding a ``complex'' option
1483type to parse Python-style complex numbers on the command line. (This
1484is even sillier than it used to be, because \module{optparse} 1.3 adds
1485built-in support for complex numbers [purely for completeness], but
1486never mind.)
1487
1488First, the necessary imports:
1489
1490\begin{verbatim}
1491from copy import copy
1492from optparse import Option, OptionValueError
1493\end{verbatim}
1494
1495You need to define your type-checker first, since it's referred to
1496later (in the \member{TYPE_CHECKER} class attribute of your
1497\class{Option} subclass):
1498
1499\begin{verbatim}
1500def check_complex (option, opt, value):
1501 try:
1502 return complex(value)
1503 except ValueError:
1504 raise OptionValueError(
1505 "option %s: invalid complex value: %r" % (opt, value))
1506\end{verbatim}
1507
1508Finally, the \class{Option} subclass:
1509
1510\begin{verbatim}
1511class MyOption (Option):
1512 TYPES = Option.TYPES + ("complex",)
1513 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1514 TYPE_CHECKER["complex"] = check_complex
1515\end{verbatim}
1516
1517(If we didn't make a \function{copy()} of
1518\member{Option.TYPE_CHECKER}, we would end up modifying the
1519\member{TYPE_CHECKER} attribute of \module{optparse}'s Option class.
1520This being Python, nothing stops you from doing that except good
1521manners and common sense.)
1522
1523That's it! Now you can write a script that uses the new option type
1524just like any other \module{optparse}-based script, except you have to
1525instruct your \class{OptionParser} to use \class{MyOption} instead of
1526\class{Option}:
1527
1528\begin{verbatim}
1529parser = OptionParser(option_class=MyOption)
1530parser.add_option("-c", action="store", type="complex", dest="c")
1531\end{verbatim}
1532
1533Alternately, you can build your own option list and pass it to
1534\class{OptionParser}; if you don't use \method{add_option()} in the
1535above way, you don't need to tell \class{OptionParser} which option
1536class to use:
1537
1538\begin{verbatim}
1539option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1540parser = OptionParser(option_list=option_list)
1541\end{verbatim}
1542
1543\subsubsection{Adding new actions\label{optparse-adding-actions}}
1544
1545Adding new actions is a bit trickier, because you have to understand
1546that \module{optparse} has a couple of classifications for actions:
1547
1548\begin{definitions}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001549\term{``store'' actions}
Neal Norwitz488609e2003-01-06 16:51:37 +00001550 actions that result in \module{optparse} storing a value to an attribute
Greg Wardbf8f1b52003-05-03 19:41:45 +00001551 of the OptionValues instance; these options require a \var{dest}
Neal Norwitz488609e2003-01-06 16:51:37 +00001552 attribute to be supplied to the Option constructor
Greg Wardbf8f1b52003-05-03 19:41:45 +00001553\term{``typed'' actions}
Neal Norwitz488609e2003-01-06 16:51:37 +00001554 actions that take a value from the command line and expect it to be
1555 of a certain type; or rather, a string that can be converted to a
Greg Wardbf8f1b52003-05-03 19:41:45 +00001556 certain type. These options require a \var{type} attribute to the
Neal Norwitz488609e2003-01-06 16:51:37 +00001557 Option constructor.
1558\end{definitions}
1559
Greg Wardbf8f1b52003-05-03 19:41:45 +00001560Some default ``store'' actions are \var{store}, \var{store_const},
1561\var{append}, and \var{count}. The default ``typed'' actions are
1562\var{store}, \var{append}, and \var{callback}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001563
1564When you add an action, you need to decide if it's a ``store'' action,
1565a ``typed'', neither, or both. Three class attributes of
1566\class{Option} (or your \class{Option} subclass) control this:
1567
1568\begin{memberdesc}{ACTIONS}
1569 All actions must be listed as strings in ACTIONS.
1570\end{memberdesc}
1571\begin{memberdesc}{STORE_ACTIONS}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001572 ``store'' actions are additionally listed here.
Neal Norwitz488609e2003-01-06 16:51:37 +00001573\end{memberdesc}
1574\begin{memberdesc}{TYPED_ACTIONS}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001575 ``typed'' actions are additionally listed here.
Neal Norwitz488609e2003-01-06 16:51:37 +00001576\end{memberdesc}
1577
1578In order to actually implement your new action, you must override
1579\class{Option}'s \method{take_action()} method and add a case that
1580recognizes your action.
1581
1582For example, let's add an ``extend'' action. This is similar to the
1583standard ``append'' action, but instead of taking a single value from
1584the command-line and appending it to an existing list, ``extend'' will
1585take multiple values in a single comma-delimited string, and extend an
1586existing list with them. That is, if \longprogramopt{names} is an
1587``extend'' option of type string, the command line:
1588
1589\begin{verbatim}
1590--names=foo,bar --names blah --names ding,dong
1591\end{verbatim}
1592
1593would result in a list:
1594
1595\begin{verbatim}
1596["foo", "bar", "blah", "ding", "dong"]
1597\end{verbatim}
1598
1599Again we define a subclass of \class{Option}:
1600
1601\begin{verbatim}
1602class MyOption (Option):
1603
1604 ACTIONS = Option.ACTIONS + ("extend",)
1605 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1606 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1607
1608 def take_action (self, action, dest, opt, value, values, parser):
1609 if action == "extend":
1610 lvalue = value.split(",")
1611 values.ensure_value(dest, []).extend(lvalue)
1612 else:
1613 Option.take_action(
1614 self, action, dest, opt, value, values, parser)
1615\end{verbatim}
1616
1617Features of note:
1618
1619\begin{itemize}
1620\item ``extend'' both expects a value on the command-line and stores that
1621value somewhere, so it goes in both \member{STORE_ACTIONS} and
1622\member{TYPED_ACTIONS}.
1623
1624\item \method{MyOption.take_action()} implements just this one new
1625action, and passes control back to \method{Option.take_action()} for
1626the standard \module{optparse} actions.
1627
1628\item \var{values} is an instance of the \class{Values} class, which
1629provides the very useful \method{ensure_value()}
1630method. \method{ensure_value()} is essentially \function{getattr()}
1631with a safety valve; it is called as:
1632
1633\begin{verbatim}
1634values.ensure_value(attr, value)
1635\end{verbatim}
1636\end{itemize}
1637
1638If the \member{attr} attribute of \var{values} doesn't exist or is
Greg Wardd7231282003-05-03 21:22:58 +00001639\code{None}, then \method{ensure_value()} first sets it to \var{value}, and
Neal Norwitz488609e2003-01-06 16:51:37 +00001640then returns \var{value}. This is very handy for actions like
1641``extend'', ``append'', and ``count'', all of which accumulate data in
1642a variable and expect that variable to be of a certain type (a list
1643for the first two, an integer for the latter). Using
1644\method{ensure_value()} means that scripts using your action don't
1645have to worry about setting a default value for the option
Greg Wardd7231282003-05-03 21:22:58 +00001646destinations in question; they can just leave the default as \code{None} and
Neal Norwitz488609e2003-01-06 16:51:37 +00001647\method{ensure_value()} will take care of getting it right when it's
1648needed.
1649
1650\subsubsection{Other reasons to extend \module{optparse}\label{optparse-extending-other-reasons}}
1651
1652Adding new types and new actions are the big, obvious reasons why you
1653might want to extend \module{optparse}. I can think of at least two
1654other areas to play with.
1655
1656First, the simple one: \class{OptionParser} tries to be helpful by
Greg Wardd7231282003-05-03 21:22:58 +00001657calling \function{sys.exit()} when appropriate, i.e. when there's an
Neal Norwitz488609e2003-01-06 16:51:37 +00001658error on the command-line or when the user requests help. In the
1659former case, the traditional course of letting the script crash with a
1660traceback is unacceptable; it will make users think there's a bug in
1661your script when they make a command-line error. In the latter case,
1662there's generally not much point in carrying on after printing a help
1663message.
1664
1665If this behaviour bothers you, it shouldn't be too hard to ``fix'' it.
1666You'll have to
1667
1668\begin{enumerate}
1669\item subclass OptionParser and override the error() method
Greg Wardbf8f1b52003-05-03 19:41:45 +00001670\item subclass Option and override the take_action() method---you'll
1671 need to provide your own handling of the ``help'' action that
Neal Norwitz488609e2003-01-06 16:51:37 +00001672 doesn't call sys.exit()
1673\end{enumerate}
1674
1675The second, much more complex, possibility is to override the
1676command-line syntax implemented by \module{optparse}. In this case,
1677you'd leave the whole machinery of option actions and types alone, but
1678rewrite the code that processes \var{sys.argv}. You'll need to
1679subclass \class{OptionParser} in any case; depending on how radical a
1680rewrite you want, you'll probably need to override one or all of
1681\method{parse_args()}, \method{_process_long_opt()}, and
1682\method{_process_short_opts()}.
1683
1684Both of these are left as an exercise for the reader. I have not
1685tried to implement either myself, since I'm quite happy with
1686\module{optparse}'s default behaviour (naturally).
1687
1688Happy hacking, and don't forget: Use the Source, Luke.
1689
1690\subsubsection{Examples\label{optparse-extending-examples}}
1691
1692Here are a few examples of extending the \module{optparse} module.
1693
1694First, let's change the option-parsing to be case-insensitive:
1695
1696\verbatiminput{caseless.py}
1697
1698And two ways of implementing ``required options'' with
1699\module{optparse}.
1700
1701Version 1: Add a method to \class{OptionParser} which applications
1702must call after parsing arguments:
1703
1704\verbatiminput{required_1.py}
1705
1706Version 2: Extend \class{Option} and add a \member{required}
1707attribute; extend \class{OptionParser} to ensure that required options
1708are present after parsing:
1709
Fred Drakecf6d74a2003-04-18 15:50:13 +00001710\verbatiminput{required_2.py}