blob: f088f88d2018f18bfa905bbd1357bcb9ec0140e6 [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
68\subsection{The Tao of Option Parsing\label{optparse-tao}}
69
70\module{optparse} is an implementation of what I have always
71considered the most obvious, straightforward, and user-friendly way to
72design a user interface for command-line programs. In short, I have
73fairly firm ideas of the Right Way (and the many Wrong Ways) to do
74argument parsing, and \module{optparse} reflects many of those ideas.
75This section is meant to explain this philosophy, which in turn is
Fred Drakecf6d74a2003-04-18 15:50:13 +000076heavily influenced by the \UNIX{} and GNU toolkits.
Neal Norwitz488609e2003-01-06 16:51:37 +000077
78\subsubsection{Terminology\label{optparse-terminology}}
79
80First, we need to establish some terminology.
81
82\begin{definitions}
83\term{argument}
84a chunk of text that a user enters on the command-line, and that the
85shell passes to \cfunction{execl()} or \cfunction{execv()}. In
86Python, arguments are elements of
87\var{sys.argv[1:]}. (\var{sys.argv[0]} is the name of the program
88being executed; in the context of parsing arguments, it's not very
Fred Drakecf6d74a2003-04-18 15:50:13 +000089important.) \UNIX{} shells also use the term ``word''.
Neal Norwitz488609e2003-01-06 16:51:37 +000090
91It's occasionally desirable to substitute an argument list other
92than \var{sys.argv[1:]}, so you should read ``argument'' as ``an element of
93\var{sys.argv[1:]}, or of some other list provided as a substitute for
94\var{sys.argv[1:]}''.
95
96\term{option}
97 an argument used to supply extra information to guide or customize
98 the execution of a program. There are many different syntaxes for
Fred Drakecf6d74a2003-04-18 15:50:13 +000099 options; the traditional \UNIX{} syntax is \programopt{-} followed by a
Neal Norwitz488609e2003-01-06 16:51:37 +0000100 single letter, e.g. \programopt{-x} or \programopt{-F}. Also,
Fred Drakecf6d74a2003-04-18 15:50:13 +0000101 traditional \UNIX{} syntax allows multiple options to be merged into a
Neal Norwitz488609e2003-01-06 16:51:37 +0000102 single argument, e.g. \programopt{-x -F} is equivalent to
103 \programopt{-xF}. The GNU project introduced \longprogramopt{}
104 followed by a series of hyphen-separated words,
105 e.g. \longprogramopt{file} or \longprogramopt{dry-run}. These are
106 the only two option syntaxes provided by \module{optparse}.
107
108 Some other option syntaxes that the world has seen include:
109
110\begin{itemize}
111\item a hyphen followed by a few letters, e.g. \programopt{-pf} (this is
Greg Wardb4e33192003-05-03 19:16:36 +0000112 \emph{not} the same as multiple options merged into a single
Neal Norwitz488609e2003-01-06 16:51:37 +0000113 argument.)
114\item a hyphen followed by a whole word, e.g. \programopt{-file} (this is
115 technically equivalent to the previous syntax, but they aren't
116 usually seen in the same program.)
117\item a plus sign followed by a single letter, or a few letters,
118 or a word, e.g. \programopt{+f}, \programopt{+rgb}.
119\item a slash followed by a letter, or a few letters, or a word, e.g.
120 \programopt{/f}, \programopt{/file}.
121\end{itemize}
122
123These option syntaxes are not supported by \module{optparse}, and they
124never will be. (If you really want to use one of those option
125syntaxes, you'll have to subclass OptionParser and override all the
126difficult bits. But please don't! \module{optparse} does things the
Fred Drakecf6d74a2003-04-18 15:50:13 +0000127traditional \UNIX/GNU way deliberately; the first three are
Neal Norwitz488609e2003-01-06 16:51:37 +0000128non-standard anywhere, and the last one makes sense only if you're
129exclusively targeting MS-DOS/Windows and/or VMS.)
130
131\term{option argument}
132an argument that follows an option, is closely associated with that
133option, and is consumed from the argument list when the option is.
134Often, option arguments may also be included in the same argument as
135the option, e.g. :
136
137\begin{verbatim}
138 ["-f", "foo"]
139\end{verbatim}
140
141may be equivalent to:
142
143\begin{verbatim}
144 ["-ffoo"]
145\end{verbatim}
146
147(\module{optparse} supports this syntax.)
148
149Some options never take an argument. Some options always take an
150argument. Lots of people want an ``optional option arguments'' feature,
151meaning that some options will take an argument if they see it, and
152won't if they don't. This is somewhat controversial, because it makes
153parsing ambiguous: if \programopt{-a} takes an optional argument and
154\programopt{-b} is another option entirely, how do we interpret
155\programopt{-ab}? \module{optparse} does not currently support this.
156
157\term{positional argument}
158something leftover in the argument list after options have been
159parsed, ie. after options and their arguments have been parsed and
160removed from the argument list.
161
162\term{required option}
163an option that must be supplied on the command-line; the phrase
Fred Drakecf6d74a2003-04-18 15:50:13 +0000164``required option'' is an oxymoron and is usually considered poor UI
Neal Norwitz488609e2003-01-06 16:51:37 +0000165design. \module{optparse} doesn't prevent you from implementing
Fred Drakecf6d74a2003-04-18 15:50:13 +0000166required options, but doesn't give you much help with it either. See
167``Extending Examples'' (section~\ref{optparse-extending-examples}) for
168two ways to implement 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,
180``/tmp/report.txt'' is an option argument. ``foo'' and ``bar'' are
181positional arguments.
182
183\subsubsection{What are options for?\label{optparse-options}}
184
185Options are used to provide extra information to tune or customize the
186execution of a program. In case it wasn't clear, options are usually
187\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
280strings. In this document, we'll only cover four of the things you
281can put there: \var{action}, \var{type}, \var{dest} (destination), and
282\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
310When \module{optparse} sees the \programopt{-f}, it sucks in 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
328Note that I didn't supply a long option, which is perfectly acceptable.
Greg Wardbf8f1b52003-05-03 19:41:45 +0000329I also didn't specify the action---it defaults to ``store''.
Neal Norwitz488609e2003-01-06 16:51:37 +0000330
331Let's parse another fake command-line. This time, we'll jam the
Greg Wardbf8f1b52003-05-03 19:41:45 +0000332option argument right up against the option---\programopt{-n42} (one
Neal Norwitz488609e2003-01-06 16:51:37 +0000333argument) is equivalent to \programopt{-n 42} (two arguments). :
334
335\begin{verbatim}
336(options, args) = parser.parse_args(["-n42"])
337print options.num
338\end{verbatim}
339
340will print ``42''.
341
342Trying out the ``float'' type is left as an exercise for the reader.
343
344If you don't specify a type, \module{optparse} assumes ``string''.
345Combined with the fact that the default action is ``store'', that
346means our first example can be a lot shorter:
347
348\begin{verbatim}
349parser.add_option("-f", "--file", dest="filename")
350\end{verbatim}
351
352If you don't supply a destination, \module{optparse} figures out a
353sensible default from the option strings: if the first long option
354string is \longprogramopt{foo-bar}, then the default destination is
355\var{foo_bar}. If there are no long option strings,
356\module{optparse} looks at the first short option: the default
357destination for \programopt{-f} is \var{f}.
358
Fred Drakecf6d74a2003-04-18 15:50:13 +0000359Adding types is fairly easy; please refer to
360section~\ref{optparse-adding-types}, ``Adding new types.''
Neal Norwitz488609e2003-01-06 16:51:37 +0000361
Greg Wardbf8f1b52003-05-03 19:41:45 +0000362\subsubsection{Other \var{store_*} actions\label{optparse-other-store-actions}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000363
Greg Wardbf8f1b52003-05-03 19:41:45 +0000364Flag options---set a variable to true or false when a particular
365option is seen---are quite common. \module{optparse} supports them
Neal Norwitz488609e2003-01-06 16:51:37 +0000366with two separate actions, ``store_true'' and ``store_false''. For
367example, you might have a \var{verbose} flag that is turned on with
368\programopt{-v} and off with \programopt{-q}:
369
370\begin{verbatim}
371parser.add_option("-v", action="store_true", dest="verbose")
372parser.add_option("-q", action="store_false", dest="verbose")
373\end{verbatim}
374
375Here we have two different options with the same destination, which is
376perfectly OK. (It just means you have to be a bit careful when setting
Greg Wardbf8f1b52003-05-03 19:41:45 +0000377default values---see below.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000378
379When \module{optparse} sees \programopt{-v} on the command line, it
380sets the \var{verbose} attribute of the special {option values}
381object to 1; when it sees \programopt{-q}, it sets \var{verbose} to
3820.
383
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
389defaults, they are all set to None. Sometimes, this is just fine
390(which is why it's the default), but sometimes, you want more control.
391To address that need, \module{optparse} lets you supply a default
392value for each destination, which is assigned before the command-line
393is parsed.
394
395First, consider the verbose/quiet example. If we want
Greg Ward1f535172003-05-03 20:13:08 +0000396\module{optparse} to set \var{verbose} to \code{True} unless
397\programopt{-q} is seen, then we can do this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000398
399\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000400parser.add_option("-v", action="store_true", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000401parser.add_option("-q", action="store_false", dest="verbose")
402\end{verbatim}
403
404Oddly enough, this is exactly equivalent:
405
406\begin{verbatim}
407parser.add_option("-v", action="store_true", dest="verbose")
Greg Ward1f535172003-05-03 20:13:08 +0000408parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000409\end{verbatim}
410
411Those are equivalent because you're supplying a default value for the
412option's \emph{destination}, and these two options happen to have the same
413destination (the \var{verbose} variable).
414
415Consider this:
416
417\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000418parser.add_option("-v", action="store_true", dest="verbose", default=False)
419parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000420\end{verbatim}
421
Greg Ward1f535172003-05-03 20:13:08 +0000422Again, the default value for \var{verbose} will be \code{True}: the last
Neal Norwitz488609e2003-01-06 16:51:37 +0000423default value supplied for any particular destination attribute is the
424one that counts.
425
426\subsubsection{Generating help\label{optparse-generating-help}}
427
428The last feature that you will use in every script is
429\module{optparse}'s ability to generate help messages. All you have
430to do is supply a \var{help} value when you add an option. Let's
431create a new parser and populate it with user-friendly (documented)
432options:
433
434\begin{verbatim}
435usage = "usage: %prog [options] arg1 arg2"
436parser = OptionParser(usage=usage)
437parser.add_option("-v", "--verbose",
Greg Ward1f535172003-05-03 20:13:08 +0000438 action="store_true", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +0000439 help="make lots of noise [default]")
440parser.add_option("-q", "--quiet",
441 action="store_false", dest="verbose",
442 help="be vewwy quiet (I'm hunting wabbits)")
443parser.add_option("-f", "--file", dest="filename",
444 metavar="FILE", help="write output to FILE"),
445parser.add_option("-m", "--mode",
446 default="intermediate",
447 help="interaction mode: one of 'novice', "
448 "'intermediate' [default], 'expert'")
449\end{verbatim}
450
451If \module{optparse} encounters either \programopt{-h} or
Greg Wardb4e33192003-05-03 19:16:36 +0000452\longprogramopt{help} on the command-line, or if you just call
Neal Norwitz488609e2003-01-06 16:51:37 +0000453\method{parser.print_help()}, it prints the following to stdout:
454
455\begin{verbatim}
456usage: <yourscript> [options] arg1 arg2
457
458options:
459 -h, --help show this help message and exit
460 -v, --verbose make lots of noise [default]
461 -q, --quiet be vewwy quiet (I'm hunting wabbits)
462 -fFILE, --file=FILE write output to FILE
463 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
464 [default], 'expert'
465\end{verbatim}
466
467There's a lot going on here to help \module{optparse} generate the
468best possible help message:
469
470\begin{itemize}
471\item the script defines its own usage message:
472
473\begin{verbatim}
474usage = "usage: %prog [options] arg1 arg2"
475\end{verbatim}
476
Greg Wardbf8f1b52003-05-03 19:41:45 +0000477\module{optparse} expands \samp{\%prog} in the usage string to the name of the
Neal Norwitz488609e2003-01-06 16:51:37 +0000478current script, ie. \code{os.path.basename(sys.argv[0])}. The
479expanded string is then printed before the detailed option help.
480
481If you don't supply a usage string, \module{optparse} uses a bland but
Greg Wardbf8f1b52003-05-03 19:41:45 +0000482sensible default: \code{"usage: \%prog [options]"}, which is fine if your
Neal Norwitz488609e2003-01-06 16:51:37 +0000483script doesn't take any positional arguments.
484
485\item every option defines a help string, and doesn't worry about
Greg Wardbf8f1b52003-05-03 19:41:45 +0000486line-wrapping---\module{optparse} takes care of wrapping lines and
Neal Norwitz488609e2003-01-06 16:51:37 +0000487making the help output look good.
488
489\item options that take a value indicate this fact in their
490automatically-generated help message, e.g. for the ``mode'' option:
491
492\begin{verbatim}
493-mMODE, --mode=MODE
494\end{verbatim}
495
496Here, ``MODE'' is called the meta-variable: it stands for the argument
497that the user is expected to supply to
498\programopt{-m}/\longprogramopt{mode}. By default, \module{optparse}
499converts the destination variable name to uppercase and uses that for
Greg Wardbf8f1b52003-05-03 19:41:45 +0000500the meta-variable. Sometimes, that's not what you want---for
Neal Norwitz488609e2003-01-06 16:51:37 +0000501example, the \var{filename} option explicitly sets
502\code{metavar="FILE"}, resulting in this automatically-generated
503option description:
504
505\begin{verbatim}
506-fFILE, --file=FILE
507\end{verbatim}
508
509This is important for more than just saving space, though: the
510manually written help text uses the meta-variable ``FILE'', to clue
511the user in that there's a connection between the formal syntax
512``-fFILE'' and the informal semantic description ``write output to
513FILE''. This is a simple but effective way to make your help text a
514lot clearer and more useful for end users.
515\end{itemize}
516
Fred Drakecf6d74a2003-04-18 15:50:13 +0000517When dealing with many options, it is convenient to group these
518options for better help output. An \class{OptionParser} can contain
519several option groups, each of which can contain several options.
520
521Continuing with the parser defined above, adding an
522\class{OptionGroup} to a parser is easy:
523
524\begin{verbatim}
525group = OptionGroup(parser, "Dangerous Options",
526 "Caution: use these options at your own risk."
527 " It is believed that some of them bite.")
528group.add_option("-g", action="store_true", help="Group option.")
529parser.add_option_group(group)
530\end{verbatim}
531
532This would result in the following help output:
533
534\begin{verbatim}
535usage: [options] arg1 arg2
536
537options:
538 -h, --help show this help message and exit
539 -v, --verbose make lots of noise [default]
540 -q, --quiet be vewwy quiet (I'm hunting wabbits)
541 -fFILE, --file=FILE write output to FILE
542 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
543 [default], 'expert'
544
545 Dangerous Options:
546 Caution: use of these options is at your own risk. It is believed that
547 some of them bite.
548 -g Group option.
549\end{verbatim}
550
551
Neal Norwitz488609e2003-01-06 16:51:37 +0000552\subsubsection{Print a version number\label{optparse-print-version}}
553
554Similar to the brief usage string, \module{optparse} can also print a
555version string for your program. You have to supply the string, as
556the \var{version} argument to \class{OptionParser}:
557
558\begin{verbatim}
559parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
560\end{verbatim}
561
562Note that ``\%prog'' is expanded just like it is in \var{usage}. Apart from
563that, \var{version} can contain anything you like. When you supply it,
Greg Wardb4e33192003-05-03 19:16:36 +0000564\module{optparse} automatically adds a \longprogramopt{version} option to your
Neal Norwitz488609e2003-01-06 16:51:37 +0000565parser. If it encounters this option on the command line, it expands
566your \var{version} string (by replacing ``\%prog''), prints it to
567stdout, and exits.
568
569For example, if your script is called /usr/bin/foo, a user might do:
570
571\begin{verbatim}
572$ /usr/bin/foo --version
573foo 1.0
574$
575\end{verbatim}
576
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 Wardbf8f1b52003-05-03 19:41:45 +0000581command-line---e.g. \programopt{-n4x} where \programopt{-n} is an
Neal Norwitz488609e2003-01-06 16:51:37 +0000582integer-valued option. \module{optparse} prints your usage message to
583stderr, followed by a useful and human-readable error message. Then
584it terminates (calls \function{sys.exit()}) with a non-zero exit
585status.
586
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
593Here's what my \module{optparse}-based scripts usually look like:
594
595\begin{verbatim}
596from optparse import OptionParser
597
Fred Drakecf6d74a2003-04-18 15:50:13 +0000598...
Neal Norwitz488609e2003-01-06 16:51:37 +0000599
600def main ():
601 usage = "usage: %prog [options] arg"
602 parser = OptionParser(usage)
603 parser.add_option("-f", "--file", type="string", dest="filename",
604 help="read data from FILENAME")
605 parser.add_option("-v", "--verbose",
606 action="store_true", dest="verbose")
607 parser.add_option("-q", "--quiet",
608 action="store_false", dest="verbose")
Fred Drakecf6d74a2003-04-18 15:50:13 +0000609 # more options ...
Neal Norwitz488609e2003-01-06 16:51:37 +0000610
611 (options, args) = parser.parse_args()
612 if len(args) != 1:
613 parser.error("incorrect number of arguments")
614
615 if options.verbose:
616 print "reading %s..." % options.filename
617
Fred Drakecf6d74a2003-04-18 15:50:13 +0000618 # go to work ...
Neal Norwitz488609e2003-01-06 16:51:37 +0000619
620if __name__ == "__main__":
621 main()
622\end{verbatim}
623
624\subsection{Advanced Usage\label{optparse-advanced-usage}}
625
626This is reference documentation. If you haven't read the basic
Fred Drakecf6d74a2003-04-18 15:50:13 +0000627documentation in section~\ref{optparse-basic-usage}, do so now.
Neal Norwitz488609e2003-01-06 16:51:37 +0000628
Fred Drakecf6d74a2003-04-18 15:50:13 +0000629\subsubsection{Creating and populating the
630 parser\label{optparse-creating-the-parser}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000631
632There are several ways to populate the parser with options. One way
633is to pass a list of \class{Options} to the \class{OptionParser}
634constructor:
635
636\begin{verbatim}
637parser = OptionParser(option_list=[
638 make_option("-f", "--filename",
639 action="store", type="string", dest="filename"),
640 make_option("-q", "--quiet",
641 action="store_false", dest="verbose")])
642\end{verbatim}
643
Fred Drakecf6d74a2003-04-18 15:50:13 +0000644(\function{make_option()} is an alias for
Neal Norwitz488609e2003-01-06 16:51:37 +0000645the \class{Option} class, ie. this just calls the \class{Option}
646constructor. A future version of \module{optparse} will probably
647split \class{Option} into several classes, and
648\function{make_option()} will become a factory function that picks the
649right class to instantiate.)
650
651For long option lists, it's often more convenient/readable to create the
652list separately:
653
654\begin{verbatim}
655option_list = [make_option("-f", "--filename",
656 action="store", type="string", dest="filename"),
Fred Drakecf6d74a2003-04-18 15:50:13 +0000657 # 17 other options ...
Neal Norwitz488609e2003-01-06 16:51:37 +0000658 make_option("-q", "--quiet",
659 action="store_false", dest="verbose")]
660parser = OptionParser(option_list=option_list)
661\end{verbatim}
662
663Or, you can use the \method{add_option()} method of
664\class{OptionParser} to add options one-at-a-time:
665
666\begin{verbatim}
667parser = OptionParser()
668parser.add_option("-f", "--filename",
669 action="store", type="string", dest="filename")
670parser.add_option("-q", "--quiet",
671 action="store_false", dest="verbose")
672\end{verbatim}
673
674This method makes it easier to track down exceptions raised by the
675\class{Option} constructor, which are common because of the complicated
Greg Wardbf8f1b52003-05-03 19:41:45 +0000676interdependencies among the various keyword arguments---if you get it
Neal Norwitz488609e2003-01-06 16:51:37 +0000677wrong, \module{optparse} raises \exception{OptionError}.
678
679\method{add_option()} can be called in one of two ways:
680
681\begin{itemize}
682\item pass it an \class{Option} instance (as returned by \function{make_option()})
683\item pass it any combination of positional and keyword arguments that
684are acceptable to \function{make_option()} (ie., to the \class{Option}
685constructor), and it will create the \class{Option} instance for you
686(shown above).
687\end{itemize}
688
689\subsubsection{Defining options\label{optparse-defining-options}}
690
691Each \class{Option} instance represents a set of synonymous
692command-line options, ie. options that have the same meaning and
693effect, but different spellings. You can specify any number of short
694or long option strings, but you must specify at least one option
695string.
696
697To define an option with only a short option string:
698
699\begin{verbatim}
700make_option("-f", ...)
701\end{verbatim}
702
703And to define an option with only a long option string:
704
705\begin{verbatim}
706make_option("--foo", ...)
707\end{verbatim}
708
709The ``...'' represents a set of keyword arguments that define
710attributes of the \class{Option} object. Just which keyword args you
711must supply for a given \class{Option} is fairly complicated (see the
712various \method{_check_*()} methods in the \class{Option} class if you
713don't believe me), but you always have to supply \emph{some}. If you
714get it wrong, \module{optparse} raises an \exception{OptionError}
715exception explaining your mistake.
716
717The most important attribute of an option is its action, ie. what to do
718when we encounter this option on the command-line. The possible actions
719are:
720
721\begin{definitions}
722\term{store} [default]
723store this option's argument.
724\term{store_const}
725store a constant value.
726\term{store_true}
727store a true value.
728\term{store_false}
729store a false value.
730\term{append}
731append this option's argument to a list.
732\term{count}
733increment a counter by one.
734\term{callback}
735call a specified function.
736\term{help}
737print a usage message including all options and the documentation for
738them.
739\end{definitions}
740
741(If you don't supply an action, the default is ``store''. For this
742action, you may also supply \var{type} and \var{dest} keywords; see
743below.)
744
745As you can see, most actions involve storing or updating a value
746somewhere. \module{optparse} always creates a particular object (an
747instance of the \class{Values} class) specifically for this
748purpose. Option arguments (and various other values) are stored as
749attributes of this object, according to the \var{dest} (destination)
750argument to \function{make_option()}/\method{add_option()}.
751
752For example, when you call:
753
754\begin{verbatim}
755parser.parse_args()
756\end{verbatim}
757
758one of the first things \module{optparse} does is create a
759\var{values} object:
760
761\begin{verbatim}
762values = Values()
763\end{verbatim}
764
765If one of the options in this parser is defined with:
766
767\begin{verbatim}
768make_option("-f", "--file", action="store", type="string", dest="filename")
769\end{verbatim}
770
771and the command-line being parsed includes any of the following:
772
773\begin{verbatim}
774-ffoo
775-f foo
776--file=foo
777--file foo
778\end{verbatim}
779
780then \module{optparse}, on seeing the \programopt{-f} or
781\longprogramopt{file} option, will do the equivalent of this:
782
783\begin{verbatim}
784 values.filename = "foo"
785\end{verbatim}
786
787Clearly, the \var{type} and \var{dest} arguments are (usually) almost
788as important as \var{action}. \var{action} is the only attribute that
Greg Wardb4e33192003-05-03 19:16:36 +0000789is meaningful for \emph{all} options, though, so it is the most
790important.
Neal Norwitz488609e2003-01-06 16:51:37 +0000791
792\subsubsection{Option actions\label{optparse-option-actions}}
793
794The various option actions all have slightly different requirements
795and effects. Except for the ``help'' action, you must supply at least
796one other keyword argument when creating the \class{Option}; the exact
797requirements for each action are listed here.
798
799\begin{definitions}
800\term{store} [relevant: \var{type}, \var{dest}, \var{nargs}, \var{choices}]
801
802The option must be followed by an argument, which is converted to a
803value according to \var{type} and stored in \var{dest}. If
804\var{nargs} > 1, multiple arguments will be consumed from the command
805line; all will be converted according to \var{type} and stored to
Fred Drakecf6d74a2003-04-18 15:50:13 +0000806\var{dest} as a tuple. See section~\ref{optparse-option-types},
807``Option types'' below.
Neal Norwitz488609e2003-01-06 16:51:37 +0000808
809If \var{choices} is supplied (a list or tuple of strings), the type
810defaults to ``choice''.
811
812If \var{type} is not supplied, it defaults to ``string''.
813
814If \var{dest} is not supplied, \module{optparse} derives a
815destination from the first long option strings (e.g.,
Greg Wardb4e33192003-05-03 19:16:36 +0000816\longprogramopt{foo-bar} becomes \var{foo_bar}). If there are no long
Neal Norwitz488609e2003-01-06 16:51:37 +0000817option strings, \module{optparse} derives a destination from the first
Greg Wardb4e33192003-05-03 19:16:36 +0000818short option string (e.g., \programopt{-f} becomes \var{f}).
Neal Norwitz488609e2003-01-06 16:51:37 +0000819
820Example:
821
822\begin{verbatim}
823make_option("-f")
824make_option("-p", type="float", nargs=3, dest="point")
825\end{verbatim}
826
827Given the following command line:
828
829\begin{verbatim}
830-f foo.txt -p 1 -3.5 4 -fbar.txt
831\end{verbatim}
832
833\module{optparse} will set:
834
835\begin{verbatim}
836values.f = "bar.txt"
837values.point = (1.0, -3.5, 4.0)
838\end{verbatim}
839
840(Actually, \member{values.f} will be set twice, but only the second
841time is visible in the end.)
842
843\term{store_const} [required: \var{const}, \var{dest}]
844
845The \var{const} value supplied to the \class{Option} constructor is
846stored in \var{dest}.
847
848Example:
849
850\begin{verbatim}
851make_option("-q", "--quiet",
852 action="store_const", const=0, dest="verbose"),
853make_option("-v", "--verbose",
854 action="store_const", const=1, dest="verbose"),
855make_option(None, "--noisy",
856 action="store_const", const=2, dest="verbose"),
857\end{verbatim}
858
859If \longprogramopt{noisy} is seen, \module{optparse} will set:
860
861\begin{verbatim}
862values.verbose = 2
863\end{verbatim}
864
865\term{store_true} [required: \var{dest}]
866
Greg Ward1f535172003-05-03 20:13:08 +0000867A special case of ``store_const'' that stores \code{True} to \var{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000868
869\term{store_false} [required: \var{dest}]
870
Greg Ward1f535172003-05-03 20:13:08 +0000871Like ``store_true'', but stores a \code{False}
Neal Norwitz488609e2003-01-06 16:51:37 +0000872
873Example:
874
875\begin{verbatim}
876make_option(None, "--clobber", action="store_true", dest="clobber")
877make_option(None, "--no-clobber", action="store_false", dest="clobber")
878\end{verbatim}
879
880\term{append} [relevant: \var{type}, \var{dest}, \var{nargs}, \var{choices}]
881
882The option must be followed by an argument, which is appended to the
883list in \var{dest}. If no default value for \var{dest} is supplied
884(ie. the default is None), an empty list is automatically created when
885\module{optparse} first encounters this option on the command-line.
886If \samp{nargs > 1}, multiple arguments are consumed, and a tuple of
887length \var{nargs} is appended to \var{dest}.
888
889The defaults for \var{type} and \var{dest} are the same as for the
890``store'' action.
891
892Example:
893
894\begin{verbatim}
895make_option("-t", "--tracks", action="append", type="int")
896\end{verbatim}
897
898If \programopt{-t3} is seen on the command-line, \module{optparse} does the equivalent of:
899
900\begin{verbatim}
901values.tracks = []
902values.tracks.append(int("3"))
903\end{verbatim}
904
Greg Wardb4e33192003-05-03 19:16:36 +0000905If, a little later on, \longprogramopt{tracks=4} is seen, it does:
Neal Norwitz488609e2003-01-06 16:51:37 +0000906
907\begin{verbatim}
908values.tracks.append(int("4"))
909\end{verbatim}
910
Fred Drakecf6d74a2003-04-18 15:50:13 +0000911See ``Error handling'' (section~\ref{optparse-error-handling}) for
Neal Norwitz488609e2003-01-06 16:51:37 +0000912information on how \module{optparse} deals with something like
Greg Wardb4e33192003-05-03 19:16:36 +0000913\longprogramopt{tracks=x}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000914
915\term{count} [required: \var{dest}]
916
917Increment the integer stored at \var{dest}. \var{dest} is set to zero
918before being incremented the first time (unless you supply a default
919value).
920
921Example:
922
923\begin{verbatim}
924make_option("-v", action="count", dest="verbosity")
925\end{verbatim}
926
927The first time \programopt{-v} is seen on the command line,
928\module{optparse} does the equivalent of:
929
930\begin{verbatim}
931values.verbosity = 0
932values.verbosity += 1
933\end{verbatim}
934
935Every subsequent occurrence of \programopt{-v} results in:
936
937\begin{verbatim}
938values.verbosity += 1
939\end{verbatim}
940
941\term{callback} [required: \var{'callback'};
942 relevant: \var{type}, \var{nargs}, \var{callback_args},
943 \var{callback_kwargs}]
944
945Call the function specified by \var{callback}. The signature of
946this function should be:
947
948\begin{verbatim}
949func(option : Option,
950 opt : string,
951 value : any,
952 parser : OptionParser,
953 *args, **kwargs)
954\end{verbatim}
955
Fred Drakecf6d74a2003-04-18 15:50:13 +0000956Callback options are covered in detail in
957section~\ref{optparse-callback-options} ``Callback Options.''
Neal Norwitz488609e2003-01-06 16:51:37 +0000958
959\term{help} [required: none]
960
961Prints a complete help message for all the options in the current
962option parser. The help message is constructed from the \var{usage}
963string passed to \class{OptionParser}'s constructor and the \var{help}
964string passed to every option.
965
966If no \var{help} string is supplied for an option, it will still be
967listed in the help message. To omit an option entirely, use the
968special value \constant{optparse.SUPPRESS_HELP}.
969
970Example:
971
972\begin{verbatim}
973from optparse import Option, OptionParser, SUPPRESS_HELP
974
975usage = "usage: %prog [options]"
976parser = OptionParser(usage, option_list=[
977 make_option("-h", "--help", action="help"),
978 make_option("-v", action="store_true", dest="verbose",
979 help="Be moderately verbose")
980 make_option("--file", dest="filename",
981 help="Input file to read data from"),
982 make_option("--secret", help=SUPPRESS_HELP)
983\end{verbatim}
984
Greg Wardb4e33192003-05-03 19:16:36 +0000985If \module{optparse} sees either \programopt{-h} or
986\longprogramopt{help} on the command line, it will print something
987like the following help message to stdout:
Neal Norwitz488609e2003-01-06 16:51:37 +0000988
989\begin{verbatim}
990usage: <yourscript> [options]
991
992options:
993 -h, --help Show this help message and exit
994 -v Be moderately verbose
995 --file=FILENAME Input file to read data from
996\end{verbatim}
997
998After printing the help message, \module{optparse} terminates your process
999with \code{sys.exit(0)}.
1000
1001\term{version} [required: none]
1002
1003Prints the version number supplied to the \class{OptionParser} to
1004stdout and exits. The version number is actually formatted and
1005printed by the \method{print_version()} method of
1006\class{OptionParser}. Generally only relevant if the \var{version}
1007argument is supplied to the \class{OptionParser} constructor.
1008\end{definitions}
1009
1010\subsubsection{Option types\label{optparse-option-types}}
1011
1012\module{optparse} supports six option types out of the box: \dfn{string},
1013\dfn{int}, \dfn{long}, \dfn{choice}, \dfn{float} and \dfn{complex}.
1014(Of these, string, int, float, and choice are the most commonly used
1015-- long and complex are there mainly for completeness.) It's easy to
1016add new option types by subclassing the \class{Option} class; see
Fred Drakecf6d74a2003-04-18 15:50:13 +00001017section~\ref{optparse-extending}, ``Extending \module{optparse}.''
Neal Norwitz488609e2003-01-06 16:51:37 +00001018
1019Arguments to string options are not checked or converted in any way:
1020the text on the command line is stored in the destination (or passed
1021to the callback) as-is.
1022
1023Integer arguments are passed to \function{int()} to convert them to
1024Python integers. If \function{int()} fails, so will
1025\module{optparse}, although with a more useful error message.
1026Internally, \module{optparse} raises \exception{OptionValueError} in
1027\function{optparse.check_builtin()}; at a higher level (in
1028\class{OptionParser}) this is caught and \module{optparse} terminates
1029your program with a useful error message.
1030
1031Likewise, float arguments are passed to \function{float()} for
1032conversion, long arguments to \function{long()}, and complex arguments
1033to \function{complex()}. Apart from that, they are handled
1034identically to integer arguments.
1035
1036Choice options are a subtype of string options. A master list or
1037tuple of choices (strings) must be passed to the option constructor
1038(\function{make_option()} or \method{OptionParser.add_option()}) as
1039the ``choices'' keyword argument. Choice option arguments are
1040compared against this master list in
1041\function{optparse.check_choice()}, and \exception{OptionValueError}
1042is raised if an unknown string is given.
1043
1044\subsubsection{Querying and manipulating your option parser\label{optparse-querying-and-manipulating}}
1045
1046Sometimes, it's useful to poke around your option parser and see what's
1047there. \class{OptionParser} provides a couple of methods to help you out:
1048
1049\begin{methoddesc}{has_option}{opt_str}
1050 Given an option string such as \programopt{-q} or
1051 \longprogramopt{verbose}, returns true if the \class{OptionParser}
1052 has an option with that option string.
1053\end{methoddesc}
1054
1055\begin{methoddesc}{get_option}{opt_str}
1056 Returns the \class{Option} instance that implements the option
1057 string you supplied, or None if no options implement it.
1058\end{methoddesc}
1059
1060\begin{methoddesc}{remove_option}{opt_str}
1061 If the \class{OptionParser} has an option corresponding to
1062 \var{opt_str}, that option is removed. If that option provided
1063 any other option strings, all of those option strings become
1064 invalid.
1065
1066 If \var{opt_str} does not occur in any option belonging to this
1067 \class{OptionParser}, raises \exception{ValueError}.
1068\end{methoddesc}
1069
1070\subsubsection{Conflicts between options\label{optparse-conflicts}}
1071
1072If you're not careful, it's easy to define conflicting options:
1073
1074\begin{verbatim}
1075parser.add_option("-n", "--dry-run", ...)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001076...
Neal Norwitz488609e2003-01-06 16:51:37 +00001077parser.add_option("-n", "--noisy", ...)
1078\end{verbatim}
1079
1080(This is even easier to do if you've defined your own
1081\class{OptionParser} subclass with some standard options.)
1082
1083On the assumption that this is usually a mistake, \module{optparse}
Fred Drakecf6d74a2003-04-18 15:50:13 +00001084raises an exception (\exception{OptionConflictError}) by default when
1085this happens. Since this is an easily-fixed programming error, you
Greg Wardbf8f1b52003-05-03 19:41:45 +00001086shouldn't try to catch this exception---fix your mistake and get on
Fred Drakecf6d74a2003-04-18 15:50:13 +00001087with life.
Neal Norwitz488609e2003-01-06 16:51:37 +00001088
1089Sometimes, you want newer options to deliberately replace the option
1090strings used by older options. You can achieve this by calling:
1091
1092\begin{verbatim}
1093parser.set_conflict_handler("resolve")
1094\end{verbatim}
1095
1096which instructs \module{optparse} to resolve option conflicts
1097intelligently.
1098
1099Here's how it works: every time you add an option, \module{optparse}
1100checks for conflicts with previously-added options. If it finds any,
1101it invokes the conflict-handling mechanism you specify either to the
1102\class{OptionParser} constructor:
1103
1104\begin{verbatim}
1105parser = OptionParser(..., conflict_handler="resolve")
1106\end{verbatim}
1107
1108or via the \method{set_conflict_handler()} method.
1109
1110The default conflict-handling mechanism is ``error''. The only other
1111one is ``ignore'', which restores the (arguably broken) behaviour of
1112\module{optparse} 1.1 and earlier.
1113
1114Here's an example: first, define an \class{OptionParser} set to
1115resolve conflicts intelligently:
1116
1117\begin{verbatim}
1118parser = OptionParser(conflict_handler="resolve")
1119\end{verbatim}
1120
1121Now add all of our options:
1122
1123\begin{verbatim}
1124parser.add_option("-n", "--dry-run", ..., help="original dry-run option")
Fred Drakecf6d74a2003-04-18 15:50:13 +00001125...
Neal Norwitz488609e2003-01-06 16:51:37 +00001126parser.add_option("-n", "--noisy", ..., help="be noisy")
1127\end{verbatim}
1128
1129At this point, \module{optparse} detects that a previously-added option is already
1130using the \programopt{-n} option string. Since \code{conflict_handler
1131== "resolve"}, it resolves the situation by removing \programopt{-n}
1132from the earlier option's list of option strings. Now,
1133\longprogramopt{dry-run} is the only way for the user to activate that
1134option. If the user asks for help, the help message will reflect
1135that, e.g.:
1136
1137\begin{verbatim}
1138options:
1139 --dry-run original dry-run option
Fred Drakecf6d74a2003-04-18 15:50:13 +00001140 ...
Neal Norwitz488609e2003-01-06 16:51:37 +00001141 -n, --noisy be noisy
1142\end{verbatim}
1143
1144Note that it's possible to whittle away the option strings for a
1145previously-added option until there are none left, and the user has no
1146way of invoking that option from the command-line. In that case,
1147\module{optparse} removes that option completely, so it doesn't show
1148up in help text or anywhere else. E.g. if we carry on with our
1149existing \class{OptionParser}:
1150
1151\begin{verbatim}
1152parser.add_option("--dry-run", ..., help="new dry-run option")
1153\end{verbatim}
1154
1155At this point, the first \programopt{-n}/\longprogramopt{dry-run}
1156option is no longer accessible, so \module{optparse} removes it. If
1157the user asks for help, they'll get something like this:
1158
1159\begin{verbatim}
1160options:
Fred Drakecf6d74a2003-04-18 15:50:13 +00001161 ...
Neal Norwitz488609e2003-01-06 16:51:37 +00001162 -n, --noisy be noisy
1163 --dry-run new dry-run option
1164\end{verbatim}
1165
1166\subsection{Callback Options\label{optparse-callback-options}}
1167
1168If \module{optparse}'s built-in actions and types just don't fit the
1169bill for you, but it's not worth extending \module{optparse} to define
1170your own actions or types, you'll probably need to define a callback
1171option. Defining callback options is quite easy; the tricky part is
1172writing a good callback (the function that is called when
1173\module{optparse} encounters the option on the command line).
1174
1175\subsubsection{Defining a callback option\label{optparse-defining-callback-option}}
1176
1177As always, you can define a callback option either by directly
1178instantiating the \class{Option} class, or by using the
1179\method{add_option()} method of your \class{OptionParser} object. The
1180only option attribute you must specify is \var{callback}, the function
1181to call:
1182
1183\begin{verbatim}
1184parser.add_option("-c", callback=my_callback)
1185\end{verbatim}
1186
Greg Wardbf8f1b52003-05-03 19:41:45 +00001187Note that you supply a function object here---so you must have
Neal Norwitz488609e2003-01-06 16:51:37 +00001188already defined a function \function{my_callback()} when you define
1189the callback option. In this simple case, \module{optparse} knows
1190nothing about the arguments the \programopt{-c} option expects to
1191take. Usually, this means that the option doesn't take any arguments
1192-- the mere presence of \programopt{-c} on the command-line is all it
1193needs to know. In some circumstances, though, you might want your
1194callback to consume an arbitrary number of command-line arguments.
1195This is where writing callbacks gets tricky; it's covered later in
1196this document.
1197
1198There are several other option attributes that you can supply when you
1199define an option attribute:
1200
1201\begin{definitions}
1202\term{type}
1203has its usual meaning: as with the ``store'' or ``append'' actions, it
1204instructs \module{optparse} to consume one argument that must be
1205convertible to \var{type}. Rather than storing the value(s) anywhere,
1206though, \module{optparse} converts it to \var{type} and passes it to
1207your callback function.
1208
1209\term{nargs}
1210also has its usual meaning: if it is supplied and \samp{nargs > 1},
1211\module{optparse} will consume \var{nargs} arguments, each of which
1212must be convertible to \var{type}. It then passes a tuple of
1213converted values to your callback.
1214
1215\term{callback_args}
1216a tuple of extra positional arguments to pass to the callback.
1217
1218\term{callback_kwargs}
1219a dictionary of extra keyword arguments to pass to the callback.
1220\end{definitions}
1221
1222\subsubsection{How callbacks are called\label{optparse-callbacks-called}}
1223
1224All callbacks are called as follows:
1225
1226\begin{verbatim}
1227func(option, opt, value, parser, *args, **kwargs)
1228\end{verbatim}
1229
1230where
1231
1232\begin{definitions}
1233\term{option}
1234is the \class{Option} instance that's calling the callback.
1235
1236\term{opt}
1237is the option string seen on the command-line that's triggering the
1238callback. (If an abbreviated long option was used, \var{opt} will be
Greg Wardbf8f1b52003-05-03 19:41:45 +00001239the full, canonical option string---e.g. if the user puts
Neal Norwitz488609e2003-01-06 16:51:37 +00001240\longprogramopt{foo} on the command-line as an abbreviation for
1241\longprogramopt{foobar}, then \var{opt} will be
1242\longprogramopt{foobar}.)
1243
1244\term{value}
1245is the argument to this option seen on the command-line.
1246\module{optparse} will only expect an argument if \var{type} is
1247set; the type of \var{value} will be the type implied by the
Fred Drakecf6d74a2003-04-18 15:50:13 +00001248option's type (see~\ref{optparse-option-types}, ``Option types''). If
Neal Norwitz488609e2003-01-06 16:51:37 +00001249\var{type} for this option is None (no argument expected), then
1250\var{value} will be None. If \samp{nargs > 1}, \var{value} will
1251be a tuple of values of the appropriate type.
1252
1253\term{parser}
1254is the \class{OptionParser} instance driving the whole thing, mainly
1255useful because you can access some other interesting data through it,
1256as instance attributes:
1257
1258\begin{definitions}
1259\term{parser.rargs}
1260the current remaining argument list, ie. with \var{opt} (and
1261\var{value}, if any) removed, and only the arguments following
1262them still there. Feel free to modify \member{parser.rargs},
1263e.g. by consuming more arguments.
1264
1265\term{parser.largs}
1266the current set of leftover arguments, ie. arguments that have been
1267processed but have not been consumed as options (or arguments to
1268options). Feel free to modify \member{parser.largs} e.g. by adding
1269more arguments to it.
1270
1271\term{parser.values}
1272the object where option values are by default stored. This is useful
1273because it lets callbacks use the same mechanism as the rest of
1274\module{optparse} for storing option values; you don't need to mess
1275around with globals or closures. You can also access the value(s) of
1276any options already encountered on the command-line.
1277\end{definitions}
1278
1279\term{args}
1280is a tuple of arbitrary positional arguments supplied via the
1281\var{callback}_args option attribute.
1282
1283\term{kwargs}
1284is a dictionary of arbitrary keyword arguments supplied via
1285\var{callback_kwargs}.
1286\end{definitions}
1287
1288Since \var{args} and \var{kwargs} are optional (they are only passed
1289if you supply \var{callback_args} and/or \var{callback_kwargs} when
1290you define your callback option), the minimal callback function is:
1291
1292\begin{verbatim}
1293def my_callback (option, opt, value, parser):
1294 pass
1295\end{verbatim}
1296
1297\subsubsection{Error handling\label{optparse-callback-error-handling}}
1298
1299The callback function should raise \exception{OptionValueError} if
1300there are any problems with the option or its
1301argument(s). \module{optparse} catches this and terminates the
1302program, printing the error message you supply to stderr. Your
1303message should be clear, concise, accurate, and mention the option at
1304fault. Otherwise, the user will have a hard time figuring out what he
1305did wrong.
1306
1307\subsubsection{Examples\label{optparse-callback-examples}}
1308
1309Here's an example of a callback option that takes no arguments, and
1310simply records that the option was seen:
1311
1312\begin{verbatim}
1313def record_foo_seen (option, opt, value, parser):
1314 parser.saw_foo = 1
1315
1316parser.add_option("--foo", action="callback", callback=record_foo_seen)
1317\end{verbatim}
1318
1319Of course, you could do that with the ``store_true'' action. Here's a
1320slightly more interesting example: record the fact that
1321\programopt{-a} is seen, but blow up if it comes after \programopt{-b}
1322in the command-line.
1323
1324\begin{verbatim}
1325def check_order (option, opt, value, parser):
1326 if parser.values.b:
1327 raise OptionValueError("can't use -a after -b")
1328 parser.values.a = 1
Fred Drakecf6d74a2003-04-18 15:50:13 +00001329...
Neal Norwitz488609e2003-01-06 16:51:37 +00001330parser.add_option("-a", action="callback", callback=check_order)
1331parser.add_option("-b", action="store_true", dest="b")
1332\end{verbatim}
1333
1334If you want to reuse this callback for several similar options (set a
1335flag, but blow up if \programopt{-b} has already been seen), it needs
1336a bit of work: the error message and the flag that it sets must be
1337generalized.
1338
1339\begin{verbatim}
1340def check_order (option, opt, value, parser):
1341 if parser.values.b:
1342 raise OptionValueError("can't use %s after -b" % opt)
1343 setattr(parser.values, option.dest, 1)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001344...
Neal Norwitz488609e2003-01-06 16:51:37 +00001345parser.add_option("-a", action="callback", callback=check_order, dest='a')
1346parser.add_option("-b", action="store_true", dest="b")
1347parser.add_option("-c", action="callback", callback=check_order, dest='c')
1348\end{verbatim}
1349
Greg Wardbf8f1b52003-05-03 19:41:45 +00001350Of course, you could put any condition in there---you're not limited
Neal Norwitz488609e2003-01-06 16:51:37 +00001351to checking the values of already-defined options. For example, if
1352you have options that should not be called when the moon is full, all
1353you have to do is this:
1354
1355\begin{verbatim}
1356def check_moon (option, opt, value, parser):
1357 if is_full_moon():
1358 raise OptionValueError("%s option invalid when moon full" % opt)
1359 setattr(parser.values, option.dest, 1)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001360...
Neal Norwitz488609e2003-01-06 16:51:37 +00001361parser.add_option("--foo",
1362 action="callback", callback=check_moon, dest="foo")
1363\end{verbatim}
1364
Greg Wardbf8f1b52003-05-03 19:41:45 +00001365(The definition of \code{is_full_moon()} is left as an exercise for the
Neal Norwitz488609e2003-01-06 16:51:37 +00001366reader.)
1367
1368\strong{Fixed arguments}
1369
1370Things get slightly more interesting when you define callback options
1371that take a fixed number of arguments. Specifying that a callback
1372option takes arguments is similar to defining a ``store'' or
1373``append'' option: if you define \var{type}, then the option takes one
1374argument that must be convertible to that type; if you further define
1375\var{nargs}, then the option takes that many arguments.
1376
1377Here's an example that just emulates the standard ``store'' action:
1378
1379\begin{verbatim}
1380def store_value (option, opt, value, parser):
1381 setattr(parser.values, option.dest, value)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001382...
Neal Norwitz488609e2003-01-06 16:51:37 +00001383parser.add_option("--foo",
1384 action="callback", callback=store_value,
1385 type="int", nargs=3, dest="foo")
1386\end{verbatim}
1387
1388Note that \module{optparse} takes care of consuming 3 arguments and
1389converting them to integers for you; all you have to do is store them.
1390(Or whatever: obviously you don't need a callback for this example.
1391Use your imagination!)
1392
1393\strong{Variable arguments}
1394
1395Things get hairy when you want an option to take a variable number of
1396arguments. For this case, you have to write a callback;
1397\module{optparse} doesn't provide any built-in capabilities for it.
Fred Drakecf6d74a2003-04-18 15:50:13 +00001398You have to deal with the full-blown syntax for conventional \UNIX{}
Neal Norwitz488609e2003-01-06 16:51:37 +00001399command-line parsing. (Previously, \module{optparse} took care of
1400this for you, but I got it wrong. It was fixed at the cost of making
1401this kind of callback more complex.) In particular, callbacks have to
1402worry about bare \longprogramopt{} and \programopt{-} arguments; the
1403convention is:
1404
1405\begin{itemize}
1406\item bare \longprogramopt{}, if not the argument to some option,
1407causes command-line processing to halt and the \longprogramopt{}
1408itself is lost.
1409
1410\item bare \programopt{-} similarly causes command-line processing to
1411halt, but the \programopt{-} itself is kept.
1412
1413\item either \longprogramopt{} or \programopt{-} can be option
1414arguments.
1415\end{itemize}
1416
1417If you want an option that takes a variable number of arguments, there
1418are several subtle, tricky issues to worry about. The exact
1419implementation you choose will be based on which trade-offs you're
1420willing to make for your application (which is why \module{optparse}
1421doesn't support this sort of thing directly).
1422
1423Nevertheless, here's a stab at a callback for an option with variable
1424arguments:
1425
1426\begin{verbatim}
1427def varargs (option, opt, value, parser):
1428 assert value is None
1429 done = 0
1430 value = []
1431 rargs = parser.rargs
1432 while rargs:
1433 arg = rargs[0]
1434
1435 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1436 # etc. Note that this also stops on "-3" or "-3.0", so if
1437 # your option takes numeric values, you will need to handle
1438 # this.
1439 if ((arg[:2] == "--" and len(arg) > 2) or
1440 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1441 break
1442 else:
1443 value.append(arg)
1444 del rargs[0]
1445
1446 setattr(parser.values, option.dest, value)
1447
Fred Drakecf6d74a2003-04-18 15:50:13 +00001448...
Neal Norwitz488609e2003-01-06 16:51:37 +00001449parser.add_option("-c", "--callback",
1450 action="callback", callback=varargs)
1451\end{verbatim}
1452
1453The main weakness with this particular implementation is that negative
1454numbers in the arguments following \programopt{-c} will be interpreted
1455as further options, rather than as arguments to \programopt{-c}.
1456Fixing this is left as an exercise for the reader.
1457
1458\subsection{Extending \module{optparse}\label{optparse-extending}}
1459
1460Since the two major controlling factors in how \module{optparse}
1461interprets command-line options are the action and type of each
1462option, the most likely direction of extension is to add new actions
1463and new types.
1464
1465Also, the examples section includes several demonstrations of
1466extending \module{optparse} in different ways: eg. a case-insensitive
1467option parser, or two kinds of option parsers that implement
1468``required options''.
1469
1470\subsubsection{Adding new types\label{optparse-adding-types}}
1471
1472To add new types, you need to define your own subclass of
1473\module{optparse}'s \class{Option} class. This class has a couple of
1474attributes that define \module{optparse}'s types: \member{TYPES} and
1475\member{TYPE_CHECKER}.
1476
1477\member{TYPES} is a tuple of type names; in your subclass, simply
1478define a new tuple \member{TYPES} that builds on the standard one.
1479
1480\member{TYPE_CHECKER} is a dictionary mapping type names to
1481type-checking functions. A type-checking function has the following
1482signature:
1483
1484\begin{verbatim}
1485def check_foo (option : Option, opt : string, value : string)
1486 -> foo
1487\end{verbatim}
1488
1489You can name it whatever you like, and make it return any type you
1490like. The value returned by a type-checking function will wind up in
1491the \class{OptionValues} instance returned by
1492\method{OptionParser.parse_args()}, or be passed to callbacks as the
1493\var{value} parameter.
1494
1495Your type-checking function should raise \exception{OptionValueError}
1496if it encounters any problems. \exception{OptionValueError} takes a
1497single string argument, which is passed as-is to
1498\class{OptionParser}'s \method{error()} method, which in turn prepends
1499the program name and the string ``error:'' and prints everything to
1500stderr before terminating the process.
1501
1502Here's a silly example that demonstrates adding a ``complex'' option
1503type to parse Python-style complex numbers on the command line. (This
1504is even sillier than it used to be, because \module{optparse} 1.3 adds
1505built-in support for complex numbers [purely for completeness], but
1506never mind.)
1507
1508First, the necessary imports:
1509
1510\begin{verbatim}
1511from copy import copy
1512from optparse import Option, OptionValueError
1513\end{verbatim}
1514
1515You need to define your type-checker first, since it's referred to
1516later (in the \member{TYPE_CHECKER} class attribute of your
1517\class{Option} subclass):
1518
1519\begin{verbatim}
1520def check_complex (option, opt, value):
1521 try:
1522 return complex(value)
1523 except ValueError:
1524 raise OptionValueError(
1525 "option %s: invalid complex value: %r" % (opt, value))
1526\end{verbatim}
1527
1528Finally, the \class{Option} subclass:
1529
1530\begin{verbatim}
1531class MyOption (Option):
1532 TYPES = Option.TYPES + ("complex",)
1533 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1534 TYPE_CHECKER["complex"] = check_complex
1535\end{verbatim}
1536
1537(If we didn't make a \function{copy()} of
1538\member{Option.TYPE_CHECKER}, we would end up modifying the
1539\member{TYPE_CHECKER} attribute of \module{optparse}'s Option class.
1540This being Python, nothing stops you from doing that except good
1541manners and common sense.)
1542
1543That's it! Now you can write a script that uses the new option type
1544just like any other \module{optparse}-based script, except you have to
1545instruct your \class{OptionParser} to use \class{MyOption} instead of
1546\class{Option}:
1547
1548\begin{verbatim}
1549parser = OptionParser(option_class=MyOption)
1550parser.add_option("-c", action="store", type="complex", dest="c")
1551\end{verbatim}
1552
1553Alternately, you can build your own option list and pass it to
1554\class{OptionParser}; if you don't use \method{add_option()} in the
1555above way, you don't need to tell \class{OptionParser} which option
1556class to use:
1557
1558\begin{verbatim}
1559option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1560parser = OptionParser(option_list=option_list)
1561\end{verbatim}
1562
1563\subsubsection{Adding new actions\label{optparse-adding-actions}}
1564
1565Adding new actions is a bit trickier, because you have to understand
1566that \module{optparse} has a couple of classifications for actions:
1567
1568\begin{definitions}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001569\term{``store'' actions}
Neal Norwitz488609e2003-01-06 16:51:37 +00001570 actions that result in \module{optparse} storing a value to an attribute
Greg Wardbf8f1b52003-05-03 19:41:45 +00001571 of the OptionValues instance; these options require a \var{dest}
Neal Norwitz488609e2003-01-06 16:51:37 +00001572 attribute to be supplied to the Option constructor
Greg Wardbf8f1b52003-05-03 19:41:45 +00001573\term{``typed'' actions}
Neal Norwitz488609e2003-01-06 16:51:37 +00001574 actions that take a value from the command line and expect it to be
1575 of a certain type; or rather, a string that can be converted to a
Greg Wardbf8f1b52003-05-03 19:41:45 +00001576 certain type. These options require a \var{type} attribute to the
Neal Norwitz488609e2003-01-06 16:51:37 +00001577 Option constructor.
1578\end{definitions}
1579
Greg Wardbf8f1b52003-05-03 19:41:45 +00001580Some default ``store'' actions are \var{store}, \var{store_const},
1581\var{append}, and \var{count}. The default ``typed'' actions are
1582\var{store}, \var{append}, and \var{callback}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001583
1584When you add an action, you need to decide if it's a ``store'' action,
1585a ``typed'', neither, or both. Three class attributes of
1586\class{Option} (or your \class{Option} subclass) control this:
1587
1588\begin{memberdesc}{ACTIONS}
1589 All actions must be listed as strings in ACTIONS.
1590\end{memberdesc}
1591\begin{memberdesc}{STORE_ACTIONS}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001592 ``store'' actions are additionally listed here.
Neal Norwitz488609e2003-01-06 16:51:37 +00001593\end{memberdesc}
1594\begin{memberdesc}{TYPED_ACTIONS}
Greg Wardbf8f1b52003-05-03 19:41:45 +00001595 ``typed'' actions are additionally listed here.
Neal Norwitz488609e2003-01-06 16:51:37 +00001596\end{memberdesc}
1597
1598In order to actually implement your new action, you must override
1599\class{Option}'s \method{take_action()} method and add a case that
1600recognizes your action.
1601
1602For example, let's add an ``extend'' action. This is similar to the
1603standard ``append'' action, but instead of taking a single value from
1604the command-line and appending it to an existing list, ``extend'' will
1605take multiple values in a single comma-delimited string, and extend an
1606existing list with them. That is, if \longprogramopt{names} is an
1607``extend'' option of type string, the command line:
1608
1609\begin{verbatim}
1610--names=foo,bar --names blah --names ding,dong
1611\end{verbatim}
1612
1613would result in a list:
1614
1615\begin{verbatim}
1616["foo", "bar", "blah", "ding", "dong"]
1617\end{verbatim}
1618
1619Again we define a subclass of \class{Option}:
1620
1621\begin{verbatim}
1622class MyOption (Option):
1623
1624 ACTIONS = Option.ACTIONS + ("extend",)
1625 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1626 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1627
1628 def take_action (self, action, dest, opt, value, values, parser):
1629 if action == "extend":
1630 lvalue = value.split(",")
1631 values.ensure_value(dest, []).extend(lvalue)
1632 else:
1633 Option.take_action(
1634 self, action, dest, opt, value, values, parser)
1635\end{verbatim}
1636
1637Features of note:
1638
1639\begin{itemize}
1640\item ``extend'' both expects a value on the command-line and stores that
1641value somewhere, so it goes in both \member{STORE_ACTIONS} and
1642\member{TYPED_ACTIONS}.
1643
1644\item \method{MyOption.take_action()} implements just this one new
1645action, and passes control back to \method{Option.take_action()} for
1646the standard \module{optparse} actions.
1647
1648\item \var{values} is an instance of the \class{Values} class, which
1649provides the very useful \method{ensure_value()}
1650method. \method{ensure_value()} is essentially \function{getattr()}
1651with a safety valve; it is called as:
1652
1653\begin{verbatim}
1654values.ensure_value(attr, value)
1655\end{verbatim}
1656\end{itemize}
1657
1658If the \member{attr} attribute of \var{values} doesn't exist or is
1659None, then \method{ensure_value()} first sets it to \var{value}, and
1660then returns \var{value}. This is very handy for actions like
1661``extend'', ``append'', and ``count'', all of which accumulate data in
1662a variable and expect that variable to be of a certain type (a list
1663for the first two, an integer for the latter). Using
1664\method{ensure_value()} means that scripts using your action don't
1665have to worry about setting a default value for the option
1666destinations in question; they can just leave the default as None and
1667\method{ensure_value()} will take care of getting it right when it's
1668needed.
1669
1670\subsubsection{Other reasons to extend \module{optparse}\label{optparse-extending-other-reasons}}
1671
1672Adding new types and new actions are the big, obvious reasons why you
1673might want to extend \module{optparse}. I can think of at least two
1674other areas to play with.
1675
1676First, the simple one: \class{OptionParser} tries to be helpful by
1677calling \function{sys.exit()} when appropriate, ie. when there's an
1678error on the command-line or when the user requests help. In the
1679former case, the traditional course of letting the script crash with a
1680traceback is unacceptable; it will make users think there's a bug in
1681your script when they make a command-line error. In the latter case,
1682there's generally not much point in carrying on after printing a help
1683message.
1684
1685If this behaviour bothers you, it shouldn't be too hard to ``fix'' it.
1686You'll have to
1687
1688\begin{enumerate}
1689\item subclass OptionParser and override the error() method
Greg Wardbf8f1b52003-05-03 19:41:45 +00001690\item subclass Option and override the take_action() method---you'll
1691 need to provide your own handling of the ``help'' action that
Neal Norwitz488609e2003-01-06 16:51:37 +00001692 doesn't call sys.exit()
1693\end{enumerate}
1694
1695The second, much more complex, possibility is to override the
1696command-line syntax implemented by \module{optparse}. In this case,
1697you'd leave the whole machinery of option actions and types alone, but
1698rewrite the code that processes \var{sys.argv}. You'll need to
1699subclass \class{OptionParser} in any case; depending on how radical a
1700rewrite you want, you'll probably need to override one or all of
1701\method{parse_args()}, \method{_process_long_opt()}, and
1702\method{_process_short_opts()}.
1703
1704Both of these are left as an exercise for the reader. I have not
1705tried to implement either myself, since I'm quite happy with
1706\module{optparse}'s default behaviour (naturally).
1707
1708Happy hacking, and don't forget: Use the Source, Luke.
1709
1710\subsubsection{Examples\label{optparse-extending-examples}}
1711
1712Here are a few examples of extending the \module{optparse} module.
1713
1714First, let's change the option-parsing to be case-insensitive:
1715
1716\verbatiminput{caseless.py}
1717
1718And two ways of implementing ``required options'' with
1719\module{optparse}.
1720
1721Version 1: Add a method to \class{OptionParser} which applications
1722must call after parsing arguments:
1723
1724\verbatiminput{required_1.py}
1725
1726Version 2: Extend \class{Option} and add a \member{required}
1727attribute; extend \class{OptionParser} to ensure that required options
1728are present after parsing:
1729
Fred Drakecf6d74a2003-04-18 15:50:13 +00001730\verbatiminput{required_2.py}