blob: 9364e9566914efcd060da570700ab45884d52d06 [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
281there: \var{action}, \var{type}, \var{dest} (destination), and
Neal Norwitz488609e2003-01-06 16:51:37 +0000282\var{help}.
283
Greg Wardbf8f1b52003-05-03 19:41:45 +0000284\subsubsection{The \var{store} action\label{optparse-store-action}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000285
286The action tells \module{optparse} what to do when it sees one of the
287option strings for this option on the command-line. For example, the
288action \var{store} means: take the next argument (or the remainder of
289the current argument), ensure that it is of the correct type, and
290store it to your chosen destination.
291
Greg Wardbf8f1b52003-05-03 19:41:45 +0000292For example, let's fill in the ``...'' of that last option:
Neal Norwitz488609e2003-01-06 16:51:37 +0000293
294\begin{verbatim}
295parser.add_option("-f", "--file",
296 action="store", type="string", dest="filename")
297\end{verbatim}
298
299Now let's make up a fake command-line and ask \module{optparse} to
300parse it:
301
302\begin{verbatim}
303args = ["-f", "foo.txt"]
304(options, args) = parser.parse_args(args)
305\end{verbatim}
306
307(Note that if you don't pass an argument list to
308\function{parse_args()}, it automatically uses \var{sys.argv[1:]}.)
309
Greg Wardd7231282003-05-03 21:22:58 +0000310When \module{optparse} sees the \programopt{-f}, it consumes the next
Greg Wardbf8f1b52003-05-03 19:41:45 +0000311argument---\code{foo.txt}---and stores it in the \var{filename}
Neal Norwitz488609e2003-01-06 16:51:37 +0000312attribute of a special object. That object is the first return value
Fred Drakecf6d74a2003-04-18 15:50:13 +0000313from \function{parse_args()}, so:
Neal Norwitz488609e2003-01-06 16:51:37 +0000314
315\begin{verbatim}
316print options.filename
317\end{verbatim}
318
Greg Wardbf8f1b52003-05-03 19:41:45 +0000319will print \code{foo.txt}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000320
Greg Wardbf8f1b52003-05-03 19:41:45 +0000321Other option types supported by \module{optparse} are \code{int} and
322\code{float}. Here's an option that expects an integer argument:
Neal Norwitz488609e2003-01-06 16:51:37 +0000323
324\begin{verbatim}
325parser.add_option("-n", type="int", dest="num")
326\end{verbatim}
327
Greg Wardd7231282003-05-03 21:22:58 +0000328This example doesn't provide a long option, which is perfectly
329acceptable. It also doesn't specify the action---it defaults to
330``store''.
Neal Norwitz488609e2003-01-06 16:51:37 +0000331
Greg Wardd7231282003-05-03 21:22:58 +0000332Let's parse another fake command-line. This time, we'll jam the option
333argument right up against the option, since \programopt{-n42} (one
334argument) is equivalent to \programopt{-n 42} (two arguments).
Neal Norwitz488609e2003-01-06 16:51:37 +0000335
336\begin{verbatim}
337(options, args) = parser.parse_args(["-n42"])
338print options.num
339\end{verbatim}
340
Greg Wardd7231282003-05-03 21:22:58 +0000341This prints \code{42}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000342
343Trying out the ``float'' type is left as an exercise for the reader.
344
345If you don't specify a type, \module{optparse} assumes ``string''.
346Combined with the fact that the default action is ``store'', that
347means our first example can be a lot shorter:
348
349\begin{verbatim}
350parser.add_option("-f", "--file", dest="filename")
351\end{verbatim}
352
353If you don't supply a destination, \module{optparse} figures out a
354sensible default from the option strings: if the first long option
355string is \longprogramopt{foo-bar}, then the default destination is
356\var{foo_bar}. If there are no long option strings,
357\module{optparse} looks at the first short option: the default
358destination for \programopt{-f} is \var{f}.
359
Fred Drakecf6d74a2003-04-18 15:50:13 +0000360Adding types is fairly easy; please refer to
361section~\ref{optparse-adding-types}, ``Adding new types.''
Neal Norwitz488609e2003-01-06 16:51:37 +0000362
Greg Wardbf8f1b52003-05-03 19:41:45 +0000363\subsubsection{Other \var{store_*} actions\label{optparse-other-store-actions}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000364
Greg Wardbf8f1b52003-05-03 19:41:45 +0000365Flag options---set a variable to true or false when a particular
366option is seen---are quite common. \module{optparse} supports them
Neal Norwitz488609e2003-01-06 16:51:37 +0000367with two separate actions, ``store_true'' and ``store_false''. For
368example, you might have a \var{verbose} flag that is turned on with
369\programopt{-v} and off with \programopt{-q}:
370
371\begin{verbatim}
372parser.add_option("-v", action="store_true", dest="verbose")
373parser.add_option("-q", action="store_false", dest="verbose")
374\end{verbatim}
375
376Here we have two different options with the same destination, which is
377perfectly OK. (It just means you have to be a bit careful when setting
Greg Wardbf8f1b52003-05-03 19:41:45 +0000378default values---see below.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000379
Greg Wardd7231282003-05-03 21:22:58 +0000380When \module{optparse} sees \programopt{-v} on the command line, it sets
381\var{options.verbose} to \code{True}; when it sees \programopt{-q}, it
382sets \var{options.verbose} to \code{False}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000383
384\subsubsection{Setting default values\label{optparse-setting-default-values}}
385
386All of the above examples involve setting some variable (the
387``destination'') when certain command-line options are seen. What
388happens if those options are never seen? Since we didn't supply any
Greg Wardd7231282003-05-03 21:22:58 +0000389defaults, they are all set to \code{None}. Sometimes, this is just fine (which
390is why it's the default), but sometimes, you want more control. To
391address that need, \module{optparse} lets you supply a default value for
392each destination, which is assigned before the command-line is parsed.
Neal Norwitz488609e2003-01-06 16:51:37 +0000393
394First, consider the verbose/quiet example. If we want
Greg Ward1f535172003-05-03 20:13:08 +0000395\module{optparse} to set \var{verbose} to \code{True} unless
396\programopt{-q} is seen, then we can do this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000397
398\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000399parser.add_option("-v", action="store_true", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000400parser.add_option("-q", action="store_false", dest="verbose")
401\end{verbatim}
402
403Oddly enough, this is exactly equivalent:
404
405\begin{verbatim}
406parser.add_option("-v", action="store_true", dest="verbose")
Greg Ward1f535172003-05-03 20:13:08 +0000407parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000408\end{verbatim}
409
410Those are equivalent because you're supplying a default value for the
411option's \emph{destination}, and these two options happen to have the same
412destination (the \var{verbose} variable).
413
414Consider this:
415
416\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000417parser.add_option("-v", action="store_true", dest="verbose", default=False)
418parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000419\end{verbatim}
420
Greg Ward1f535172003-05-03 20:13:08 +0000421Again, the default value for \var{verbose} will be \code{True}: the last
Greg Wardd7231282003-05-03 21:22:58 +0000422default value supplied for any particular destination is the one that
423counts.
Neal Norwitz488609e2003-01-06 16:51:37 +0000424
425\subsubsection{Generating help\label{optparse-generating-help}}
426
427The last feature that you will use in every script is
428\module{optparse}'s ability to generate help messages. All you have
429to do is supply a \var{help} value when you add an option. Let's
430create a new parser and populate it with user-friendly (documented)
431options:
432
433\begin{verbatim}
434usage = "usage: %prog [options] arg1 arg2"
435parser = OptionParser(usage=usage)
436parser.add_option("-v", "--verbose",
Greg Ward1f535172003-05-03 20:13:08 +0000437 action="store_true", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +0000438 help="make lots of noise [default]")
439parser.add_option("-q", "--quiet",
440 action="store_false", dest="verbose",
441 help="be vewwy quiet (I'm hunting wabbits)")
442parser.add_option("-f", "--file", dest="filename",
443 metavar="FILE", help="write output to FILE"),
444parser.add_option("-m", "--mode",
445 default="intermediate",
446 help="interaction mode: one of 'novice', "
447 "'intermediate' [default], 'expert'")
448\end{verbatim}
449
450If \module{optparse} encounters either \programopt{-h} or
Greg Wardb4e33192003-05-03 19:16:36 +0000451\longprogramopt{help} on the command-line, or if you just call
Neal Norwitz488609e2003-01-06 16:51:37 +0000452\method{parser.print_help()}, it prints the following to stdout:
453
454\begin{verbatim}
455usage: <yourscript> [options] arg1 arg2
456
457options:
458 -h, --help show this help message and exit
459 -v, --verbose make lots of noise [default]
460 -q, --quiet be vewwy quiet (I'm hunting wabbits)
461 -fFILE, --file=FILE write output to FILE
462 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
463 [default], 'expert'
464\end{verbatim}
465
466There's a lot going on here to help \module{optparse} generate the
467best possible help message:
468
469\begin{itemize}
470\item the script defines its own usage message:
471
472\begin{verbatim}
473usage = "usage: %prog [options] arg1 arg2"
474\end{verbatim}
475
Greg Wardbf8f1b52003-05-03 19:41:45 +0000476\module{optparse} expands \samp{\%prog} in the usage string to the name of the
Greg Wardd7231282003-05-03 21:22:58 +0000477current script, i.e. \code{os.path.basename(sys.argv[0])}. The
Neal Norwitz488609e2003-01-06 16:51:37 +0000478expanded string is then printed before the detailed option help.
479
480If you don't supply a usage string, \module{optparse} uses a bland but
Greg Wardbf8f1b52003-05-03 19:41:45 +0000481sensible default: \code{"usage: \%prog [options]"}, which is fine if your
Neal Norwitz488609e2003-01-06 16:51:37 +0000482script doesn't take any positional arguments.
483
484\item every option defines a help string, and doesn't worry about
Greg Wardbf8f1b52003-05-03 19:41:45 +0000485line-wrapping---\module{optparse} takes care of wrapping lines and
Neal Norwitz488609e2003-01-06 16:51:37 +0000486making the help output look good.
487
488\item options that take a value indicate this fact in their
489automatically-generated help message, e.g. for the ``mode'' option:
490
491\begin{verbatim}
492-mMODE, --mode=MODE
493\end{verbatim}
494
495Here, ``MODE'' is called the meta-variable: it stands for the argument
496that the user is expected to supply to
497\programopt{-m}/\longprogramopt{mode}. By default, \module{optparse}
498converts the destination variable name to uppercase and uses that for
Greg Wardbf8f1b52003-05-03 19:41:45 +0000499the meta-variable. Sometimes, that's not what you want---for
Neal Norwitz488609e2003-01-06 16:51:37 +0000500example, the \var{filename} option explicitly sets
501\code{metavar="FILE"}, resulting in this automatically-generated
502option description:
503
504\begin{verbatim}
505-fFILE, --file=FILE
506\end{verbatim}
507
508This is important for more than just saving space, though: the
509manually written help text uses the meta-variable ``FILE'', to clue
510the user in that there's a connection between the formal syntax
511``-fFILE'' and the informal semantic description ``write output to
512FILE''. This is a simple but effective way to make your help text a
513lot clearer and more useful for end users.
514\end{itemize}
515
Fred Drakecf6d74a2003-04-18 15:50:13 +0000516When dealing with many options, it is convenient to group these
517options for better help output. An \class{OptionParser} can contain
518several option groups, each of which can contain several options.
519
520Continuing with the parser defined above, adding an
521\class{OptionGroup} to a parser is easy:
522
523\begin{verbatim}
524group = OptionGroup(parser, "Dangerous Options",
Greg Wardd7231282003-05-03 21:22:58 +0000525 "Caution: use these options at your own risk. "
526 "It is believed that some of them bite.")
Fred Drakecf6d74a2003-04-18 15:50:13 +0000527group.add_option("-g", action="store_true", help="Group option.")
528parser.add_option_group(group)
529\end{verbatim}
530
531This would result in the following help output:
532
533\begin{verbatim}
534usage: [options] arg1 arg2
535
536options:
537 -h, --help show this help message and exit
538 -v, --verbose make lots of noise [default]
539 -q, --quiet be vewwy quiet (I'm hunting wabbits)
540 -fFILE, --file=FILE write output to FILE
541 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
542 [default], 'expert'
543
544 Dangerous Options:
545 Caution: use of these options is at your own risk. It is believed that
546 some of them bite.
547 -g Group option.
548\end{verbatim}
549
550
Neal Norwitz488609e2003-01-06 16:51:37 +0000551\subsubsection{Print a version number\label{optparse-print-version}}
552
553Similar to the brief usage string, \module{optparse} can also print a
554version string for your program. You have to supply the string, as
555the \var{version} argument to \class{OptionParser}:
556
557\begin{verbatim}
558parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
559\end{verbatim}
560
Greg Wardd7231282003-05-03 21:22:58 +0000561\var{version} can contain anything you like; \code{\%prog} is expanded
562in \var{version} just as with \var{usage}. When you supply it,
563\module{optparse} automatically adds a \longprogramopt{version} option
564to your parser. If it encounters this option on the command line, it
565expands your \var{version} string (by replacing \code{\%prog}), prints
566it to stdout, and exits.
Neal Norwitz488609e2003-01-06 16:51:37 +0000567
568For example, if your script is called /usr/bin/foo, a user might do:
569
570\begin{verbatim}
571$ /usr/bin/foo --version
572foo 1.0
Greg Wardd7231282003-05-03 21:22:58 +0000573\end{verbatim} % $ (avoid confusing emacs)
Neal Norwitz488609e2003-01-06 16:51:37 +0000574
575\subsubsection{Error-handling\label{optparse-error-handling}}
576
577The one thing you need to know for basic usage is how
578\module{optparse} behaves when it encounters an error on the
Greg Wardd7231282003-05-03 21:22:58 +0000579command-line---e.g. \programopt{-n 4x} where \programopt{-n} is an
580integer-valued option. In this case, \module{optparse} prints your
581usage message to stderr, followed by a useful and human-readable error
582message. Then it terminates (calls \function{sys.exit()}) with a
583non-zero exit status.
Neal Norwitz488609e2003-01-06 16:51:37 +0000584
585If you don't like this, subclass \class{OptionParser} and override the
Fred Drakecf6d74a2003-04-18 15:50:13 +0000586\method{error()} method. See section~\ref{optparse-extending},
587``Extending \module{optparse}.''
Neal Norwitz488609e2003-01-06 16:51:37 +0000588
589\subsubsection{Putting it all together\label{optparse-basic-summary}}
590
Greg Wardd7231282003-05-03 21:22:58 +0000591Here's what \module{optparse}-based scripts typically look like:
Neal Norwitz488609e2003-01-06 16:51:37 +0000592
593\begin{verbatim}
594from optparse import OptionParser
Greg Wardd7231282003-05-03 21:22:58 +0000595[...]
596def main():
597 usage = "usage: \%prog [-f] [-v] [-q] firstarg secondarg"
Neal Norwitz488609e2003-01-06 16:51:37 +0000598 parser = OptionParser(usage)
599 parser.add_option("-f", "--file", type="string", dest="filename",
600 help="read data from FILENAME")
601 parser.add_option("-v", "--verbose",
602 action="store_true", dest="verbose")
603 parser.add_option("-q", "--quiet",
604 action="store_false", dest="verbose")
Neal Norwitz488609e2003-01-06 16:51:37 +0000605
606 (options, args) = parser.parse_args()
607 if len(args) != 1:
608 parser.error("incorrect number of arguments")
609
610 if options.verbose:
Greg Wardd7231282003-05-03 21:22:58 +0000611 print "reading \%s..." \% options.filename
612 [... go to work ...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000613
614if __name__ == "__main__":
615 main()
616\end{verbatim}
617
618\subsection{Advanced Usage\label{optparse-advanced-usage}}
619
Fred Drakecf6d74a2003-04-18 15:50:13 +0000620\subsubsection{Creating and populating the
621 parser\label{optparse-creating-the-parser}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000622
623There are several ways to populate the parser with options. One way
624is to pass a list of \class{Options} to the \class{OptionParser}
625constructor:
626
627\begin{verbatim}
Greg Wardd7231282003-05-03 21:22:58 +0000628from optparse import OptionParser, make_option
629[...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000630parser = OptionParser(option_list=[
631 make_option("-f", "--filename",
632 action="store", type="string", dest="filename"),
633 make_option("-q", "--quiet",
634 action="store_false", dest="verbose")])
635\end{verbatim}
636
Greg Wardd7231282003-05-03 21:22:58 +0000637(\function{make_option()} is a factory function for generating
638\class{Option} objects.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000639
Greg Wardd7231282003-05-03 21:22:58 +0000640For long option lists, it may be more convenient/readable to create the
Neal Norwitz488609e2003-01-06 16:51:37 +0000641list separately:
642
643\begin{verbatim}
644option_list = [make_option("-f", "--filename",
645 action="store", type="string", dest="filename"),
Greg Wardd7231282003-05-03 21:22:58 +0000646 [... more options ...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000647 make_option("-q", "--quiet",
648 action="store_false", dest="verbose")]
649parser = OptionParser(option_list=option_list)
650\end{verbatim}
651
652Or, you can use the \method{add_option()} method of
653\class{OptionParser} to add options one-at-a-time:
654
655\begin{verbatim}
656parser = OptionParser()
657parser.add_option("-f", "--filename",
658 action="store", type="string", dest="filename")
659parser.add_option("-q", "--quiet",
660 action="store_false", dest="verbose")
661\end{verbatim}
662
663This method makes it easier to track down exceptions raised by the
664\class{Option} constructor, which are common because of the complicated
Greg Wardd7231282003-05-03 21:22:58 +0000665interdependencies among the various keyword arguments. (If you get it
666wrong, \module{optparse} raises \exception{OptionError}.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000667
668\method{add_option()} can be called in one of two ways:
669
670\begin{itemize}
671\item pass it an \class{Option} instance (as returned by \function{make_option()})
672\item pass it any combination of positional and keyword arguments that
Greg Wardd7231282003-05-03 21:22:58 +0000673are acceptable to \function{make_option()} (i.e., to the \class{Option}
Neal Norwitz488609e2003-01-06 16:51:37 +0000674constructor), and it will create the \class{Option} instance for you
675(shown above).
676\end{itemize}
677
678\subsubsection{Defining options\label{optparse-defining-options}}
679
680Each \class{Option} instance represents a set of synonymous
Greg Wardd7231282003-05-03 21:22:58 +0000681command-line options, i.e. options that have the same meaning and
Neal Norwitz488609e2003-01-06 16:51:37 +0000682effect, but different spellings. You can specify any number of short
683or long option strings, but you must specify at least one option
684string.
685
686To define an option with only a short option string:
687
688\begin{verbatim}
689make_option("-f", ...)
690\end{verbatim}
691
692And to define an option with only a long option string:
693
694\begin{verbatim}
695make_option("--foo", ...)
696\end{verbatim}
697
Greg Wardd7231282003-05-03 21:22:58 +0000698The ``...'' represents a set of keyword arguments that define attributes
699of the \class{Option} object. The rules governing which keyword args
700you must supply for a given \class{Option} are fairly complicated, but
701you always have to supply \emph{some}. If you get it wrong,
702\module{optparse} raises an \exception{OptionError} exception explaining
703your mistake.
Neal Norwitz488609e2003-01-06 16:51:37 +0000704
Greg Wardd7231282003-05-03 21:22:58 +0000705The most important attribute of an option is its action, i.e. what to do
Neal Norwitz488609e2003-01-06 16:51:37 +0000706when we encounter this option on the command-line. The possible actions
707are:
708
Greg Wardd7231282003-05-03 21:22:58 +0000709\begin{tableii}{l|l}{code}{Action}{Meaning}
710\lineii{store}{store this option's argument (default)}
711\lineii{store_const}{store a constant value}
712\lineii{store_true}{store a true value}
713\lineii{store_false}{store a false value}
714\lineii{append}{append this option's argument to a list}
715\lineii{count}{increment a counter by one}
716\lineii{callback}{call a specified function}
717\lineii{help}{print a usage message including all options and the
718 documentation for them}
719\end{tableii}
Neal Norwitz488609e2003-01-06 16:51:37 +0000720
721(If you don't supply an action, the default is ``store''. For this
722action, you may also supply \var{type} and \var{dest} keywords; see
723below.)
724
725As you can see, most actions involve storing or updating a value
726somewhere. \module{optparse} always creates a particular object (an
727instance of the \class{Values} class) specifically for this
728purpose. Option arguments (and various other values) are stored as
729attributes of this object, according to the \var{dest} (destination)
730argument to \function{make_option()}/\method{add_option()}.
731
732For example, when you call:
733
734\begin{verbatim}
735parser.parse_args()
736\end{verbatim}
737
738one of the first things \module{optparse} does is create a
739\var{values} object:
740
741\begin{verbatim}
742values = Values()
743\end{verbatim}
744
745If one of the options in this parser is defined with:
746
747\begin{verbatim}
748make_option("-f", "--file", action="store", type="string", dest="filename")
749\end{verbatim}
750
751and the command-line being parsed includes any of the following:
752
753\begin{verbatim}
754-ffoo
755-f foo
756--file=foo
757--file foo
758\end{verbatim}
759
760then \module{optparse}, on seeing the \programopt{-f} or
761\longprogramopt{file} option, will do the equivalent of this:
762
763\begin{verbatim}
764 values.filename = "foo"
765\end{verbatim}
766
Greg Wardd7231282003-05-03 21:22:58 +0000767Clearly, the \var{type} and \var{dest} arguments are almost
Neal Norwitz488609e2003-01-06 16:51:37 +0000768as important as \var{action}. \var{action} is the only attribute that
Greg Wardb4e33192003-05-03 19:16:36 +0000769is meaningful for \emph{all} options, though, so it is the most
770important.
Neal Norwitz488609e2003-01-06 16:51:37 +0000771
772\subsubsection{Option actions\label{optparse-option-actions}}
773
774The various option actions all have slightly different requirements
775and effects. Except for the ``help'' action, you must supply at least
776one other keyword argument when creating the \class{Option}; the exact
777requirements for each action are listed here.
778
779\begin{definitions}
780\term{store} [relevant: \var{type}, \var{dest}, \var{nargs}, \var{choices}]
781
782The option must be followed by an argument, which is converted to a
783value according to \var{type} and stored in \var{dest}. If
Greg Wardd7231282003-05-03 21:22:58 +0000784\code{nargs > 1}, multiple arguments will be consumed from the command
Neal Norwitz488609e2003-01-06 16:51:37 +0000785line; all will be converted according to \var{type} and stored to
Fred Drakecf6d74a2003-04-18 15:50:13 +0000786\var{dest} as a tuple. See section~\ref{optparse-option-types},
787``Option types'' below.
Neal Norwitz488609e2003-01-06 16:51:37 +0000788
Greg Wardd7231282003-05-03 21:22:58 +0000789If \var{choices} (a sequence of strings) is supplied, the type
Neal Norwitz488609e2003-01-06 16:51:37 +0000790defaults to ``choice''.
791
792If \var{type} is not supplied, it defaults to ``string''.
793
794If \var{dest} is not supplied, \module{optparse} derives a
795destination from the first long option strings (e.g.,
Greg Wardb4e33192003-05-03 19:16:36 +0000796\longprogramopt{foo-bar} becomes \var{foo_bar}). If there are no long
Neal Norwitz488609e2003-01-06 16:51:37 +0000797option strings, \module{optparse} derives a destination from the first
Greg Wardb4e33192003-05-03 19:16:36 +0000798short option string (e.g., \programopt{-f} becomes \var{f}).
Neal Norwitz488609e2003-01-06 16:51:37 +0000799
800Example:
801
802\begin{verbatim}
803make_option("-f")
804make_option("-p", type="float", nargs=3, dest="point")
805\end{verbatim}
806
807Given the following command line:
808
809\begin{verbatim}
810-f foo.txt -p 1 -3.5 4 -fbar.txt
811\end{verbatim}
812
813\module{optparse} will set:
814
815\begin{verbatim}
816values.f = "bar.txt"
817values.point = (1.0, -3.5, 4.0)
818\end{verbatim}
819
820(Actually, \member{values.f} will be set twice, but only the second
821time is visible in the end.)
822
823\term{store_const} [required: \var{const}, \var{dest}]
824
825The \var{const} value supplied to the \class{Option} constructor is
826stored in \var{dest}.
827
828Example:
829
830\begin{verbatim}
831make_option("-q", "--quiet",
832 action="store_const", const=0, dest="verbose"),
833make_option("-v", "--verbose",
834 action="store_const", const=1, dest="verbose"),
Greg Wardd7231282003-05-03 21:22:58 +0000835make_option("--noisy",
Neal Norwitz488609e2003-01-06 16:51:37 +0000836 action="store_const", const=2, dest="verbose"),
837\end{verbatim}
838
839If \longprogramopt{noisy} is seen, \module{optparse} will set:
840
841\begin{verbatim}
842values.verbose = 2
843\end{verbatim}
844
845\term{store_true} [required: \var{dest}]
846
Greg Ward1f535172003-05-03 20:13:08 +0000847A special case of ``store_const'' that stores \code{True} to \var{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000848
849\term{store_false} [required: \var{dest}]
850
Greg Wardd7231282003-05-03 21:22:58 +0000851Like ``store_true'', but stores \code{False}
Neal Norwitz488609e2003-01-06 16:51:37 +0000852
853Example:
854
855\begin{verbatim}
856make_option(None, "--clobber", action="store_true", dest="clobber")
857make_option(None, "--no-clobber", action="store_false", dest="clobber")
858\end{verbatim}
859
860\term{append} [relevant: \var{type}, \var{dest}, \var{nargs}, \var{choices}]
861
862The option must be followed by an argument, which is appended to the
863list in \var{dest}. If no default value for \var{dest} is supplied
Greg Wardd7231282003-05-03 21:22:58 +0000864(i.e. the default is \code{None}), an empty list is automatically created when
Neal Norwitz488609e2003-01-06 16:51:37 +0000865\module{optparse} first encounters this option on the command-line.
Greg Wardd7231282003-05-03 21:22:58 +0000866If \code{nargs > 1}, multiple arguments are consumed, and a tuple of
Neal Norwitz488609e2003-01-06 16:51:37 +0000867length \var{nargs} is appended to \var{dest}.
868
869The defaults for \var{type} and \var{dest} are the same as for the
870``store'' action.
871
872Example:
873
874\begin{verbatim}
875make_option("-t", "--tracks", action="append", type="int")
876\end{verbatim}
877
878If \programopt{-t3} is seen on the command-line, \module{optparse} does the equivalent of:
879
880\begin{verbatim}
881values.tracks = []
882values.tracks.append(int("3"))
883\end{verbatim}
884
Greg Wardb4e33192003-05-03 19:16:36 +0000885If, a little later on, \longprogramopt{tracks=4} is seen, it does:
Neal Norwitz488609e2003-01-06 16:51:37 +0000886
887\begin{verbatim}
888values.tracks.append(int("4"))
889\end{verbatim}
890
Fred Drakecf6d74a2003-04-18 15:50:13 +0000891See ``Error handling'' (section~\ref{optparse-error-handling}) for
Neal Norwitz488609e2003-01-06 16:51:37 +0000892information on how \module{optparse} deals with something like
Greg Wardb4e33192003-05-03 19:16:36 +0000893\longprogramopt{tracks=x}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000894
895\term{count} [required: \var{dest}]
896
897Increment the integer stored at \var{dest}. \var{dest} is set to zero
898before being incremented the first time (unless you supply a default
899value).
900
901Example:
902
903\begin{verbatim}
904make_option("-v", action="count", dest="verbosity")
905\end{verbatim}
906
907The first time \programopt{-v} is seen on the command line,
908\module{optparse} does the equivalent of:
909
910\begin{verbatim}
911values.verbosity = 0
912values.verbosity += 1
913\end{verbatim}
914
915Every subsequent occurrence of \programopt{-v} results in:
916
917\begin{verbatim}
918values.verbosity += 1
919\end{verbatim}
920
Greg Wardd7231282003-05-03 21:22:58 +0000921\term{callback} [required: \var{callback};
Neal Norwitz488609e2003-01-06 16:51:37 +0000922 relevant: \var{type}, \var{nargs}, \var{callback_args},
923 \var{callback_kwargs}]
924
925Call the function specified by \var{callback}. The signature of
926this function should be:
927
928\begin{verbatim}
929func(option : Option,
930 opt : string,
931 value : any,
932 parser : OptionParser,
933 *args, **kwargs)
934\end{verbatim}
935
Fred Drakecf6d74a2003-04-18 15:50:13 +0000936Callback options are covered in detail in
Greg Wardd7231282003-05-03 21:22:58 +0000937section~\ref{optparse-callback-options}, ``Callback Options.''
Neal Norwitz488609e2003-01-06 16:51:37 +0000938
939\term{help} [required: none]
940
941Prints a complete help message for all the options in the current
942option parser. The help message is constructed from the \var{usage}
943string passed to \class{OptionParser}'s constructor and the \var{help}
944string passed to every option.
945
946If no \var{help} string is supplied for an option, it will still be
947listed in the help message. To omit an option entirely, use the
948special value \constant{optparse.SUPPRESS_HELP}.
949
950Example:
951
952\begin{verbatim}
953from optparse import Option, OptionParser, SUPPRESS_HELP
954
955usage = "usage: %prog [options]"
956parser = OptionParser(usage, option_list=[
957 make_option("-h", "--help", action="help"),
958 make_option("-v", action="store_true", dest="verbose",
959 help="Be moderately verbose")
960 make_option("--file", dest="filename",
961 help="Input file to read data from"),
962 make_option("--secret", help=SUPPRESS_HELP)
963\end{verbatim}
964
Greg Wardb4e33192003-05-03 19:16:36 +0000965If \module{optparse} sees either \programopt{-h} or
966\longprogramopt{help} on the command line, it will print something
967like the following help message to stdout:
Neal Norwitz488609e2003-01-06 16:51:37 +0000968
969\begin{verbatim}
970usage: <yourscript> [options]
971
972options:
973 -h, --help Show this help message and exit
974 -v Be moderately verbose
975 --file=FILENAME Input file to read data from
976\end{verbatim}
977
978After printing the help message, \module{optparse} terminates your process
979with \code{sys.exit(0)}.
980
981\term{version} [required: none]
982
983Prints the version number supplied to the \class{OptionParser} to
984stdout and exits. The version number is actually formatted and
985printed by the \method{print_version()} method of
986\class{OptionParser}. Generally only relevant if the \var{version}
987argument is supplied to the \class{OptionParser} constructor.
988\end{definitions}
989
990\subsubsection{Option types\label{optparse-option-types}}
991
992\module{optparse} supports six option types out of the box: \dfn{string},
993\dfn{int}, \dfn{long}, \dfn{choice}, \dfn{float} and \dfn{complex}.
994(Of these, string, int, float, and choice are the most commonly used
Greg Wardd7231282003-05-03 21:22:58 +0000995---long and complex are there mainly for completeness.) It's easy to
Neal Norwitz488609e2003-01-06 16:51:37 +0000996add new option types by subclassing the \class{Option} class; see
Fred Drakecf6d74a2003-04-18 15:50:13 +0000997section~\ref{optparse-extending}, ``Extending \module{optparse}.''
Neal Norwitz488609e2003-01-06 16:51:37 +0000998
999Arguments to string options are not checked or converted in any way:
1000the text on the command line is stored in the destination (or passed
1001to the callback) as-is.
1002
1003Integer arguments are passed to \function{int()} to convert them to
1004Python integers. If \function{int()} fails, so will
1005\module{optparse}, although with a more useful error message.
1006Internally, \module{optparse} raises \exception{OptionValueError} in
1007\function{optparse.check_builtin()}; at a higher level (in
Greg Wardd7231282003-05-03 21:22:58 +00001008\class{OptionParser}), \module{optparse} catches this exception and
1009terminates your program with a useful error message.
Neal Norwitz488609e2003-01-06 16:51:37 +00001010
1011Likewise, float arguments are passed to \function{float()} for
1012conversion, long arguments to \function{long()}, and complex arguments
1013to \function{complex()}. Apart from that, they are handled
1014identically to integer arguments.
1015
1016Choice options are a subtype of string options. A master list or
1017tuple of choices (strings) must be passed to the option constructor
1018(\function{make_option()} or \method{OptionParser.add_option()}) as
Greg Wardd7231282003-05-03 21:22:58 +00001019the \var{choices} keyword argument. Choice option arguments are
Neal Norwitz488609e2003-01-06 16:51:37 +00001020compared against this master list in
1021\function{optparse.check_choice()}, and \exception{OptionValueError}
1022is raised if an unknown string is given.
1023
1024\subsubsection{Querying and manipulating your option parser\label{optparse-querying-and-manipulating}}
1025
1026Sometimes, it's useful to poke around your option parser and see what's
1027there. \class{OptionParser} provides a couple of methods to help you out:
1028
1029\begin{methoddesc}{has_option}{opt_str}
1030 Given an option string such as \programopt{-q} or
1031 \longprogramopt{verbose}, returns true if the \class{OptionParser}
1032 has an option with that option string.
1033\end{methoddesc}
1034
1035\begin{methoddesc}{get_option}{opt_str}
1036 Returns the \class{Option} instance that implements the option
Greg Wardd7231282003-05-03 21:22:58 +00001037 string you supplied, or \code{None} if no options implement it.
Neal Norwitz488609e2003-01-06 16:51:37 +00001038\end{methoddesc}
1039
1040\begin{methoddesc}{remove_option}{opt_str}
1041 If the \class{OptionParser} has an option corresponding to
1042 \var{opt_str}, that option is removed. If that option provided
1043 any other option strings, all of those option strings become
1044 invalid.
1045
1046 If \var{opt_str} does not occur in any option belonging to this
1047 \class{OptionParser}, raises \exception{ValueError}.
1048\end{methoddesc}
1049
1050\subsubsection{Conflicts between options\label{optparse-conflicts}}
1051
1052If you're not careful, it's easy to define conflicting options:
1053
1054\begin{verbatim}
1055parser.add_option("-n", "--dry-run", ...)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001056...
Neal Norwitz488609e2003-01-06 16:51:37 +00001057parser.add_option("-n", "--noisy", ...)
1058\end{verbatim}
1059
1060(This is even easier to do if you've defined your own
1061\class{OptionParser} subclass with some standard options.)
1062
1063On the assumption that this is usually a mistake, \module{optparse}
Fred Drakecf6d74a2003-04-18 15:50:13 +00001064raises an exception (\exception{OptionConflictError}) by default when
1065this happens. Since this is an easily-fixed programming error, you
Greg Wardbf8f1b52003-05-03 19:41:45 +00001066shouldn't try to catch this exception---fix your mistake and get on
Fred Drakecf6d74a2003-04-18 15:50:13 +00001067with life.
Neal Norwitz488609e2003-01-06 16:51:37 +00001068
1069Sometimes, you want newer options to deliberately replace the option
1070strings used by older options. You can achieve this by calling:
1071
1072\begin{verbatim}
1073parser.set_conflict_handler("resolve")
1074\end{verbatim}
1075
1076which instructs \module{optparse} to resolve option conflicts
1077intelligently.
1078
1079Here's how it works: every time you add an option, \module{optparse}
1080checks for conflicts with previously-added options. If it finds any,
1081it invokes the conflict-handling mechanism you specify either to the
1082\class{OptionParser} constructor:
1083
1084\begin{verbatim}
1085parser = OptionParser(..., conflict_handler="resolve")
1086\end{verbatim}
1087
1088or via the \method{set_conflict_handler()} method.
1089
Greg Wardd7231282003-05-03 21:22:58 +00001090The default conflict-handling mechanism is \code{error}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001091
1092Here's an example: first, define an \class{OptionParser} set to
1093resolve conflicts intelligently:
1094
1095\begin{verbatim}
1096parser = OptionParser(conflict_handler="resolve")
1097\end{verbatim}
1098
1099Now add all of our options:
1100
1101\begin{verbatim}
1102parser.add_option("-n", "--dry-run", ..., help="original dry-run option")
Fred Drakecf6d74a2003-04-18 15:50:13 +00001103...
Neal Norwitz488609e2003-01-06 16:51:37 +00001104parser.add_option("-n", "--noisy", ..., help="be noisy")
1105\end{verbatim}
1106
1107At this point, \module{optparse} detects that a previously-added option is already
1108using the \programopt{-n} option string. Since \code{conflict_handler
1109== "resolve"}, it resolves the situation by removing \programopt{-n}
1110from the earlier option's list of option strings. Now,
1111\longprogramopt{dry-run} is the only way for the user to activate that
1112option. If the user asks for help, the help message will reflect
1113that, e.g.:
1114
1115\begin{verbatim}
1116options:
1117 --dry-run original dry-run option
Fred Drakecf6d74a2003-04-18 15:50:13 +00001118 ...
Neal Norwitz488609e2003-01-06 16:51:37 +00001119 -n, --noisy be noisy
1120\end{verbatim}
1121
1122Note that it's possible to whittle away the option strings for a
1123previously-added option until there are none left, and the user has no
1124way of invoking that option from the command-line. In that case,
1125\module{optparse} removes that option completely, so it doesn't show
1126up in help text or anywhere else. E.g. if we carry on with our
1127existing \class{OptionParser}:
1128
1129\begin{verbatim}
1130parser.add_option("--dry-run", ..., help="new dry-run option")
1131\end{verbatim}
1132
1133At this point, the first \programopt{-n}/\longprogramopt{dry-run}
1134option is no longer accessible, so \module{optparse} removes it. If
1135the user asks for help, they'll get something like this:
1136
1137\begin{verbatim}
1138options:
Fred Drakecf6d74a2003-04-18 15:50:13 +00001139 ...
Neal Norwitz488609e2003-01-06 16:51:37 +00001140 -n, --noisy be noisy
1141 --dry-run new dry-run option
1142\end{verbatim}
1143
1144\subsection{Callback Options\label{optparse-callback-options}}
1145
1146If \module{optparse}'s built-in actions and types just don't fit the
1147bill for you, but it's not worth extending \module{optparse} to define
1148your own actions or types, you'll probably need to define a callback
1149option. Defining callback options is quite easy; the tricky part is
1150writing a good callback (the function that is called when
1151\module{optparse} encounters the option on the command line).
1152
1153\subsubsection{Defining a callback option\label{optparse-defining-callback-option}}
1154
1155As always, you can define a callback option either by directly
1156instantiating the \class{Option} class, or by using the
1157\method{add_option()} method of your \class{OptionParser} object. The
1158only option attribute you must specify is \var{callback}, the function
1159to call:
1160
1161\begin{verbatim}
1162parser.add_option("-c", callback=my_callback)
1163\end{verbatim}
1164
Greg Wardbf8f1b52003-05-03 19:41:45 +00001165Note that you supply a function object here---so you must have
Neal Norwitz488609e2003-01-06 16:51:37 +00001166already defined a function \function{my_callback()} when you define
1167the callback option. In this simple case, \module{optparse} knows
1168nothing about the arguments the \programopt{-c} option expects to
1169take. Usually, this means that the option doesn't take any arguments
1170-- the mere presence of \programopt{-c} on the command-line is all it
1171needs to know. In some circumstances, though, you might want your
1172callback to consume an arbitrary number of command-line arguments.
1173This is where writing callbacks gets tricky; it's covered later in
1174this document.
1175
1176There are several other option attributes that you can supply when you
1177define an option attribute:
1178
1179\begin{definitions}
1180\term{type}
1181has its usual meaning: as with the ``store'' or ``append'' actions, it
1182instructs \module{optparse} to consume one argument that must be
1183convertible to \var{type}. Rather than storing the value(s) anywhere,
1184though, \module{optparse} converts it to \var{type} and passes it to
1185your callback function.
1186
1187\term{nargs}
1188also has its usual meaning: if it is supplied and \samp{nargs > 1},
1189\module{optparse} will consume \var{nargs} arguments, each of which
1190must be convertible to \var{type}. It then passes a tuple of
1191converted values to your callback.
1192
1193\term{callback_args}
1194a tuple of extra positional arguments to pass to the callback.
1195
1196\term{callback_kwargs}
1197a dictionary of extra keyword arguments to pass to the callback.
1198\end{definitions}
1199
1200\subsubsection{How callbacks are called\label{optparse-callbacks-called}}
1201
1202All callbacks are called as follows:
1203
1204\begin{verbatim}
1205func(option, opt, value, parser, *args, **kwargs)
1206\end{verbatim}
1207
1208where
1209
1210\begin{definitions}
1211\term{option}
1212is the \class{Option} instance that's calling the callback.
1213
1214\term{opt}
1215is the option string seen on the command-line that's triggering the
1216callback. (If an abbreviated long option was used, \var{opt} will be
Greg Wardbf8f1b52003-05-03 19:41:45 +00001217the full, canonical option string---e.g. if the user puts
Neal Norwitz488609e2003-01-06 16:51:37 +00001218\longprogramopt{foo} on the command-line as an abbreviation for
1219\longprogramopt{foobar}, then \var{opt} will be
1220\longprogramopt{foobar}.)
1221
1222\term{value}
1223is the argument to this option seen on the command-line.
1224\module{optparse} will only expect an argument if \var{type} is
1225set; the type of \var{value} will be the type implied by the
Fred Drakecf6d74a2003-04-18 15:50:13 +00001226option's type (see~\ref{optparse-option-types}, ``Option types''). If
Greg Wardd7231282003-05-03 21:22:58 +00001227\var{type} for this option is \code{None} (no argument expected), then
1228\var{value} will be \code{None}. If \samp{nargs > 1}, \var{value} will
Neal Norwitz488609e2003-01-06 16:51:37 +00001229be a tuple of values of the appropriate type.
1230
1231\term{parser}
1232is the \class{OptionParser} instance driving the whole thing, mainly
1233useful because you can access some other interesting data through it,
1234as instance attributes:
1235
1236\begin{definitions}
1237\term{parser.rargs}
Greg Wardd7231282003-05-03 21:22:58 +00001238the current remaining argument list, i.e. with \var{opt} (and
Neal Norwitz488609e2003-01-06 16:51:37 +00001239\var{value}, if any) removed, and only the arguments following
1240them still there. Feel free to modify \member{parser.rargs},
1241e.g. by consuming more arguments.
1242
1243\term{parser.largs}
Greg Wardd7231282003-05-03 21:22:58 +00001244the current set of leftover arguments, i.e. arguments that have been
Neal Norwitz488609e2003-01-06 16:51:37 +00001245processed but have not been consumed as options (or arguments to
1246options). Feel free to modify \member{parser.largs} e.g. by adding
1247more arguments to it.
1248
1249\term{parser.values}
1250the object where option values are by default stored. This is useful
1251because it lets callbacks use the same mechanism as the rest of
1252\module{optparse} for storing option values; you don't need to mess
1253around with globals or closures. You can also access the value(s) of
1254any options already encountered on the command-line.
1255\end{definitions}
1256
1257\term{args}
1258is a tuple of arbitrary positional arguments supplied via the
1259\var{callback}_args option attribute.
1260
1261\term{kwargs}
1262is a dictionary of arbitrary keyword arguments supplied via
1263\var{callback_kwargs}.
1264\end{definitions}
1265
1266Since \var{args} and \var{kwargs} are optional (they are only passed
1267if you supply \var{callback_args} and/or \var{callback_kwargs} when
1268you define your callback option), the minimal callback function is:
1269
1270\begin{verbatim}
1271def my_callback (option, opt, value, parser):
1272 pass
1273\end{verbatim}
1274
1275\subsubsection{Error handling\label{optparse-callback-error-handling}}
1276
1277The callback function should raise \exception{OptionValueError} if
1278there are any problems with the option or its
1279argument(s). \module{optparse} catches this and terminates the
1280program, printing the error message you supply to stderr. Your
1281message should be clear, concise, accurate, and mention the option at
1282fault. Otherwise, the user will have a hard time figuring out what he
1283did wrong.
1284
1285\subsubsection{Examples\label{optparse-callback-examples}}
1286
1287Here's an example of a callback option that takes no arguments, and
1288simply records that the option was seen:
1289
1290\begin{verbatim}
1291def record_foo_seen (option, opt, value, parser):
1292 parser.saw_foo = 1
1293
1294parser.add_option("--foo", action="callback", callback=record_foo_seen)
1295\end{verbatim}
1296
1297Of course, you could do that with the ``store_true'' action. Here's a
1298slightly more interesting example: record the fact that
1299\programopt{-a} is seen, but blow up if it comes after \programopt{-b}
1300in the command-line.
1301
1302\begin{verbatim}
1303def check_order (option, opt, value, parser):
1304 if parser.values.b:
1305 raise OptionValueError("can't use -a after -b")
1306 parser.values.a = 1
Fred Drakecf6d74a2003-04-18 15:50:13 +00001307...
Neal Norwitz488609e2003-01-06 16:51:37 +00001308parser.add_option("-a", action="callback", callback=check_order)
1309parser.add_option("-b", action="store_true", dest="b")
1310\end{verbatim}
1311
1312If you want to reuse this callback for several similar options (set a
1313flag, but blow up if \programopt{-b} has already been seen), it needs
1314a bit of work: the error message and the flag that it sets must be
1315generalized.
1316
1317\begin{verbatim}
1318def check_order (option, opt, value, parser):
1319 if parser.values.b:
1320 raise OptionValueError("can't use %s after -b" % opt)
1321 setattr(parser.values, option.dest, 1)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001322...
Neal Norwitz488609e2003-01-06 16:51:37 +00001323parser.add_option("-a", action="callback", callback=check_order, dest='a')
1324parser.add_option("-b", action="store_true", dest="b")
1325parser.add_option("-c", action="callback", callback=check_order, dest='c')
1326\end{verbatim}
1327
Greg Wardbf8f1b52003-05-03 19:41:45 +00001328Of course, you could put any condition in there---you're not limited
Neal Norwitz488609e2003-01-06 16:51:37 +00001329to checking the values of already-defined options. For example, if
1330you have options that should not be called when the moon is full, all
1331you have to do is this:
1332
1333\begin{verbatim}
1334def check_moon (option, opt, value, parser):
1335 if is_full_moon():
1336 raise OptionValueError("%s option invalid when moon full" % opt)
1337 setattr(parser.values, option.dest, 1)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001338...
Neal Norwitz488609e2003-01-06 16:51:37 +00001339parser.add_option("--foo",
1340 action="callback", callback=check_moon, dest="foo")
1341\end{verbatim}
1342
Greg Wardbf8f1b52003-05-03 19:41:45 +00001343(The definition of \code{is_full_moon()} is left as an exercise for the
Neal Norwitz488609e2003-01-06 16:51:37 +00001344reader.)
1345
1346\strong{Fixed arguments}
1347
1348Things get slightly more interesting when you define callback options
1349that take a fixed number of arguments. Specifying that a callback
1350option takes arguments is similar to defining a ``store'' or
1351``append'' option: if you define \var{type}, then the option takes one
1352argument that must be convertible to that type; if you further define
1353\var{nargs}, then the option takes that many arguments.
1354
1355Here's an example that just emulates the standard ``store'' action:
1356
1357\begin{verbatim}
1358def store_value (option, opt, value, parser):
1359 setattr(parser.values, option.dest, value)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001360...
Neal Norwitz488609e2003-01-06 16:51:37 +00001361parser.add_option("--foo",
1362 action="callback", callback=store_value,
1363 type="int", nargs=3, dest="foo")
1364\end{verbatim}
1365
1366Note that \module{optparse} takes care of consuming 3 arguments and
1367converting them to integers for you; all you have to do is store them.
1368(Or whatever: obviously you don't need a callback for this example.
1369Use your imagination!)
1370
1371\strong{Variable arguments}
1372
1373Things get hairy when you want an option to take a variable number of
1374arguments. For this case, you have to write a callback;
1375\module{optparse} doesn't provide any built-in capabilities for it.
Fred Drakecf6d74a2003-04-18 15:50:13 +00001376You have to deal with the full-blown syntax for conventional \UNIX{}
Neal Norwitz488609e2003-01-06 16:51:37 +00001377command-line parsing. (Previously, \module{optparse} took care of
1378this for you, but I got it wrong. It was fixed at the cost of making
1379this kind of callback more complex.) In particular, callbacks have to
1380worry about bare \longprogramopt{} and \programopt{-} arguments; the
1381convention is:
1382
1383\begin{itemize}
1384\item bare \longprogramopt{}, if not the argument to some option,
1385causes command-line processing to halt and the \longprogramopt{}
1386itself is lost.
1387
1388\item bare \programopt{-} similarly causes command-line processing to
1389halt, but the \programopt{-} itself is kept.
1390
1391\item either \longprogramopt{} or \programopt{-} can be option
1392arguments.
1393\end{itemize}
1394
1395If you want an option that takes a variable number of arguments, there
1396are several subtle, tricky issues to worry about. The exact
1397implementation you choose will be based on which trade-offs you're
1398willing to make for your application (which is why \module{optparse}
1399doesn't support this sort of thing directly).
1400
1401Nevertheless, here's a stab at a callback for an option with variable
1402arguments:
1403
1404\begin{verbatim}
1405def varargs (option, opt, value, parser):
1406 assert value is None
1407 done = 0
1408 value = []
1409 rargs = parser.rargs
1410 while rargs:
1411 arg = rargs[0]
1412
1413 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1414 # etc. Note that this also stops on "-3" or "-3.0", so if
1415 # your option takes numeric values, you will need to handle
1416 # this.
1417 if ((arg[:2] == "--" and len(arg) > 2) or
1418 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1419 break
1420 else:
1421 value.append(arg)
1422 del rargs[0]
1423
1424 setattr(parser.values, option.dest, value)
1425
Fred Drakecf6d74a2003-04-18 15:50:13 +00001426...
Neal Norwitz488609e2003-01-06 16:51:37 +00001427parser.add_option("-c", "--callback",
1428 action="callback", callback=varargs)
1429\end{verbatim}
1430
1431The main weakness with this particular implementation is that negative
1432numbers in the arguments following \programopt{-c} will be interpreted
1433as further options, rather than as arguments to \programopt{-c}.
1434Fixing this is left as an exercise for the reader.
1435
1436\subsection{Extending \module{optparse}\label{optparse-extending}}
1437
1438Since the two major controlling factors in how \module{optparse}
1439interprets command-line options are the action and type of each
1440option, the most likely direction of extension is to add new actions
1441and new types.
1442
1443Also, the examples section includes several demonstrations of
Greg Wardd7231282003-05-03 21:22:58 +00001444extending \module{optparse} in different ways: e.g. a case-insensitive
Neal Norwitz488609e2003-01-06 16:51:37 +00001445option parser, or two kinds of option parsers that implement
1446``required options''.
1447
1448\subsubsection{Adding new types\label{optparse-adding-types}}
1449
1450To add new types, you need to define your own subclass of
1451\module{optparse}'s \class{Option} class. This class has a couple of
1452attributes that define \module{optparse}'s types: \member{TYPES} and
1453\member{TYPE_CHECKER}.
1454
1455\member{TYPES} is a tuple of type names; in your subclass, simply
1456define a new tuple \member{TYPES} that builds on the standard one.
1457
1458\member{TYPE_CHECKER} is a dictionary mapping type names to
1459type-checking functions. A type-checking function has the following
1460signature:
1461
1462\begin{verbatim}
1463def check_foo (option : Option, opt : string, value : string)
1464 -> foo
1465\end{verbatim}
1466
1467You can name it whatever you like, and make it return any type you
1468like. The value returned by a type-checking function will wind up in
1469the \class{OptionValues} instance returned by
1470\method{OptionParser.parse_args()}, or be passed to callbacks as the
1471\var{value} parameter.
1472
1473Your type-checking function should raise \exception{OptionValueError}
1474if it encounters any problems. \exception{OptionValueError} takes a
1475single string argument, which is passed as-is to
1476\class{OptionParser}'s \method{error()} method, which in turn prepends
1477the program name and the string ``error:'' and prints everything to
1478stderr before terminating the process.
1479
1480Here's a silly example that demonstrates adding a ``complex'' option
1481type to parse Python-style complex numbers on the command line. (This
1482is even sillier than it used to be, because \module{optparse} 1.3 adds
1483built-in support for complex numbers [purely for completeness], but
1484never mind.)
1485
1486First, the necessary imports:
1487
1488\begin{verbatim}
1489from copy import copy
1490from optparse import Option, OptionValueError
1491\end{verbatim}
1492
1493You need to define your type-checker first, since it's referred to
1494later (in the \member{TYPE_CHECKER} class attribute of your
1495\class{Option} subclass):
1496
1497\begin{verbatim}
1498def check_complex (option, opt, value):
1499 try:
1500 return complex(value)
1501 except ValueError:
1502 raise OptionValueError(
1503 "option %s: invalid complex value: %r" % (opt, value))
1504\end{verbatim}
1505
1506Finally, the \class{Option} subclass:
1507
1508\begin{verbatim}
1509class MyOption (Option):
1510 TYPES = Option.TYPES + ("complex",)
1511 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1512 TYPE_CHECKER["complex"] = check_complex
1513\end{verbatim}
1514
1515(If we didn't make a \function{copy()} of
1516\member{Option.TYPE_CHECKER}, we would end up modifying the
1517\member{TYPE_CHECKER} attribute of \module{optparse}'s Option class.
1518This being Python, nothing stops you from doing that except good
1519manners and common sense.)
1520
1521That's it! Now you can write a script that uses the new option type
1522just like any other \module{optparse}-based script, except you have to
1523instruct your \class{OptionParser} to use \class{MyOption} instead of
1524\class{Option}:
1525
1526\begin{verbatim}
1527parser = OptionParser(option_class=MyOption)
1528parser.add_option("-c", action="store", type="complex", dest="c")
1529\end{verbatim}
1530
1531Alternately, you can build your own option list and pass it to
1532\class{OptionParser}; if you don't use \method{add_option()} in the
1533above way, you don't need to tell \class{OptionParser} which option
1534class to use:
1535
1536\begin{verbatim}
1537option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1538parser = OptionParser(option_list=option_list)
1539\end{verbatim}
1540
1541\subsubsection{Adding new actions\label{optparse-adding-actions}}
1542
1543Adding new actions is a bit trickier, because you have to understand
1544that \module{optparse} has a couple of classifications for actions:
1545
1546\begin{definitions}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001547\term{``store'' actions}
Neal Norwitz488609e2003-01-06 16:51:37 +00001548 actions that result in \module{optparse} storing a value to an attribute
Greg Wardbf8f1b52003-05-03 19:41:45 +00001549 of the OptionValues instance; these options require a \var{dest}
Neal Norwitz488609e2003-01-06 16:51:37 +00001550 attribute to be supplied to the Option constructor
Greg Wardbf8f1b52003-05-03 19:41:45 +00001551\term{``typed'' actions}
Neal Norwitz488609e2003-01-06 16:51:37 +00001552 actions that take a value from the command line and expect it to be
1553 of a certain type; or rather, a string that can be converted to a
Greg Wardbf8f1b52003-05-03 19:41:45 +00001554 certain type. These options require a \var{type} attribute to the
Neal Norwitz488609e2003-01-06 16:51:37 +00001555 Option constructor.
1556\end{definitions}
1557
Greg Wardbf8f1b52003-05-03 19:41:45 +00001558Some default ``store'' actions are \var{store}, \var{store_const},
1559\var{append}, and \var{count}. The default ``typed'' actions are
1560\var{store}, \var{append}, and \var{callback}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001561
1562When you add an action, you need to decide if it's a ``store'' action,
1563a ``typed'', neither, or both. Three class attributes of
1564\class{Option} (or your \class{Option} subclass) control this:
1565
1566\begin{memberdesc}{ACTIONS}
1567 All actions must be listed as strings in ACTIONS.
1568\end{memberdesc}
1569\begin{memberdesc}{STORE_ACTIONS}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001570 ``store'' actions are additionally listed here.
Neal Norwitz488609e2003-01-06 16:51:37 +00001571\end{memberdesc}
1572\begin{memberdesc}{TYPED_ACTIONS}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001573 ``typed'' actions are additionally listed here.
Neal Norwitz488609e2003-01-06 16:51:37 +00001574\end{memberdesc}
1575
1576In order to actually implement your new action, you must override
1577\class{Option}'s \method{take_action()} method and add a case that
1578recognizes your action.
1579
1580For example, let's add an ``extend'' action. This is similar to the
1581standard ``append'' action, but instead of taking a single value from
1582the command-line and appending it to an existing list, ``extend'' will
1583take multiple values in a single comma-delimited string, and extend an
1584existing list with them. That is, if \longprogramopt{names} is an
1585``extend'' option of type string, the command line:
1586
1587\begin{verbatim}
1588--names=foo,bar --names blah --names ding,dong
1589\end{verbatim}
1590
1591would result in a list:
1592
1593\begin{verbatim}
1594["foo", "bar", "blah", "ding", "dong"]
1595\end{verbatim}
1596
1597Again we define a subclass of \class{Option}:
1598
1599\begin{verbatim}
1600class MyOption (Option):
1601
1602 ACTIONS = Option.ACTIONS + ("extend",)
1603 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1604 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1605
1606 def take_action (self, action, dest, opt, value, values, parser):
1607 if action == "extend":
1608 lvalue = value.split(",")
1609 values.ensure_value(dest, []).extend(lvalue)
1610 else:
1611 Option.take_action(
1612 self, action, dest, opt, value, values, parser)
1613\end{verbatim}
1614
1615Features of note:
1616
1617\begin{itemize}
1618\item ``extend'' both expects a value on the command-line and stores that
1619value somewhere, so it goes in both \member{STORE_ACTIONS} and
1620\member{TYPED_ACTIONS}.
1621
1622\item \method{MyOption.take_action()} implements just this one new
1623action, and passes control back to \method{Option.take_action()} for
1624the standard \module{optparse} actions.
1625
1626\item \var{values} is an instance of the \class{Values} class, which
1627provides the very useful \method{ensure_value()}
1628method. \method{ensure_value()} is essentially \function{getattr()}
1629with a safety valve; it is called as:
1630
1631\begin{verbatim}
1632values.ensure_value(attr, value)
1633\end{verbatim}
1634\end{itemize}
1635
1636If the \member{attr} attribute of \var{values} doesn't exist or is
Greg Wardd7231282003-05-03 21:22:58 +00001637\code{None}, then \method{ensure_value()} first sets it to \var{value}, and
Neal Norwitz488609e2003-01-06 16:51:37 +00001638then returns \var{value}. This is very handy for actions like
1639``extend'', ``append'', and ``count'', all of which accumulate data in
1640a variable and expect that variable to be of a certain type (a list
1641for the first two, an integer for the latter). Using
1642\method{ensure_value()} means that scripts using your action don't
1643have to worry about setting a default value for the option
Greg Wardd7231282003-05-03 21:22:58 +00001644destinations in question; they can just leave the default as \code{None} and
Neal Norwitz488609e2003-01-06 16:51:37 +00001645\method{ensure_value()} will take care of getting it right when it's
1646needed.
1647
1648\subsubsection{Other reasons to extend \module{optparse}\label{optparse-extending-other-reasons}}
1649
1650Adding new types and new actions are the big, obvious reasons why you
1651might want to extend \module{optparse}. I can think of at least two
1652other areas to play with.
1653
1654First, the simple one: \class{OptionParser} tries to be helpful by
Greg Wardd7231282003-05-03 21:22:58 +00001655calling \function{sys.exit()} when appropriate, i.e. when there's an
Neal Norwitz488609e2003-01-06 16:51:37 +00001656error on the command-line or when the user requests help. In the
1657former case, the traditional course of letting the script crash with a
1658traceback is unacceptable; it will make users think there's a bug in
1659your script when they make a command-line error. In the latter case,
1660there's generally not much point in carrying on after printing a help
1661message.
1662
1663If this behaviour bothers you, it shouldn't be too hard to ``fix'' it.
1664You'll have to
1665
1666\begin{enumerate}
1667\item subclass OptionParser and override the error() method
Greg Wardbf8f1b52003-05-03 19:41:45 +00001668\item subclass Option and override the take_action() method---you'll
1669 need to provide your own handling of the ``help'' action that
Neal Norwitz488609e2003-01-06 16:51:37 +00001670 doesn't call sys.exit()
1671\end{enumerate}
1672
1673The second, much more complex, possibility is to override the
1674command-line syntax implemented by \module{optparse}. In this case,
1675you'd leave the whole machinery of option actions and types alone, but
1676rewrite the code that processes \var{sys.argv}. You'll need to
1677subclass \class{OptionParser} in any case; depending on how radical a
1678rewrite you want, you'll probably need to override one or all of
1679\method{parse_args()}, \method{_process_long_opt()}, and
1680\method{_process_short_opts()}.
1681
1682Both of these are left as an exercise for the reader. I have not
1683tried to implement either myself, since I'm quite happy with
1684\module{optparse}'s default behaviour (naturally).
1685
1686Happy hacking, and don't forget: Use the Source, Luke.
1687
1688\subsubsection{Examples\label{optparse-extending-examples}}
1689
1690Here are a few examples of extending the \module{optparse} module.
1691
1692First, let's change the option-parsing to be case-insensitive:
1693
1694\verbatiminput{caseless.py}
1695
1696And two ways of implementing ``required options'' with
1697\module{optparse}.
1698
1699Version 1: Add a method to \class{OptionParser} which applications
1700must call after parsing arguments:
1701
1702\verbatiminput{required_1.py}
1703
1704Version 2: Extend \class{Option} and add a \member{required}
1705attribute; extend \class{OptionParser} to ensure that required options
1706are present after parsing:
1707
Fred Drakecf6d74a2003-04-18 15:50:13 +00001708\verbatiminput{required_2.py}