blob: 8b1b40483d27500937f21b76eaf6ad7a5c41bf40 [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",
29 action="store_false", dest="verbose", default=1,
30 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
36"usual thing" on the command-line:
37
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
46\code{options.verbose == 0} ...just as you might expect.)
47
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},
191and \program{dd} --- all of which are mutant oddballs that have been
192rightly 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
Fred Drakecf6d74a2003-04-18 15:50:13 +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
Fred Drakecf6d74a2003-04-18 15:50:13 +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''
Fred Drakecf6d74a2003-04-18 15:50:13 +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
284\subsubsection{The "store" action\label{optparse-store-action}}
285
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
292For example, let's fill in the "..." of that last option:
293
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
Fred Drakecf6d74a2003-04-18 15:50:13 +0000311argument --- ``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
319will print ``foo.txt''.
320
321Other option types supported by \module{optparse} are ``int'' and
322``float''. Here's an option that expects an integer argument:
323
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.
Fred Drakecf6d74a2003-04-18 15:50:13 +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
Fred Drakecf6d74a2003-04-18 15:50:13 +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
362\subsubsection{Other "store_*" actions\label{optparse-other-store-actions}}
363
Fred Drakecf6d74a2003-04-18 15:50:13 +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
Fred Drakecf6d74a2003-04-18 15:50:13 +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
Fred Drakecf6d74a2003-04-18 15:50:13 +0000396\module{optparse} to set \var{verbose} to 1 unless \programopt{-q} is
397seen, then we can do this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000398
399\begin{verbatim}
400parser.add_option("-v", action="store_true", dest="verbose", default=1)
401parser.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")
408parser.add_option("-q", action="store_false", dest="verbose", default=1)
409\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}
418parser.add_option("-v", action="store_true", dest="verbose", default=0)
419parser.add_option("-q", action="store_false", dest="verbose", default=1)
420\end{verbatim}
421
422Again, the default value for \var{verbose} will be 1: the last
423default 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",
438 action="store_true", dest="verbose", default=1,
439 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
477\module{optparse} expands "\%prog" in the usage string to the name of the
478current 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
482sensible default: ``usage: \%prog [options]'', which is fine if your
483script doesn't take any positional arguments.
484
485\item every option defines a help string, and doesn't worry about
Fred Drakecf6d74a2003-04-18 15:50:13 +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
Fred Drakecf6d74a2003-04-18 15:50:13 +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
Fred Drakecf6d74a2003-04-18 15:50:13 +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
Fred Drakecf6d74a2003-04-18 15:50:13 +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
867A special case of ``store_const'' that stores a true value
868(specifically, the integer 1) to \var{dest}.
869
870\term{store_false} [required: \var{dest}]
871
872Like ``store_true'', but stores a false value (the integer 0).
873
874Example:
875
876\begin{verbatim}
877make_option(None, "--clobber", action="store_true", dest="clobber")
878make_option(None, "--no-clobber", action="store_false", dest="clobber")
879\end{verbatim}
880
881\term{append} [relevant: \var{type}, \var{dest}, \var{nargs}, \var{choices}]
882
883The option must be followed by an argument, which is appended to the
884list in \var{dest}. If no default value for \var{dest} is supplied
885(ie. the default is None), an empty list is automatically created when
886\module{optparse} first encounters this option on the command-line.
887If \samp{nargs > 1}, multiple arguments are consumed, and a tuple of
888length \var{nargs} is appended to \var{dest}.
889
890The defaults for \var{type} and \var{dest} are the same as for the
891``store'' action.
892
893Example:
894
895\begin{verbatim}
896make_option("-t", "--tracks", action="append", type="int")
897\end{verbatim}
898
899If \programopt{-t3} is seen on the command-line, \module{optparse} does the equivalent of:
900
901\begin{verbatim}
902values.tracks = []
903values.tracks.append(int("3"))
904\end{verbatim}
905
Greg Wardb4e33192003-05-03 19:16:36 +0000906If, a little later on, \longprogramopt{tracks=4} is seen, it does:
Neal Norwitz488609e2003-01-06 16:51:37 +0000907
908\begin{verbatim}
909values.tracks.append(int("4"))
910\end{verbatim}
911
Fred Drakecf6d74a2003-04-18 15:50:13 +0000912See ``Error handling'' (section~\ref{optparse-error-handling}) for
Neal Norwitz488609e2003-01-06 16:51:37 +0000913information on how \module{optparse} deals with something like
Greg Wardb4e33192003-05-03 19:16:36 +0000914\longprogramopt{tracks=x}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000915
916\term{count} [required: \var{dest}]
917
918Increment the integer stored at \var{dest}. \var{dest} is set to zero
919before being incremented the first time (unless you supply a default
920value).
921
922Example:
923
924\begin{verbatim}
925make_option("-v", action="count", dest="verbosity")
926\end{verbatim}
927
928The first time \programopt{-v} is seen on the command line,
929\module{optparse} does the equivalent of:
930
931\begin{verbatim}
932values.verbosity = 0
933values.verbosity += 1
934\end{verbatim}
935
936Every subsequent occurrence of \programopt{-v} results in:
937
938\begin{verbatim}
939values.verbosity += 1
940\end{verbatim}
941
942\term{callback} [required: \var{'callback'};
943 relevant: \var{type}, \var{nargs}, \var{callback_args},
944 \var{callback_kwargs}]
945
946Call the function specified by \var{callback}. The signature of
947this function should be:
948
949\begin{verbatim}
950func(option : Option,
951 opt : string,
952 value : any,
953 parser : OptionParser,
954 *args, **kwargs)
955\end{verbatim}
956
Fred Drakecf6d74a2003-04-18 15:50:13 +0000957Callback options are covered in detail in
958section~\ref{optparse-callback-options} ``Callback Options.''
Neal Norwitz488609e2003-01-06 16:51:37 +0000959
960\term{help} [required: none]
961
962Prints a complete help message for all the options in the current
963option parser. The help message is constructed from the \var{usage}
964string passed to \class{OptionParser}'s constructor and the \var{help}
965string passed to every option.
966
967If no \var{help} string is supplied for an option, it will still be
968listed in the help message. To omit an option entirely, use the
969special value \constant{optparse.SUPPRESS_HELP}.
970
971Example:
972
973\begin{verbatim}
974from optparse import Option, OptionParser, SUPPRESS_HELP
975
976usage = "usage: %prog [options]"
977parser = OptionParser(usage, option_list=[
978 make_option("-h", "--help", action="help"),
979 make_option("-v", action="store_true", dest="verbose",
980 help="Be moderately verbose")
981 make_option("--file", dest="filename",
982 help="Input file to read data from"),
983 make_option("--secret", help=SUPPRESS_HELP)
984\end{verbatim}
985
Greg Wardb4e33192003-05-03 19:16:36 +0000986If \module{optparse} sees either \programopt{-h} or
987\longprogramopt{help} on the command line, it will print something
988like the following help message to stdout:
Neal Norwitz488609e2003-01-06 16:51:37 +0000989
990\begin{verbatim}
991usage: <yourscript> [options]
992
993options:
994 -h, --help Show this help message and exit
995 -v Be moderately verbose
996 --file=FILENAME Input file to read data from
997\end{verbatim}
998
999After printing the help message, \module{optparse} terminates your process
1000with \code{sys.exit(0)}.
1001
1002\term{version} [required: none]
1003
1004Prints the version number supplied to the \class{OptionParser} to
1005stdout and exits. The version number is actually formatted and
1006printed by the \method{print_version()} method of
1007\class{OptionParser}. Generally only relevant if the \var{version}
1008argument is supplied to the \class{OptionParser} constructor.
1009\end{definitions}
1010
1011\subsubsection{Option types\label{optparse-option-types}}
1012
1013\module{optparse} supports six option types out of the box: \dfn{string},
1014\dfn{int}, \dfn{long}, \dfn{choice}, \dfn{float} and \dfn{complex}.
1015(Of these, string, int, float, and choice are the most commonly used
1016-- long and complex are there mainly for completeness.) It's easy to
1017add new option types by subclassing the \class{Option} class; see
Fred Drakecf6d74a2003-04-18 15:50:13 +00001018section~\ref{optparse-extending}, ``Extending \module{optparse}.''
Neal Norwitz488609e2003-01-06 16:51:37 +00001019
1020Arguments to string options are not checked or converted in any way:
1021the text on the command line is stored in the destination (or passed
1022to the callback) as-is.
1023
1024Integer arguments are passed to \function{int()} to convert them to
1025Python integers. If \function{int()} fails, so will
1026\module{optparse}, although with a more useful error message.
1027Internally, \module{optparse} raises \exception{OptionValueError} in
1028\function{optparse.check_builtin()}; at a higher level (in
1029\class{OptionParser}) this is caught and \module{optparse} terminates
1030your program with a useful error message.
1031
1032Likewise, float arguments are passed to \function{float()} for
1033conversion, long arguments to \function{long()}, and complex arguments
1034to \function{complex()}. Apart from that, they are handled
1035identically to integer arguments.
1036
1037Choice options are a subtype of string options. A master list or
1038tuple of choices (strings) must be passed to the option constructor
1039(\function{make_option()} or \method{OptionParser.add_option()}) as
1040the ``choices'' keyword argument. Choice option arguments are
1041compared against this master list in
1042\function{optparse.check_choice()}, and \exception{OptionValueError}
1043is raised if an unknown string is given.
1044
1045\subsubsection{Querying and manipulating your option parser\label{optparse-querying-and-manipulating}}
1046
1047Sometimes, it's useful to poke around your option parser and see what's
1048there. \class{OptionParser} provides a couple of methods to help you out:
1049
1050\begin{methoddesc}{has_option}{opt_str}
1051 Given an option string such as \programopt{-q} or
1052 \longprogramopt{verbose}, returns true if the \class{OptionParser}
1053 has an option with that option string.
1054\end{methoddesc}
1055
1056\begin{methoddesc}{get_option}{opt_str}
1057 Returns the \class{Option} instance that implements the option
1058 string you supplied, or None if no options implement it.
1059\end{methoddesc}
1060
1061\begin{methoddesc}{remove_option}{opt_str}
1062 If the \class{OptionParser} has an option corresponding to
1063 \var{opt_str}, that option is removed. If that option provided
1064 any other option strings, all of those option strings become
1065 invalid.
1066
1067 If \var{opt_str} does not occur in any option belonging to this
1068 \class{OptionParser}, raises \exception{ValueError}.
1069\end{methoddesc}
1070
1071\subsubsection{Conflicts between options\label{optparse-conflicts}}
1072
1073If you're not careful, it's easy to define conflicting options:
1074
1075\begin{verbatim}
1076parser.add_option("-n", "--dry-run", ...)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001077...
Neal Norwitz488609e2003-01-06 16:51:37 +00001078parser.add_option("-n", "--noisy", ...)
1079\end{verbatim}
1080
1081(This is even easier to do if you've defined your own
1082\class{OptionParser} subclass with some standard options.)
1083
1084On the assumption that this is usually a mistake, \module{optparse}
Fred Drakecf6d74a2003-04-18 15:50:13 +00001085raises an exception (\exception{OptionConflictError}) by default when
1086this happens. Since this is an easily-fixed programming error, you
1087shouldn't try to catch this exception --- fix your mistake and get on
1088with life.
Neal Norwitz488609e2003-01-06 16:51:37 +00001089
1090Sometimes, you want newer options to deliberately replace the option
1091strings used by older options. You can achieve this by calling:
1092
1093\begin{verbatim}
1094parser.set_conflict_handler("resolve")
1095\end{verbatim}
1096
1097which instructs \module{optparse} to resolve option conflicts
1098intelligently.
1099
1100Here's how it works: every time you add an option, \module{optparse}
1101checks for conflicts with previously-added options. If it finds any,
1102it invokes the conflict-handling mechanism you specify either to the
1103\class{OptionParser} constructor:
1104
1105\begin{verbatim}
1106parser = OptionParser(..., conflict_handler="resolve")
1107\end{verbatim}
1108
1109or via the \method{set_conflict_handler()} method.
1110
1111The default conflict-handling mechanism is ``error''. The only other
1112one is ``ignore'', which restores the (arguably broken) behaviour of
1113\module{optparse} 1.1 and earlier.
1114
1115Here's an example: first, define an \class{OptionParser} set to
1116resolve conflicts intelligently:
1117
1118\begin{verbatim}
1119parser = OptionParser(conflict_handler="resolve")
1120\end{verbatim}
1121
1122Now add all of our options:
1123
1124\begin{verbatim}
1125parser.add_option("-n", "--dry-run", ..., help="original dry-run option")
Fred Drakecf6d74a2003-04-18 15:50:13 +00001126...
Neal Norwitz488609e2003-01-06 16:51:37 +00001127parser.add_option("-n", "--noisy", ..., help="be noisy")
1128\end{verbatim}
1129
1130At this point, \module{optparse} detects that a previously-added option is already
1131using the \programopt{-n} option string. Since \code{conflict_handler
1132== "resolve"}, it resolves the situation by removing \programopt{-n}
1133from the earlier option's list of option strings. Now,
1134\longprogramopt{dry-run} is the only way for the user to activate that
1135option. If the user asks for help, the help message will reflect
1136that, e.g.:
1137
1138\begin{verbatim}
1139options:
1140 --dry-run original dry-run option
Fred Drakecf6d74a2003-04-18 15:50:13 +00001141 ...
Neal Norwitz488609e2003-01-06 16:51:37 +00001142 -n, --noisy be noisy
1143\end{verbatim}
1144
1145Note that it's possible to whittle away the option strings for a
1146previously-added option until there are none left, and the user has no
1147way of invoking that option from the command-line. In that case,
1148\module{optparse} removes that option completely, so it doesn't show
1149up in help text or anywhere else. E.g. if we carry on with our
1150existing \class{OptionParser}:
1151
1152\begin{verbatim}
1153parser.add_option("--dry-run", ..., help="new dry-run option")
1154\end{verbatim}
1155
1156At this point, the first \programopt{-n}/\longprogramopt{dry-run}
1157option is no longer accessible, so \module{optparse} removes it. If
1158the user asks for help, they'll get something like this:
1159
1160\begin{verbatim}
1161options:
Fred Drakecf6d74a2003-04-18 15:50:13 +00001162 ...
Neal Norwitz488609e2003-01-06 16:51:37 +00001163 -n, --noisy be noisy
1164 --dry-run new dry-run option
1165\end{verbatim}
1166
1167\subsection{Callback Options\label{optparse-callback-options}}
1168
1169If \module{optparse}'s built-in actions and types just don't fit the
1170bill for you, but it's not worth extending \module{optparse} to define
1171your own actions or types, you'll probably need to define a callback
1172option. Defining callback options is quite easy; the tricky part is
1173writing a good callback (the function that is called when
1174\module{optparse} encounters the option on the command line).
1175
1176\subsubsection{Defining a callback option\label{optparse-defining-callback-option}}
1177
1178As always, you can define a callback option either by directly
1179instantiating the \class{Option} class, or by using the
1180\method{add_option()} method of your \class{OptionParser} object. The
1181only option attribute you must specify is \var{callback}, the function
1182to call:
1183
1184\begin{verbatim}
1185parser.add_option("-c", callback=my_callback)
1186\end{verbatim}
1187
Fred Drakecf6d74a2003-04-18 15:50:13 +00001188Note that you supply a function object here --- so you must have
Neal Norwitz488609e2003-01-06 16:51:37 +00001189already defined a function \function{my_callback()} when you define
1190the callback option. In this simple case, \module{optparse} knows
1191nothing about the arguments the \programopt{-c} option expects to
1192take. Usually, this means that the option doesn't take any arguments
1193-- the mere presence of \programopt{-c} on the command-line is all it
1194needs to know. In some circumstances, though, you might want your
1195callback to consume an arbitrary number of command-line arguments.
1196This is where writing callbacks gets tricky; it's covered later in
1197this document.
1198
1199There are several other option attributes that you can supply when you
1200define an option attribute:
1201
1202\begin{definitions}
1203\term{type}
1204has its usual meaning: as with the ``store'' or ``append'' actions, it
1205instructs \module{optparse} to consume one argument that must be
1206convertible to \var{type}. Rather than storing the value(s) anywhere,
1207though, \module{optparse} converts it to \var{type} and passes it to
1208your callback function.
1209
1210\term{nargs}
1211also has its usual meaning: if it is supplied and \samp{nargs > 1},
1212\module{optparse} will consume \var{nargs} arguments, each of which
1213must be convertible to \var{type}. It then passes a tuple of
1214converted values to your callback.
1215
1216\term{callback_args}
1217a tuple of extra positional arguments to pass to the callback.
1218
1219\term{callback_kwargs}
1220a dictionary of extra keyword arguments to pass to the callback.
1221\end{definitions}
1222
1223\subsubsection{How callbacks are called\label{optparse-callbacks-called}}
1224
1225All callbacks are called as follows:
1226
1227\begin{verbatim}
1228func(option, opt, value, parser, *args, **kwargs)
1229\end{verbatim}
1230
1231where
1232
1233\begin{definitions}
1234\term{option}
1235is the \class{Option} instance that's calling the callback.
1236
1237\term{opt}
1238is the option string seen on the command-line that's triggering the
1239callback. (If an abbreviated long option was used, \var{opt} will be
Fred Drakecf6d74a2003-04-18 15:50:13 +00001240the full, canonical option string --- e.g. if the user puts
Neal Norwitz488609e2003-01-06 16:51:37 +00001241\longprogramopt{foo} on the command-line as an abbreviation for
1242\longprogramopt{foobar}, then \var{opt} will be
1243\longprogramopt{foobar}.)
1244
1245\term{value}
1246is the argument to this option seen on the command-line.
1247\module{optparse} will only expect an argument if \var{type} is
1248set; the type of \var{value} will be the type implied by the
Fred Drakecf6d74a2003-04-18 15:50:13 +00001249option's type (see~\ref{optparse-option-types}, ``Option types''). If
Neal Norwitz488609e2003-01-06 16:51:37 +00001250\var{type} for this option is None (no argument expected), then
1251\var{value} will be None. If \samp{nargs > 1}, \var{value} will
1252be a tuple of values of the appropriate type.
1253
1254\term{parser}
1255is the \class{OptionParser} instance driving the whole thing, mainly
1256useful because you can access some other interesting data through it,
1257as instance attributes:
1258
1259\begin{definitions}
1260\term{parser.rargs}
1261the current remaining argument list, ie. with \var{opt} (and
1262\var{value}, if any) removed, and only the arguments following
1263them still there. Feel free to modify \member{parser.rargs},
1264e.g. by consuming more arguments.
1265
1266\term{parser.largs}
1267the current set of leftover arguments, ie. arguments that have been
1268processed but have not been consumed as options (or arguments to
1269options). Feel free to modify \member{parser.largs} e.g. by adding
1270more arguments to it.
1271
1272\term{parser.values}
1273the object where option values are by default stored. This is useful
1274because it lets callbacks use the same mechanism as the rest of
1275\module{optparse} for storing option values; you don't need to mess
1276around with globals or closures. You can also access the value(s) of
1277any options already encountered on the command-line.
1278\end{definitions}
1279
1280\term{args}
1281is a tuple of arbitrary positional arguments supplied via the
1282\var{callback}_args option attribute.
1283
1284\term{kwargs}
1285is a dictionary of arbitrary keyword arguments supplied via
1286\var{callback_kwargs}.
1287\end{definitions}
1288
1289Since \var{args} and \var{kwargs} are optional (they are only passed
1290if you supply \var{callback_args} and/or \var{callback_kwargs} when
1291you define your callback option), the minimal callback function is:
1292
1293\begin{verbatim}
1294def my_callback (option, opt, value, parser):
1295 pass
1296\end{verbatim}
1297
1298\subsubsection{Error handling\label{optparse-callback-error-handling}}
1299
1300The callback function should raise \exception{OptionValueError} if
1301there are any problems with the option or its
1302argument(s). \module{optparse} catches this and terminates the
1303program, printing the error message you supply to stderr. Your
1304message should be clear, concise, accurate, and mention the option at
1305fault. Otherwise, the user will have a hard time figuring out what he
1306did wrong.
1307
1308\subsubsection{Examples\label{optparse-callback-examples}}
1309
1310Here's an example of a callback option that takes no arguments, and
1311simply records that the option was seen:
1312
1313\begin{verbatim}
1314def record_foo_seen (option, opt, value, parser):
1315 parser.saw_foo = 1
1316
1317parser.add_option("--foo", action="callback", callback=record_foo_seen)
1318\end{verbatim}
1319
1320Of course, you could do that with the ``store_true'' action. Here's a
1321slightly more interesting example: record the fact that
1322\programopt{-a} is seen, but blow up if it comes after \programopt{-b}
1323in the command-line.
1324
1325\begin{verbatim}
1326def check_order (option, opt, value, parser):
1327 if parser.values.b:
1328 raise OptionValueError("can't use -a after -b")
1329 parser.values.a = 1
Fred Drakecf6d74a2003-04-18 15:50:13 +00001330...
Neal Norwitz488609e2003-01-06 16:51:37 +00001331parser.add_option("-a", action="callback", callback=check_order)
1332parser.add_option("-b", action="store_true", dest="b")
1333\end{verbatim}
1334
1335If you want to reuse this callback for several similar options (set a
1336flag, but blow up if \programopt{-b} has already been seen), it needs
1337a bit of work: the error message and the flag that it sets must be
1338generalized.
1339
1340\begin{verbatim}
1341def check_order (option, opt, value, parser):
1342 if parser.values.b:
1343 raise OptionValueError("can't use %s after -b" % opt)
1344 setattr(parser.values, option.dest, 1)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001345...
Neal Norwitz488609e2003-01-06 16:51:37 +00001346parser.add_option("-a", action="callback", callback=check_order, dest='a')
1347parser.add_option("-b", action="store_true", dest="b")
1348parser.add_option("-c", action="callback", callback=check_order, dest='c')
1349\end{verbatim}
1350
Fred Drakecf6d74a2003-04-18 15:50:13 +00001351Of course, you could put any condition in there --- you're not limited
Neal Norwitz488609e2003-01-06 16:51:37 +00001352to checking the values of already-defined options. For example, if
1353you have options that should not be called when the moon is full, all
1354you have to do is this:
1355
1356\begin{verbatim}
1357def check_moon (option, opt, value, parser):
1358 if is_full_moon():
1359 raise OptionValueError("%s option invalid when moon full" % opt)
1360 setattr(parser.values, option.dest, 1)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001361...
Neal Norwitz488609e2003-01-06 16:51:37 +00001362parser.add_option("--foo",
1363 action="callback", callback=check_moon, dest="foo")
1364\end{verbatim}
1365
1366(The definition of is_full_moon() is left as an exercise for the
1367reader.)
1368
1369\strong{Fixed arguments}
1370
1371Things get slightly more interesting when you define callback options
1372that take a fixed number of arguments. Specifying that a callback
1373option takes arguments is similar to defining a ``store'' or
1374``append'' option: if you define \var{type}, then the option takes one
1375argument that must be convertible to that type; if you further define
1376\var{nargs}, then the option takes that many arguments.
1377
1378Here's an example that just emulates the standard ``store'' action:
1379
1380\begin{verbatim}
1381def store_value (option, opt, value, parser):
1382 setattr(parser.values, option.dest, value)
Fred Drakecf6d74a2003-04-18 15:50:13 +00001383...
Neal Norwitz488609e2003-01-06 16:51:37 +00001384parser.add_option("--foo",
1385 action="callback", callback=store_value,
1386 type="int", nargs=3, dest="foo")
1387\end{verbatim}
1388
1389Note that \module{optparse} takes care of consuming 3 arguments and
1390converting them to integers for you; all you have to do is store them.
1391(Or whatever: obviously you don't need a callback for this example.
1392Use your imagination!)
1393
1394\strong{Variable arguments}
1395
1396Things get hairy when you want an option to take a variable number of
1397arguments. For this case, you have to write a callback;
1398\module{optparse} doesn't provide any built-in capabilities for it.
Fred Drakecf6d74a2003-04-18 15:50:13 +00001399You have to deal with the full-blown syntax for conventional \UNIX{}
Neal Norwitz488609e2003-01-06 16:51:37 +00001400command-line parsing. (Previously, \module{optparse} took care of
1401this for you, but I got it wrong. It was fixed at the cost of making
1402this kind of callback more complex.) In particular, callbacks have to
1403worry about bare \longprogramopt{} and \programopt{-} arguments; the
1404convention is:
1405
1406\begin{itemize}
1407\item bare \longprogramopt{}, if not the argument to some option,
1408causes command-line processing to halt and the \longprogramopt{}
1409itself is lost.
1410
1411\item bare \programopt{-} similarly causes command-line processing to
1412halt, but the \programopt{-} itself is kept.
1413
1414\item either \longprogramopt{} or \programopt{-} can be option
1415arguments.
1416\end{itemize}
1417
1418If you want an option that takes a variable number of arguments, there
1419are several subtle, tricky issues to worry about. The exact
1420implementation you choose will be based on which trade-offs you're
1421willing to make for your application (which is why \module{optparse}
1422doesn't support this sort of thing directly).
1423
1424Nevertheless, here's a stab at a callback for an option with variable
1425arguments:
1426
1427\begin{verbatim}
1428def varargs (option, opt, value, parser):
1429 assert value is None
1430 done = 0
1431 value = []
1432 rargs = parser.rargs
1433 while rargs:
1434 arg = rargs[0]
1435
1436 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1437 # etc. Note that this also stops on "-3" or "-3.0", so if
1438 # your option takes numeric values, you will need to handle
1439 # this.
1440 if ((arg[:2] == "--" and len(arg) > 2) or
1441 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1442 break
1443 else:
1444 value.append(arg)
1445 del rargs[0]
1446
1447 setattr(parser.values, option.dest, value)
1448
Fred Drakecf6d74a2003-04-18 15:50:13 +00001449...
Neal Norwitz488609e2003-01-06 16:51:37 +00001450parser.add_option("-c", "--callback",
1451 action="callback", callback=varargs)
1452\end{verbatim}
1453
1454The main weakness with this particular implementation is that negative
1455numbers in the arguments following \programopt{-c} will be interpreted
1456as further options, rather than as arguments to \programopt{-c}.
1457Fixing this is left as an exercise for the reader.
1458
1459\subsection{Extending \module{optparse}\label{optparse-extending}}
1460
1461Since the two major controlling factors in how \module{optparse}
1462interprets command-line options are the action and type of each
1463option, the most likely direction of extension is to add new actions
1464and new types.
1465
1466Also, the examples section includes several demonstrations of
1467extending \module{optparse} in different ways: eg. a case-insensitive
1468option parser, or two kinds of option parsers that implement
1469``required options''.
1470
1471\subsubsection{Adding new types\label{optparse-adding-types}}
1472
1473To add new types, you need to define your own subclass of
1474\module{optparse}'s \class{Option} class. This class has a couple of
1475attributes that define \module{optparse}'s types: \member{TYPES} and
1476\member{TYPE_CHECKER}.
1477
1478\member{TYPES} is a tuple of type names; in your subclass, simply
1479define a new tuple \member{TYPES} that builds on the standard one.
1480
1481\member{TYPE_CHECKER} is a dictionary mapping type names to
1482type-checking functions. A type-checking function has the following
1483signature:
1484
1485\begin{verbatim}
1486def check_foo (option : Option, opt : string, value : string)
1487 -> foo
1488\end{verbatim}
1489
1490You can name it whatever you like, and make it return any type you
1491like. The value returned by a type-checking function will wind up in
1492the \class{OptionValues} instance returned by
1493\method{OptionParser.parse_args()}, or be passed to callbacks as the
1494\var{value} parameter.
1495
1496Your type-checking function should raise \exception{OptionValueError}
1497if it encounters any problems. \exception{OptionValueError} takes a
1498single string argument, which is passed as-is to
1499\class{OptionParser}'s \method{error()} method, which in turn prepends
1500the program name and the string ``error:'' and prints everything to
1501stderr before terminating the process.
1502
1503Here's a silly example that demonstrates adding a ``complex'' option
1504type to parse Python-style complex numbers on the command line. (This
1505is even sillier than it used to be, because \module{optparse} 1.3 adds
1506built-in support for complex numbers [purely for completeness], but
1507never mind.)
1508
1509First, the necessary imports:
1510
1511\begin{verbatim}
1512from copy import copy
1513from optparse import Option, OptionValueError
1514\end{verbatim}
1515
1516You need to define your type-checker first, since it's referred to
1517later (in the \member{TYPE_CHECKER} class attribute of your
1518\class{Option} subclass):
1519
1520\begin{verbatim}
1521def check_complex (option, opt, value):
1522 try:
1523 return complex(value)
1524 except ValueError:
1525 raise OptionValueError(
1526 "option %s: invalid complex value: %r" % (opt, value))
1527\end{verbatim}
1528
1529Finally, the \class{Option} subclass:
1530
1531\begin{verbatim}
1532class MyOption (Option):
1533 TYPES = Option.TYPES + ("complex",)
1534 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1535 TYPE_CHECKER["complex"] = check_complex
1536\end{verbatim}
1537
1538(If we didn't make a \function{copy()} of
1539\member{Option.TYPE_CHECKER}, we would end up modifying the
1540\member{TYPE_CHECKER} attribute of \module{optparse}'s Option class.
1541This being Python, nothing stops you from doing that except good
1542manners and common sense.)
1543
1544That's it! Now you can write a script that uses the new option type
1545just like any other \module{optparse}-based script, except you have to
1546instruct your \class{OptionParser} to use \class{MyOption} instead of
1547\class{Option}:
1548
1549\begin{verbatim}
1550parser = OptionParser(option_class=MyOption)
1551parser.add_option("-c", action="store", type="complex", dest="c")
1552\end{verbatim}
1553
1554Alternately, you can build your own option list and pass it to
1555\class{OptionParser}; if you don't use \method{add_option()} in the
1556above way, you don't need to tell \class{OptionParser} which option
1557class to use:
1558
1559\begin{verbatim}
1560option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1561parser = OptionParser(option_list=option_list)
1562\end{verbatim}
1563
1564\subsubsection{Adding new actions\label{optparse-adding-actions}}
1565
1566Adding new actions is a bit trickier, because you have to understand
1567that \module{optparse} has a couple of classifications for actions:
1568
1569\begin{definitions}
1570\term{"store" actions}
1571 actions that result in \module{optparse} storing a value to an attribute
1572 of the OptionValues instance; these options require a 'dest'
1573 attribute to be supplied to the Option constructor
1574\term{"typed" actions}
1575 actions that take a value from the command line and expect it to be
1576 of a certain type; or rather, a string that can be converted to a
1577 certain type. These options require a 'type' attribute to the
1578 Option constructor.
1579\end{definitions}
1580
1581Some default ``store'' actions are ``store'', ``store_const'',
1582``append'', and ``count''. The default ``typed'' actions are
1583``store'', ``append'', and ``callback''.
1584
1585When you add an action, you need to decide if it's a ``store'' action,
1586a ``typed'', neither, or both. Three class attributes of
1587\class{Option} (or your \class{Option} subclass) control this:
1588
1589\begin{memberdesc}{ACTIONS}
1590 All actions must be listed as strings in ACTIONS.
1591\end{memberdesc}
1592\begin{memberdesc}{STORE_ACTIONS}
1593 "store" actions are additionally listed here.
1594\end{memberdesc}
1595\begin{memberdesc}{TYPED_ACTIONS}
1596 "typed" actions are additionally listed here.
1597\end{memberdesc}
1598
1599In order to actually implement your new action, you must override
1600\class{Option}'s \method{take_action()} method and add a case that
1601recognizes your action.
1602
1603For example, let's add an ``extend'' action. This is similar to the
1604standard ``append'' action, but instead of taking a single value from
1605the command-line and appending it to an existing list, ``extend'' will
1606take multiple values in a single comma-delimited string, and extend an
1607existing list with them. That is, if \longprogramopt{names} is an
1608``extend'' option of type string, the command line:
1609
1610\begin{verbatim}
1611--names=foo,bar --names blah --names ding,dong
1612\end{verbatim}
1613
1614would result in a list:
1615
1616\begin{verbatim}
1617["foo", "bar", "blah", "ding", "dong"]
1618\end{verbatim}
1619
1620Again we define a subclass of \class{Option}:
1621
1622\begin{verbatim}
1623class MyOption (Option):
1624
1625 ACTIONS = Option.ACTIONS + ("extend",)
1626 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1627 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1628
1629 def take_action (self, action, dest, opt, value, values, parser):
1630 if action == "extend":
1631 lvalue = value.split(",")
1632 values.ensure_value(dest, []).extend(lvalue)
1633 else:
1634 Option.take_action(
1635 self, action, dest, opt, value, values, parser)
1636\end{verbatim}
1637
1638Features of note:
1639
1640\begin{itemize}
1641\item ``extend'' both expects a value on the command-line and stores that
1642value somewhere, so it goes in both \member{STORE_ACTIONS} and
1643\member{TYPED_ACTIONS}.
1644
1645\item \method{MyOption.take_action()} implements just this one new
1646action, and passes control back to \method{Option.take_action()} for
1647the standard \module{optparse} actions.
1648
1649\item \var{values} is an instance of the \class{Values} class, which
1650provides the very useful \method{ensure_value()}
1651method. \method{ensure_value()} is essentially \function{getattr()}
1652with a safety valve; it is called as:
1653
1654\begin{verbatim}
1655values.ensure_value(attr, value)
1656\end{verbatim}
1657\end{itemize}
1658
1659If the \member{attr} attribute of \var{values} doesn't exist or is
1660None, then \method{ensure_value()} first sets it to \var{value}, and
1661then returns \var{value}. This is very handy for actions like
1662``extend'', ``append'', and ``count'', all of which accumulate data in
1663a variable and expect that variable to be of a certain type (a list
1664for the first two, an integer for the latter). Using
1665\method{ensure_value()} means that scripts using your action don't
1666have to worry about setting a default value for the option
1667destinations in question; they can just leave the default as None and
1668\method{ensure_value()} will take care of getting it right when it's
1669needed.
1670
1671\subsubsection{Other reasons to extend \module{optparse}\label{optparse-extending-other-reasons}}
1672
1673Adding new types and new actions are the big, obvious reasons why you
1674might want to extend \module{optparse}. I can think of at least two
1675other areas to play with.
1676
1677First, the simple one: \class{OptionParser} tries to be helpful by
1678calling \function{sys.exit()} when appropriate, ie. when there's an
1679error on the command-line or when the user requests help. In the
1680former case, the traditional course of letting the script crash with a
1681traceback is unacceptable; it will make users think there's a bug in
1682your script when they make a command-line error. In the latter case,
1683there's generally not much point in carrying on after printing a help
1684message.
1685
1686If this behaviour bothers you, it shouldn't be too hard to ``fix'' it.
1687You'll have to
1688
1689\begin{enumerate}
1690\item subclass OptionParser and override the error() method
Fred Drakecf6d74a2003-04-18 15:50:13 +00001691\item subclass Option and override the take_action() method --- you'll
Neal Norwitz488609e2003-01-06 16:51:37 +00001692 need to provide your own handling of the "help" action that
1693 doesn't call sys.exit()
1694\end{enumerate}
1695
1696The second, much more complex, possibility is to override the
1697command-line syntax implemented by \module{optparse}. In this case,
1698you'd leave the whole machinery of option actions and types alone, but
1699rewrite the code that processes \var{sys.argv}. You'll need to
1700subclass \class{OptionParser} in any case; depending on how radical a
1701rewrite you want, you'll probably need to override one or all of
1702\method{parse_args()}, \method{_process_long_opt()}, and
1703\method{_process_short_opts()}.
1704
1705Both of these are left as an exercise for the reader. I have not
1706tried to implement either myself, since I'm quite happy with
1707\module{optparse}'s default behaviour (naturally).
1708
1709Happy hacking, and don't forget: Use the Source, Luke.
1710
1711\subsubsection{Examples\label{optparse-extending-examples}}
1712
1713Here are a few examples of extending the \module{optparse} module.
1714
1715First, let's change the option-parsing to be case-insensitive:
1716
1717\verbatiminput{caseless.py}
1718
1719And two ways of implementing ``required options'' with
1720\module{optparse}.
1721
1722Version 1: Add a method to \class{OptionParser} which applications
1723must call after parsing arguments:
1724
1725\verbatiminput{required_1.py}
1726
1727Version 2: Extend \class{Option} and add a \member{required}
1728attribute; extend \class{OptionParser} to ensure that required options
1729are present after parsing:
1730
Fred Drakecf6d74a2003-04-18 15:50:13 +00001731\verbatiminput{required_2.py}