blob: 118c2c48ab967cda4504d1fb1ddfca688db75ddc [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
Fred Drakebd12b182004-01-27 21:08:04 +000032options, args = parser.parse_args()
Neal Norwitz488609e2003-01-06 16:51:37 +000033\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
Fred Drake853276e2003-07-16 17:58:38 +000085\code{sys.argv[1:]}. (\code{sys.argv[0]} is the name of the program
Neal Norwitz488609e2003-01-06 16:51:37 +000086being 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
Fred Drake853276e2003-07-16 17:58:38 +000090\code{sys.argv[1:]}, so you should read ``argument'' as ``an element of
91\code{sys.argv[1:]}, or of some other list provided as a substitute for
92\code{sys.argv[1:]}''.
Neal Norwitz488609e2003-01-06 16:51:37 +000093
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"]
Fred Drakebd12b182004-01-27 21:08:04 +0000305options, args = parser.parse_args(args)
Neal Norwitz488609e2003-01-06 16:51:37 +0000306\end{verbatim}
307
308(Note that if you don't pass an argument list to
Fred Drake853276e2003-07-16 17:58:38 +0000309\function{parse_args()}, it automatically uses \code{sys.argv[1:]}.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000310
Greg Wardd7231282003-05-03 21:22:58 +0000311When \module{optparse} sees the \programopt{-f}, it consumes the next
Fred Drake853276e2003-07-16 17:58:38 +0000312argument---\code{foo.txt}---and stores it in the \member{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}
Fred Drakebd12b182004-01-27 21:08:04 +0000338options, args = parser.parse_args(["-n42"])
Neal Norwitz488609e2003-01-06 16:51:37 +0000339print 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
Fred Drake853276e2003-07-16 17:58:38 +0000357\member{foo_bar}. If there are no long option strings,
Neal Norwitz488609e2003-01-06 16:51:37 +0000358\module{optparse} looks at the first short option: the default
Fred Drake853276e2003-07-16 17:58:38 +0000359destination for \programopt{-f} is \member{f}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000360
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
Fred Drake853276e2003-07-16 17:58:38 +0000383\code{options.verbose} to \code{True}; when it sees \programopt{-q}, it
384sets \code{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
Fred Drake853276e2003-07-16 17:58:38 +0000397\module{optparse} to set \member{verbose} to \code{True} unless
Greg Ward1f535172003-05-03 20:13:08 +0000398\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
Fred Drake853276e2003-07-16 17:58:38 +0000414destination (the \member{verbose} variable).
Neal Norwitz488609e2003-01-06 16:51:37 +0000415
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
Fred Drake853276e2003-07-16 17:58:38 +0000423Again, the default value for \member{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
Fred Drake853276e2003-07-16 17:58:38 +0000431to do is supply a \var{help} argument when you add an option. Let's
Neal Norwitz488609e2003-01-06 16:51:37 +0000432create 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
Fred Drakebd12b182004-01-27 21:08:04 +0000608 options, args = parser.parse_args()
Neal Norwitz488609e2003-01-06 16:51:37 +0000609 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
Fred Drake853276e2003-07-16 17:58:38 +0000741\code{values} object:
Neal Norwitz488609e2003-01-06 16:51:37 +0000742
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},
Fred Drake853276e2003-07-16 17:58:38 +0000789``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.,
Fred Drake853276e2003-07-16 17:58:38 +0000798\longprogramopt{foo-bar} becomes \member{foo_bar}). If there are no long
Neal Norwitz488609e2003-01-06 16:51:37 +0000799option strings, \module{optparse} derives a destination from the first
Fred Drake853276e2003-07-16 17:58:38 +0000800short option string (e.g., \programopt{-f} becomes \member{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)
Raymond Hettinger52136a82003-05-10 03:35:37 +0000965])
Neal Norwitz488609e2003-01-06 16:51:37 +0000966\end{verbatim}
967
Greg Wardb4e33192003-05-03 19:16:36 +0000968If \module{optparse} sees either \programopt{-h} or
969\longprogramopt{help} on the command line, it will print something
970like the following help message to stdout:
Neal Norwitz488609e2003-01-06 16:51:37 +0000971
972\begin{verbatim}
973usage: <yourscript> [options]
974
975options:
976 -h, --help Show this help message and exit
977 -v Be moderately verbose
978 --file=FILENAME Input file to read data from
979\end{verbatim}
980
981After printing the help message, \module{optparse} terminates your process
982with \code{sys.exit(0)}.
983
984\term{version} [required: none]
985
986Prints the version number supplied to the \class{OptionParser} to
987stdout and exits. The version number is actually formatted and
988printed by the \method{print_version()} method of
989\class{OptionParser}. Generally only relevant if the \var{version}
990argument is supplied to the \class{OptionParser} constructor.
991\end{definitions}
992
993\subsubsection{Option types\label{optparse-option-types}}
994
995\module{optparse} supports six option types out of the box: \dfn{string},
996\dfn{int}, \dfn{long}, \dfn{choice}, \dfn{float} and \dfn{complex}.
997(Of these, string, int, float, and choice are the most commonly used
Greg Wardd7231282003-05-03 21:22:58 +0000998---long and complex are there mainly for completeness.) It's easy to
Neal Norwitz488609e2003-01-06 16:51:37 +0000999add new option types by subclassing the \class{Option} class; see
Fred Drakecf6d74a2003-04-18 15:50:13 +00001000section~\ref{optparse-extending}, ``Extending \module{optparse}.''
Neal Norwitz488609e2003-01-06 16:51:37 +00001001
1002Arguments to string options are not checked or converted in any way:
1003the text on the command line is stored in the destination (or passed
1004to the callback) as-is.
1005
1006Integer arguments are passed to \function{int()} to convert them to
1007Python integers. If \function{int()} fails, so will
1008\module{optparse}, although with a more useful error message.
1009Internally, \module{optparse} raises \exception{OptionValueError} in
1010\function{optparse.check_builtin()}; at a higher level (in
Greg Wardd7231282003-05-03 21:22:58 +00001011\class{OptionParser}), \module{optparse} catches this exception and
1012terminates your program with a useful error message.
Neal Norwitz488609e2003-01-06 16:51:37 +00001013
1014Likewise, float arguments are passed to \function{float()} for
1015conversion, long arguments to \function{long()}, and complex arguments
1016to \function{complex()}. Apart from that, they are handled
1017identically to integer arguments.
1018
1019Choice options are a subtype of string options. A master list or
1020tuple of choices (strings) must be passed to the option constructor
1021(\function{make_option()} or \method{OptionParser.add_option()}) as
Greg Wardd7231282003-05-03 21:22:58 +00001022the \var{choices} keyword argument. Choice option arguments are
Neal Norwitz488609e2003-01-06 16:51:37 +00001023compared against this master list in
1024\function{optparse.check_choice()}, and \exception{OptionValueError}
1025is raised if an unknown string is given.
1026
1027\subsubsection{Querying and manipulating your option parser\label{optparse-querying-and-manipulating}}
1028
1029Sometimes, it's useful to poke around your option parser and see what's
1030there. \class{OptionParser} provides a couple of methods to help you out:
1031
1032\begin{methoddesc}{has_option}{opt_str}
1033 Given an option string such as \programopt{-q} or
1034 \longprogramopt{verbose}, returns true if the \class{OptionParser}
1035 has an option with that option string.
1036\end{methoddesc}
1037
1038\begin{methoddesc}{get_option}{opt_str}
1039 Returns the \class{Option} instance that implements the option
Greg Wardd7231282003-05-03 21:22:58 +00001040 string you supplied, or \code{None} if no options implement it.
Neal Norwitz488609e2003-01-06 16:51:37 +00001041\end{methoddesc}
1042
1043\begin{methoddesc}{remove_option}{opt_str}
1044 If the \class{OptionParser} has an option corresponding to
1045 \var{opt_str}, that option is removed. If that option provided
1046 any other option strings, all of those option strings become
1047 invalid.
1048
1049 If \var{opt_str} does not occur in any option belonging to this
1050 \class{OptionParser}, raises \exception{ValueError}.
1051\end{methoddesc}
1052
1053\subsubsection{Conflicts between options\label{optparse-conflicts}}
1054
1055If you're not careful, it's easy to define conflicting options:
1056
1057\begin{verbatim}
1058parser.add_option("-n", "--dry-run", ...)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001059...
Neal Norwitz488609e2003-01-06 16:51:37 +00001060parser.add_option("-n", "--noisy", ...)
1061\end{verbatim}
1062
1063(This is even easier to do if you've defined your own
1064\class{OptionParser} subclass with some standard options.)
1065
1066On the assumption that this is usually a mistake, \module{optparse}
Fred Drakecf6d74a2003-04-18 15:50:13 +00001067raises an exception (\exception{OptionConflictError}) by default when
1068this happens. Since this is an easily-fixed programming error, you
Greg Wardbf8f1b52003-05-03 19:41:45 +00001069shouldn't try to catch this exception---fix your mistake and get on
Fred Drakecf6d74a2003-04-18 15:50:13 +00001070with life.
Neal Norwitz488609e2003-01-06 16:51:37 +00001071
1072Sometimes, you want newer options to deliberately replace the option
1073strings used by older options. You can achieve this by calling:
1074
1075\begin{verbatim}
1076parser.set_conflict_handler("resolve")
1077\end{verbatim}
1078
1079which instructs \module{optparse} to resolve option conflicts
1080intelligently.
1081
1082Here's how it works: every time you add an option, \module{optparse}
1083checks for conflicts with previously-added options. If it finds any,
1084it invokes the conflict-handling mechanism you specify either to the
1085\class{OptionParser} constructor:
1086
1087\begin{verbatim}
1088parser = OptionParser(..., conflict_handler="resolve")
1089\end{verbatim}
1090
1091or via the \method{set_conflict_handler()} method.
1092
Greg Wardd7231282003-05-03 21:22:58 +00001093The default conflict-handling mechanism is \code{error}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001094
1095Here's an example: first, define an \class{OptionParser} set to
1096resolve conflicts intelligently:
1097
1098\begin{verbatim}
1099parser = OptionParser(conflict_handler="resolve")
1100\end{verbatim}
1101
1102Now add all of our options:
1103
1104\begin{verbatim}
1105parser.add_option("-n", "--dry-run", ..., help="original dry-run option")
Fred Drakecf6d74a2003-04-18 15:50:13 +00001106...
Neal Norwitz488609e2003-01-06 16:51:37 +00001107parser.add_option("-n", "--noisy", ..., help="be noisy")
1108\end{verbatim}
1109
1110At this point, \module{optparse} detects that a previously-added option is already
1111using the \programopt{-n} option string. Since \code{conflict_handler
1112== "resolve"}, it resolves the situation by removing \programopt{-n}
1113from the earlier option's list of option strings. Now,
1114\longprogramopt{dry-run} is the only way for the user to activate that
1115option. If the user asks for help, the help message will reflect
1116that, e.g.:
1117
1118\begin{verbatim}
1119options:
1120 --dry-run original dry-run option
Fred Drakecf6d74a2003-04-18 15:50:13 +00001121 ...
Neal Norwitz488609e2003-01-06 16:51:37 +00001122 -n, --noisy be noisy
1123\end{verbatim}
1124
1125Note that it's possible to whittle away the option strings for a
1126previously-added option until there are none left, and the user has no
1127way of invoking that option from the command-line. In that case,
1128\module{optparse} removes that option completely, so it doesn't show
1129up in help text or anywhere else. E.g. if we carry on with our
1130existing \class{OptionParser}:
1131
1132\begin{verbatim}
1133parser.add_option("--dry-run", ..., help="new dry-run option")
1134\end{verbatim}
1135
1136At this point, the first \programopt{-n}/\longprogramopt{dry-run}
1137option is no longer accessible, so \module{optparse} removes it. If
1138the user asks for help, they'll get something like this:
1139
1140\begin{verbatim}
1141options:
Fred Drakecf6d74a2003-04-18 15:50:13 +00001142 ...
Neal Norwitz488609e2003-01-06 16:51:37 +00001143 -n, --noisy be noisy
1144 --dry-run new dry-run option
1145\end{verbatim}
1146
1147\subsection{Callback Options\label{optparse-callback-options}}
1148
1149If \module{optparse}'s built-in actions and types just don't fit the
1150bill for you, but it's not worth extending \module{optparse} to define
1151your own actions or types, you'll probably need to define a callback
1152option. Defining callback options is quite easy; the tricky part is
1153writing a good callback (the function that is called when
1154\module{optparse} encounters the option on the command line).
1155
1156\subsubsection{Defining a callback option\label{optparse-defining-callback-option}}
1157
1158As always, you can define a callback option either by directly
1159instantiating the \class{Option} class, or by using the
1160\method{add_option()} method of your \class{OptionParser} object. The
1161only option attribute you must specify is \var{callback}, the function
1162to call:
1163
1164\begin{verbatim}
1165parser.add_option("-c", callback=my_callback)
1166\end{verbatim}
1167
Greg Wardbf8f1b52003-05-03 19:41:45 +00001168Note that you supply a function object here---so you must have
Neal Norwitz488609e2003-01-06 16:51:37 +00001169already defined a function \function{my_callback()} when you define
1170the callback option. In this simple case, \module{optparse} knows
1171nothing about the arguments the \programopt{-c} option expects to
1172take. Usually, this means that the option doesn't take any arguments
1173-- the mere presence of \programopt{-c} on the command-line is all it
1174needs to know. In some circumstances, though, you might want your
1175callback to consume an arbitrary number of command-line arguments.
1176This is where writing callbacks gets tricky; it's covered later in
1177this document.
1178
1179There are several other option attributes that you can supply when you
1180define an option attribute:
1181
1182\begin{definitions}
1183\term{type}
1184has its usual meaning: as with the ``store'' or ``append'' actions, it
1185instructs \module{optparse} to consume one argument that must be
1186convertible to \var{type}. Rather than storing the value(s) anywhere,
1187though, \module{optparse} converts it to \var{type} and passes it to
1188your callback function.
1189
1190\term{nargs}
1191also has its usual meaning: if it is supplied and \samp{nargs > 1},
1192\module{optparse} will consume \var{nargs} arguments, each of which
1193must be convertible to \var{type}. It then passes a tuple of
1194converted values to your callback.
1195
1196\term{callback_args}
1197a tuple of extra positional arguments to pass to the callback.
1198
1199\term{callback_kwargs}
1200a dictionary of extra keyword arguments to pass to the callback.
1201\end{definitions}
1202
1203\subsubsection{How callbacks are called\label{optparse-callbacks-called}}
1204
1205All callbacks are called as follows:
1206
1207\begin{verbatim}
1208func(option, opt, value, parser, *args, **kwargs)
1209\end{verbatim}
1210
1211where
1212
1213\begin{definitions}
1214\term{option}
1215is the \class{Option} instance that's calling the callback.
1216
1217\term{opt}
1218is the option string seen on the command-line that's triggering the
1219callback. (If an abbreviated long option was used, \var{opt} will be
Fred Drake853276e2003-07-16 17:58:38 +00001220the full, canonical option string---for example, if the user puts
Neal Norwitz488609e2003-01-06 16:51:37 +00001221\longprogramopt{foo} on the command-line as an abbreviation for
1222\longprogramopt{foobar}, then \var{opt} will be
1223\longprogramopt{foobar}.)
1224
1225\term{value}
1226is the argument to this option seen on the command-line.
1227\module{optparse} will only expect an argument if \var{type} is
1228set; the type of \var{value} will be the type implied by the
Fred Drakecf6d74a2003-04-18 15:50:13 +00001229option's type (see~\ref{optparse-option-types}, ``Option types''). If
Greg Wardd7231282003-05-03 21:22:58 +00001230\var{type} for this option is \code{None} (no argument expected), then
1231\var{value} will be \code{None}. If \samp{nargs > 1}, \var{value} will
Neal Norwitz488609e2003-01-06 16:51:37 +00001232be a tuple of values of the appropriate type.
1233
1234\term{parser}
1235is the \class{OptionParser} instance driving the whole thing, mainly
1236useful because you can access some other interesting data through it,
1237as instance attributes:
1238
1239\begin{definitions}
1240\term{parser.rargs}
Greg Wardd7231282003-05-03 21:22:58 +00001241the current remaining argument list, i.e. with \var{opt} (and
Neal Norwitz488609e2003-01-06 16:51:37 +00001242\var{value}, if any) removed, and only the arguments following
1243them still there. Feel free to modify \member{parser.rargs},
1244e.g. by consuming more arguments.
1245
1246\term{parser.largs}
Greg Wardd7231282003-05-03 21:22:58 +00001247the current set of leftover arguments, i.e. arguments that have been
Neal Norwitz488609e2003-01-06 16:51:37 +00001248processed but have not been consumed as options (or arguments to
1249options). Feel free to modify \member{parser.largs} e.g. by adding
1250more arguments to it.
1251
1252\term{parser.values}
1253the object where option values are by default stored. This is useful
1254because it lets callbacks use the same mechanism as the rest of
1255\module{optparse} for storing option values; you don't need to mess
1256around with globals or closures. You can also access the value(s) of
1257any options already encountered on the command-line.
1258\end{definitions}
1259
1260\term{args}
1261is a tuple of arbitrary positional arguments supplied via the
1262\var{callback}_args option attribute.
1263
1264\term{kwargs}
1265is a dictionary of arbitrary keyword arguments supplied via
1266\var{callback_kwargs}.
1267\end{definitions}
1268
1269Since \var{args} and \var{kwargs} are optional (they are only passed
1270if you supply \var{callback_args} and/or \var{callback_kwargs} when
1271you define your callback option), the minimal callback function is:
1272
1273\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001274def my_callback(option, opt, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001275 pass
1276\end{verbatim}
1277
1278\subsubsection{Error handling\label{optparse-callback-error-handling}}
1279
1280The callback function should raise \exception{OptionValueError} if
1281there are any problems with the option or its
1282argument(s). \module{optparse} catches this and terminates the
1283program, printing the error message you supply to stderr. Your
1284message should be clear, concise, accurate, and mention the option at
1285fault. Otherwise, the user will have a hard time figuring out what he
1286did wrong.
1287
1288\subsubsection{Examples\label{optparse-callback-examples}}
1289
1290Here's an example of a callback option that takes no arguments, and
1291simply records that the option was seen:
1292
1293\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001294def record_foo_seen(option, opt, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001295 parser.saw_foo = 1
1296
1297parser.add_option("--foo", action="callback", callback=record_foo_seen)
1298\end{verbatim}
1299
1300Of course, you could do that with the ``store_true'' action. Here's a
1301slightly more interesting example: record the fact that
1302\programopt{-a} is seen, but blow up if it comes after \programopt{-b}
1303in the command-line.
1304
1305\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001306def check_order(option, opt, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001307 if parser.values.b:
1308 raise OptionValueError("can't use -a after -b")
1309 parser.values.a = 1
Fred Drakecf6d74a2003-04-18 15:50:13 +00001310...
Neal Norwitz488609e2003-01-06 16:51:37 +00001311parser.add_option("-a", action="callback", callback=check_order)
1312parser.add_option("-b", action="store_true", dest="b")
1313\end{verbatim}
1314
1315If you want to reuse this callback for several similar options (set a
1316flag, but blow up if \programopt{-b} has already been seen), it needs
1317a bit of work: the error message and the flag that it sets must be
1318generalized.
1319
1320\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001321def check_order(option, opt, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001322 if parser.values.b:
1323 raise OptionValueError("can't use %s after -b" % opt)
1324 setattr(parser.values, option.dest, 1)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001325...
Neal Norwitz488609e2003-01-06 16:51:37 +00001326parser.add_option("-a", action="callback", callback=check_order, dest='a')
1327parser.add_option("-b", action="store_true", dest="b")
1328parser.add_option("-c", action="callback", callback=check_order, dest='c')
1329\end{verbatim}
1330
Greg Wardbf8f1b52003-05-03 19:41:45 +00001331Of course, you could put any condition in there---you're not limited
Neal Norwitz488609e2003-01-06 16:51:37 +00001332to checking the values of already-defined options. For example, if
1333you have options that should not be called when the moon is full, all
1334you have to do is this:
1335
1336\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001337def check_moon(option, opt, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001338 if is_full_moon():
1339 raise OptionValueError("%s option invalid when moon full" % opt)
1340 setattr(parser.values, option.dest, 1)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001341...
Neal Norwitz488609e2003-01-06 16:51:37 +00001342parser.add_option("--foo",
1343 action="callback", callback=check_moon, dest="foo")
1344\end{verbatim}
1345
Greg Wardbf8f1b52003-05-03 19:41:45 +00001346(The definition of \code{is_full_moon()} is left as an exercise for the
Neal Norwitz488609e2003-01-06 16:51:37 +00001347reader.)
1348
1349\strong{Fixed arguments}
1350
1351Things get slightly more interesting when you define callback options
1352that take a fixed number of arguments. Specifying that a callback
1353option takes arguments is similar to defining a ``store'' or
1354``append'' option: if you define \var{type}, then the option takes one
1355argument that must be convertible to that type; if you further define
1356\var{nargs}, then the option takes that many arguments.
1357
1358Here's an example that just emulates the standard ``store'' action:
1359
1360\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001361def store_value(option, opt, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001362 setattr(parser.values, option.dest, value)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001363...
Neal Norwitz488609e2003-01-06 16:51:37 +00001364parser.add_option("--foo",
1365 action="callback", callback=store_value,
1366 type="int", nargs=3, dest="foo")
1367\end{verbatim}
1368
1369Note that \module{optparse} takes care of consuming 3 arguments and
1370converting them to integers for you; all you have to do is store them.
1371(Or whatever: obviously you don't need a callback for this example.
1372Use your imagination!)
1373
1374\strong{Variable arguments}
1375
1376Things get hairy when you want an option to take a variable number of
1377arguments. For this case, you have to write a callback;
1378\module{optparse} doesn't provide any built-in capabilities for it.
Fred Drakecf6d74a2003-04-18 15:50:13 +00001379You have to deal with the full-blown syntax for conventional \UNIX{}
Neal Norwitz488609e2003-01-06 16:51:37 +00001380command-line parsing. (Previously, \module{optparse} took care of
1381this for you, but I got it wrong. It was fixed at the cost of making
1382this kind of callback more complex.) In particular, callbacks have to
1383worry about bare \longprogramopt{} and \programopt{-} arguments; the
1384convention is:
1385
1386\begin{itemize}
1387\item bare \longprogramopt{}, if not the argument to some option,
1388causes command-line processing to halt and the \longprogramopt{}
1389itself is lost.
1390
1391\item bare \programopt{-} similarly causes command-line processing to
1392halt, but the \programopt{-} itself is kept.
1393
1394\item either \longprogramopt{} or \programopt{-} can be option
1395arguments.
1396\end{itemize}
1397
1398If you want an option that takes a variable number of arguments, there
1399are several subtle, tricky issues to worry about. The exact
1400implementation you choose will be based on which trade-offs you're
1401willing to make for your application (which is why \module{optparse}
1402doesn't support this sort of thing directly).
1403
1404Nevertheless, here's a stab at a callback for an option with variable
1405arguments:
1406
1407\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001408def varargs(option, opt, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001409 assert value is None
1410 done = 0
1411 value = []
1412 rargs = parser.rargs
1413 while rargs:
1414 arg = rargs[0]
1415
1416 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1417 # etc. Note that this also stops on "-3" or "-3.0", so if
1418 # your option takes numeric values, you will need to handle
1419 # this.
1420 if ((arg[:2] == "--" and len(arg) > 2) or
1421 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1422 break
1423 else:
1424 value.append(arg)
1425 del rargs[0]
1426
1427 setattr(parser.values, option.dest, value)
1428
Fred Drakecf6d74a2003-04-18 15:50:13 +00001429...
Neal Norwitz488609e2003-01-06 16:51:37 +00001430parser.add_option("-c", "--callback",
1431 action="callback", callback=varargs)
1432\end{verbatim}
1433
1434The main weakness with this particular implementation is that negative
1435numbers in the arguments following \programopt{-c} will be interpreted
1436as further options, rather than as arguments to \programopt{-c}.
1437Fixing this is left as an exercise for the reader.
1438
1439\subsection{Extending \module{optparse}\label{optparse-extending}}
1440
1441Since the two major controlling factors in how \module{optparse}
1442interprets command-line options are the action and type of each
1443option, the most likely direction of extension is to add new actions
1444and new types.
1445
1446Also, the examples section includes several demonstrations of
Greg Wardd7231282003-05-03 21:22:58 +00001447extending \module{optparse} in different ways: e.g. a case-insensitive
Neal Norwitz488609e2003-01-06 16:51:37 +00001448option parser, or two kinds of option parsers that implement
1449``required options''.
1450
1451\subsubsection{Adding new types\label{optparse-adding-types}}
1452
1453To add new types, you need to define your own subclass of
1454\module{optparse}'s \class{Option} class. This class has a couple of
1455attributes that define \module{optparse}'s types: \member{TYPES} and
1456\member{TYPE_CHECKER}.
1457
1458\member{TYPES} is a tuple of type names; in your subclass, simply
1459define a new tuple \member{TYPES} that builds on the standard one.
1460
1461\member{TYPE_CHECKER} is a dictionary mapping type names to
1462type-checking functions. A type-checking function has the following
1463signature:
1464
1465\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001466def check_foo(option : Option, opt : string, value : string)
1467 -> foo
Neal Norwitz488609e2003-01-06 16:51:37 +00001468\end{verbatim}
1469
1470You can name it whatever you like, and make it return any type you
1471like. The value returned by a type-checking function will wind up in
1472the \class{OptionValues} instance returned by
1473\method{OptionParser.parse_args()}, or be passed to callbacks as the
1474\var{value} parameter.
1475
1476Your type-checking function should raise \exception{OptionValueError}
1477if it encounters any problems. \exception{OptionValueError} takes a
1478single string argument, which is passed as-is to
1479\class{OptionParser}'s \method{error()} method, which in turn prepends
1480the program name and the string ``error:'' and prints everything to
1481stderr before terminating the process.
1482
1483Here's a silly example that demonstrates adding a ``complex'' option
1484type to parse Python-style complex numbers on the command line. (This
1485is even sillier than it used to be, because \module{optparse} 1.3 adds
1486built-in support for complex numbers [purely for completeness], but
1487never mind.)
1488
1489First, the necessary imports:
1490
1491\begin{verbatim}
1492from copy import copy
1493from optparse import Option, OptionValueError
1494\end{verbatim}
1495
1496You need to define your type-checker first, since it's referred to
1497later (in the \member{TYPE_CHECKER} class attribute of your
1498\class{Option} subclass):
1499
1500\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001501def check_complex(option, opt, value):
Neal Norwitz488609e2003-01-06 16:51:37 +00001502 try:
1503 return complex(value)
1504 except ValueError:
1505 raise OptionValueError(
1506 "option %s: invalid complex value: %r" % (opt, value))
1507\end{verbatim}
1508
1509Finally, the \class{Option} subclass:
1510
1511\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001512class MyOption(Option):
Neal Norwitz488609e2003-01-06 16:51:37 +00001513 TYPES = Option.TYPES + ("complex",)
1514 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1515 TYPE_CHECKER["complex"] = check_complex
1516\end{verbatim}
1517
1518(If we didn't make a \function{copy()} of
1519\member{Option.TYPE_CHECKER}, we would end up modifying the
1520\member{TYPE_CHECKER} attribute of \module{optparse}'s Option class.
1521This being Python, nothing stops you from doing that except good
1522manners and common sense.)
1523
1524That's it! Now you can write a script that uses the new option type
1525just like any other \module{optparse}-based script, except you have to
1526instruct your \class{OptionParser} to use \class{MyOption} instead of
1527\class{Option}:
1528
1529\begin{verbatim}
1530parser = OptionParser(option_class=MyOption)
1531parser.add_option("-c", action="store", type="complex", dest="c")
1532\end{verbatim}
1533
1534Alternately, you can build your own option list and pass it to
1535\class{OptionParser}; if you don't use \method{add_option()} in the
1536above way, you don't need to tell \class{OptionParser} which option
1537class to use:
1538
1539\begin{verbatim}
1540option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1541parser = OptionParser(option_list=option_list)
1542\end{verbatim}
1543
1544\subsubsection{Adding new actions\label{optparse-adding-actions}}
1545
1546Adding new actions is a bit trickier, because you have to understand
1547that \module{optparse} has a couple of classifications for actions:
1548
1549\begin{definitions}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001550\term{``store'' actions}
Neal Norwitz488609e2003-01-06 16:51:37 +00001551 actions that result in \module{optparse} storing a value to an attribute
Greg Wardbf8f1b52003-05-03 19:41:45 +00001552 of the OptionValues instance; these options require a \var{dest}
Neal Norwitz488609e2003-01-06 16:51:37 +00001553 attribute to be supplied to the Option constructor
Greg Wardbf8f1b52003-05-03 19:41:45 +00001554\term{``typed'' actions}
Neal Norwitz488609e2003-01-06 16:51:37 +00001555 actions that take a value from the command line and expect it to be
1556 of a certain type; or rather, a string that can be converted to a
Greg Wardbf8f1b52003-05-03 19:41:45 +00001557 certain type. These options require a \var{type} attribute to the
Neal Norwitz488609e2003-01-06 16:51:37 +00001558 Option constructor.
1559\end{definitions}
1560
Greg Wardbf8f1b52003-05-03 19:41:45 +00001561Some default ``store'' actions are \var{store}, \var{store_const},
1562\var{append}, and \var{count}. The default ``typed'' actions are
1563\var{store}, \var{append}, and \var{callback}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001564
1565When you add an action, you need to decide if it's a ``store'' action,
1566a ``typed'', neither, or both. Three class attributes of
1567\class{Option} (or your \class{Option} subclass) control this:
1568
1569\begin{memberdesc}{ACTIONS}
1570 All actions must be listed as strings in ACTIONS.
1571\end{memberdesc}
1572\begin{memberdesc}{STORE_ACTIONS}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001573 ``store'' actions are additionally listed here.
Neal Norwitz488609e2003-01-06 16:51:37 +00001574\end{memberdesc}
1575\begin{memberdesc}{TYPED_ACTIONS}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001576 ``typed'' actions are additionally listed here.
Neal Norwitz488609e2003-01-06 16:51:37 +00001577\end{memberdesc}
1578
1579In order to actually implement your new action, you must override
1580\class{Option}'s \method{take_action()} method and add a case that
1581recognizes your action.
1582
1583For example, let's add an ``extend'' action. This is similar to the
1584standard ``append'' action, but instead of taking a single value from
1585the command-line and appending it to an existing list, ``extend'' will
1586take multiple values in a single comma-delimited string, and extend an
1587existing list with them. That is, if \longprogramopt{names} is an
1588``extend'' option of type string, the command line:
1589
1590\begin{verbatim}
1591--names=foo,bar --names blah --names ding,dong
1592\end{verbatim}
1593
1594would result in a list:
1595
1596\begin{verbatim}
1597["foo", "bar", "blah", "ding", "dong"]
1598\end{verbatim}
1599
1600Again we define a subclass of \class{Option}:
1601
1602\begin{verbatim}
Fred Drakebd12b182004-01-27 21:08:04 +00001603class MyOption(Option):
Neal Norwitz488609e2003-01-06 16:51:37 +00001604
1605 ACTIONS = Option.ACTIONS + ("extend",)
1606 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1607 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1608
Fred Drakebd12b182004-01-27 21:08:04 +00001609 def take_action(self, action, dest, opt, value, values, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001610 if action == "extend":
1611 lvalue = value.split(",")
1612 values.ensure_value(dest, []).extend(lvalue)
1613 else:
1614 Option.take_action(
1615 self, action, dest, opt, value, values, parser)
1616\end{verbatim}
1617
1618Features of note:
1619
1620\begin{itemize}
1621\item ``extend'' both expects a value on the command-line and stores that
1622value somewhere, so it goes in both \member{STORE_ACTIONS} and
1623\member{TYPED_ACTIONS}.
1624
1625\item \method{MyOption.take_action()} implements just this one new
1626action, and passes control back to \method{Option.take_action()} for
1627the standard \module{optparse} actions.
1628
1629\item \var{values} is an instance of the \class{Values} class, which
1630provides the very useful \method{ensure_value()}
1631method. \method{ensure_value()} is essentially \function{getattr()}
1632with a safety valve; it is called as:
1633
1634\begin{verbatim}
1635values.ensure_value(attr, value)
1636\end{verbatim}
1637\end{itemize}
1638
1639If the \member{attr} attribute of \var{values} doesn't exist or is
Greg Wardd7231282003-05-03 21:22:58 +00001640\code{None}, then \method{ensure_value()} first sets it to \var{value}, and
Neal Norwitz488609e2003-01-06 16:51:37 +00001641then returns \var{value}. This is very handy for actions like
1642``extend'', ``append'', and ``count'', all of which accumulate data in
1643a variable and expect that variable to be of a certain type (a list
1644for the first two, an integer for the latter). Using
1645\method{ensure_value()} means that scripts using your action don't
1646have to worry about setting a default value for the option
Greg Wardd7231282003-05-03 21:22:58 +00001647destinations in question; they can just leave the default as \code{None} and
Neal Norwitz488609e2003-01-06 16:51:37 +00001648\method{ensure_value()} will take care of getting it right when it's
1649needed.
1650
1651\subsubsection{Other reasons to extend \module{optparse}\label{optparse-extending-other-reasons}}
1652
1653Adding new types and new actions are the big, obvious reasons why you
1654might want to extend \module{optparse}. I can think of at least two
1655other areas to play with.
1656
1657First, the simple one: \class{OptionParser} tries to be helpful by
Greg Wardd7231282003-05-03 21:22:58 +00001658calling \function{sys.exit()} when appropriate, i.e. when there's an
Neal Norwitz488609e2003-01-06 16:51:37 +00001659error on the command-line or when the user requests help. In the
1660former case, the traditional course of letting the script crash with a
1661traceback is unacceptable; it will make users think there's a bug in
1662your script when they make a command-line error. In the latter case,
1663there's generally not much point in carrying on after printing a help
1664message.
1665
1666If this behaviour bothers you, it shouldn't be too hard to ``fix'' it.
1667You'll have to
1668
1669\begin{enumerate}
1670\item subclass OptionParser and override the error() method
Greg Wardbf8f1b52003-05-03 19:41:45 +00001671\item subclass Option and override the take_action() method---you'll
1672 need to provide your own handling of the ``help'' action that
Neal Norwitz488609e2003-01-06 16:51:37 +00001673 doesn't call sys.exit()
1674\end{enumerate}
1675
1676The second, much more complex, possibility is to override the
1677command-line syntax implemented by \module{optparse}. In this case,
1678you'd leave the whole machinery of option actions and types alone, but
Fred Drake853276e2003-07-16 17:58:38 +00001679rewrite the code that processes \code{sys.argv}. You'll need to
Neal Norwitz488609e2003-01-06 16:51:37 +00001680subclass \class{OptionParser} in any case; depending on how radical a
1681rewrite you want, you'll probably need to override one or all of
1682\method{parse_args()}, \method{_process_long_opt()}, and
1683\method{_process_short_opts()}.
1684
1685Both of these are left as an exercise for the reader. I have not
1686tried to implement either myself, since I'm quite happy with
1687\module{optparse}'s default behaviour (naturally).
1688
1689Happy hacking, and don't forget: Use the Source, Luke.
1690
1691\subsubsection{Examples\label{optparse-extending-examples}}
1692
1693Here are a few examples of extending the \module{optparse} module.
1694
1695First, let's change the option-parsing to be case-insensitive:
1696
1697\verbatiminput{caseless.py}
1698
1699And two ways of implementing ``required options'' with
1700\module{optparse}.
1701
1702Version 1: Add a method to \class{OptionParser} which applications
1703must call after parsing arguments:
1704
1705\verbatiminput{required_1.py}
1706
1707Version 2: Extend \class{Option} and add a \member{required}
1708attribute; extend \class{OptionParser} to ensure that required options
1709are present after parsing:
1710
Fred Drakecf6d74a2003-04-18 15:50:13 +00001711\verbatiminput{required_2.py}
Skip Montanarodb8d1c22004-01-26 19:30:21 +00001712
1713\begin{seealso}
Fred Drake913829c2004-01-26 19:39:13 +00001714 \seemodule{getopt}{More traditional \UNIX-style command line option parsing.}
Skip Montanarodb8d1c22004-01-26 19:30:21 +00001715\end{seealso}