blob: bc3186f2c0d087cf7ab23cc5fdf0f90bcd411355 [file] [log] [blame]
Greg Wardb6f7fb72004-09-28 01:30:23 +00001\section{\module{optparse} --- More powerful command line option parser}
Neal Norwitz488609e2003-01-06 16:51:37 +00002\declaremodule{standard}{optparse}
3\moduleauthor{Greg Ward}{gward@python.net}
Greg Wardb6f7fb72004-09-28 01:30:23 +00004\modulesynopsis{More convenient, flexible, and powerful command-line parsing library.}
Neal Norwitz488609e2003-01-06 16:51:37 +00005\versionadded{2.3}
Greg Wardb6f7fb72004-09-28 01:30:23 +00006\sectionauthor{Greg Ward}{gward@python.net}
7% An intro blurb used only when generating LaTeX docs for the Python
8% manual (based on README.txt).
Neal Norwitz488609e2003-01-06 16:51:37 +00009
Greg Wardb6f7fb72004-09-28 01:30:23 +000010\code{optparse} is a more convenient, flexible, and powerful library for
11parsing command-line options than \code{getopt}. \code{optparse} uses a more
12declarative style of command-line parsing: you create an instance of
13\class{OptionParser}, populate it with options, and parse the command line.
14\code{optparse} allows users to specify options in the conventional GNU/POSIX
15syntax, and additionally generates usage and help messages for you.
Neal Norwitz488609e2003-01-06 16:51:37 +000016
Greg Wardb6f7fb72004-09-28 01:30:23 +000017Here's an example of using \code{optparse} in a simple script:
Neal Norwitz488609e2003-01-06 16:51:37 +000018\begin{verbatim}
19from optparse import OptionParser
Greg Wardb6f7fb72004-09-28 01:30:23 +000020[...]
Neal Norwitz488609e2003-01-06 16:51:37 +000021parser = OptionParser()
22parser.add_option("-f", "--file", dest="filename",
23 help="write report to FILE", metavar="FILE")
24parser.add_option("-q", "--quiet",
Greg Ward1f535172003-05-03 20:13:08 +000025 action="store_false", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +000026 help="don't print status messages to stdout")
27
Greg Wardb6f7fb72004-09-28 01:30:23 +000028(options, args) = parser.parse_args()
Neal Norwitz488609e2003-01-06 16:51:37 +000029\end{verbatim}
30
31With these few lines of code, users of your script can now do the
Greg Wardb6f7fb72004-09-28 01:30:23 +000032``usual thing'' on the command-line, for example:
Neal Norwitz488609e2003-01-06 16:51:37 +000033\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +000034<yourscript> --file=outfile -q
Neal Norwitz488609e2003-01-06 16:51:37 +000035\end{verbatim}
36
Greg Wardb6f7fb72004-09-28 01:30:23 +000037As it parses the command line, \code{optparse} sets attributes of the
38\var{options} object returned by \method{parse{\_}args()} based on user-supplied
39command-line values. When \method{parse{\_}args()} returns from parsing this
40command line, \var{options.filename} will be \code{"outfile"} and
41\code{options.verbose} will be \code{False}. \code{optparse} supports both long
42and short options, allows short options to be merged together, and
43allows options to be associated with their arguments in a variety of
44ways. Thus, the following command lines are all equivalent to the above
45example:
Neal Norwitz488609e2003-01-06 16:51:37 +000046\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +000047<yourscript> -f outfile --quiet
48<yourscript> --quiet --file outfile
49<yourscript> -q -foutfile
50<yourscript> -qfoutfile
Neal Norwitz488609e2003-01-06 16:51:37 +000051\end{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +000052
53Additionally, users can run one of
54\begin{verbatim}
55<yourscript> -h
56<yourscript> --help
57\end{verbatim}
58
59and \code{optparse} will print out a brief summary of your script's
Neal Norwitz488609e2003-01-06 16:51:37 +000060options:
Neal Norwitz488609e2003-01-06 16:51:37 +000061\begin{verbatim}
62usage: <yourscript> [options]
63
64options:
Greg Wardb6f7fb72004-09-28 01:30:23 +000065 -h, --help show this help message and exit
66 -f FILE, --file=FILE write report to FILE
67 -q, --quiet don't print status messages to stdout
Neal Norwitz488609e2003-01-06 16:51:37 +000068\end{verbatim}
69
Greg Wardb6f7fb72004-09-28 01:30:23 +000070where the value of \emph{yourscript} is determined at runtime (normally
71from \code{sys.argv{[}0]}).
72% $Id$
Neal Norwitz488609e2003-01-06 16:51:37 +000073
Neal Norwitz488609e2003-01-06 16:51:37 +000074
Greg Wardb6f7fb72004-09-28 01:30:23 +000075\subsection{Background\label{optparse-background}}
76
77\module{optparse} was explicitly designed to encourage the creation of programs with
78straightforward, conventional command-line interfaces. To that end, it
79supports only the most common command-line syntax and semantics
80conventionally used under \UNIX{}. If you are unfamiliar with these
81conventions, read this section to acquaint yourself with them.
82
Neal Norwitz488609e2003-01-06 16:51:37 +000083
84\subsubsection{Terminology\label{optparse-terminology}}
Greg Wardb6f7fb72004-09-28 01:30:23 +000085\begin{description}
86\item[argument]
87a string entered on the command-line, and passed by the shell to
88\code{execl()} or \code{execv()}. In Python, arguments are elements of
89\code{sys.argv{[}1:]} (\code{sys.argv{[}0]} is the name of the program being
90executed). \UNIX{} shells also use the term ``word''.
Neal Norwitz488609e2003-01-06 16:51:37 +000091
Greg Wardb6f7fb72004-09-28 01:30:23 +000092It is occasionally desirable to substitute an argument list other
93than \code{sys.argv{[}1:]}, so you should read ``argument'' as ``an element of
94\code{sys.argv{[}1:]}, or of some other list provided as a substitute for
95\code{sys.argv{[}1:]}''.
96\item[option ]
97an argument used to supply extra information to guide or customize the
98execution of a program. There are many different syntaxes for
99options; the traditional \UNIX{} syntax is a hyphen (``-'') followed by a
100single letter, e.g. \code{"-x"} or \code{"-F"}. Also, traditional \UNIX{}
101syntax allows multiple options to be merged into a single argument,
102e.g. \code{"-x -F"} is equivalent to \code{"-xF"}. The GNU project
103introduced \code{"-{}-"} followed by a series of hyphen-separated words,
104e.g. \code{"-{}-file"} or \code{"-{}-dry-run"}. These are the only two option
105syntaxes provided by \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000106
Greg Wardb6f7fb72004-09-28 01:30:23 +0000107Some other option syntaxes that the world has seen include:
Neal Norwitz488609e2003-01-06 16:51:37 +0000108\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000109\item {}
110a hyphen followed by a few letters, e.g. \code{"-pf"} (this is
111\emph{not} the same as multiple options merged into a single argument)
112
113\item {}
114a hyphen followed by a whole word, e.g. \code{"-file"} (this is
115technically equivalent to the previous syntax, but they aren't
116usually seen in the same program)
117
118\item {}
119a plus sign followed by a single letter, or a few letters,
120or a word, e.g. \code{"+f"}, \code{"+rgb"}
121
122\item {}
123a slash followed by a letter, or a few letters, or a word, e.g.
124\code{"/f"}, \code{"/file"}
125
Neal Norwitz488609e2003-01-06 16:51:37 +0000126\end{itemize}
127
Greg Wardb6f7fb72004-09-28 01:30:23 +0000128These option syntaxes are not supported by \module{optparse}, and they never will
129be. This is deliberate: the first three are non-standard on any
130environment, and the last only makes sense if you're exclusively
131targeting VMS, MS-DOS, and/or Windows.
132\item[option argument]
Neal Norwitz488609e2003-01-06 16:51:37 +0000133an argument that follows an option, is closely associated with that
Greg Wardb6f7fb72004-09-28 01:30:23 +0000134option, and is consumed from the argument list when that option is.
135With \module{optparse}, option arguments may either be in a separate argument
136from their option:
Neal Norwitz488609e2003-01-06 16:51:37 +0000137\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000138-f foo
139--file foo
Neal Norwitz488609e2003-01-06 16:51:37 +0000140\end{verbatim}
141
Greg Wardb6f7fb72004-09-28 01:30:23 +0000142or included in the same argument:
Neal Norwitz488609e2003-01-06 16:51:37 +0000143\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000144-ffoo
145--file=foo
Neal Norwitz488609e2003-01-06 16:51:37 +0000146\end{verbatim}
147
Greg Wardb6f7fb72004-09-28 01:30:23 +0000148Typically, a given option either takes an argument or it doesn't.
149Lots of people want an ``optional option arguments'' feature, meaning
150that some options will take an argument if they see it, and won't if
151they don't. This is somewhat controversial, because it makes parsing
152ambiguous: if \code{"-a"} takes an optional argument and \code{"-b"} is
153another option entirely, how do we interpret \code{"-ab"}? Because of
154this ambiguity, \module{optparse} does not support this feature.
155\item[positional argument]
Neal Norwitz488609e2003-01-06 16:51:37 +0000156something leftover in the argument list after options have been
Greg Wardb6f7fb72004-09-28 01:30:23 +0000157parsed, i.e. after options and their arguments have been parsed and
Neal Norwitz488609e2003-01-06 16:51:37 +0000158removed from the argument list.
Greg Wardb6f7fb72004-09-28 01:30:23 +0000159\item[required option]
160an option that must be supplied on the command-line; note that the
161phrase ``required option'' is self-contradictory in English. \module{optparse}
162doesn't prevent you from implementing required options, but doesn't
163give you much help at it either. See \code{examples/required{\_}1.py} and
164\code{examples/required{\_}2.py} in the \module{optparse} source distribution for two
165ways to implement required options with \module{optparse}.
166\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +0000167
168For example, consider this hypothetical command-line:
Neal Norwitz488609e2003-01-06 16:51:37 +0000169\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000170prog -v --report /tmp/report.txt foo bar
Neal Norwitz488609e2003-01-06 16:51:37 +0000171\end{verbatim}
172
Greg Wardb6f7fb72004-09-28 01:30:23 +0000173\code{"-v"} and \code{"-{}-report"} are both options. Assuming that
174\longprogramopt{report} takes one argument, \code{"/tmp/report.txt"} is an option
175argument. \code{"foo"} and \code{"bar"} are positional arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +0000176
Greg Wardb6f7fb72004-09-28 01:30:23 +0000177
178\subsubsection{What are options for?\label{optparse-what-are-options-for?}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000179
180Options are used to provide extra information to tune or customize the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000181execution of a program. In case it wasn't clear, options are usually
182\emph{optional}. A program should be able to run just fine with no options
183whatsoever. (Pick a random program from the \UNIX{} or GNU toolsets. Can
184it run without any options at all and still make sense? The main
185exceptions are \code{find}, \code{tar}, and \code{dd}{---}all of which are mutant
186oddballs that have been rightly criticized for their non-standard syntax
187and confusing interfaces.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000188
Greg Wardb6f7fb72004-09-28 01:30:23 +0000189Lots of people want their programs to have ``required options''. Think
190about it. If it's required, then it's \emph{not optional}! If there is a
191piece of information that your program absolutely requires in order to
192run successfully, that's what positional arguments are for.
Neal Norwitz488609e2003-01-06 16:51:37 +0000193
Greg Wardb6f7fb72004-09-28 01:30:23 +0000194As an example of good command-line interface design, consider the humble
195\code{cp} utility, for copying files. It doesn't make much sense to try to
196copy files without supplying a destination and at least one source.
197Hence, \code{cp} fails if you run it with no arguments. However, it has a
198flexible, useful syntax that does not require any options at all:
Neal Norwitz488609e2003-01-06 16:51:37 +0000199\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000200cp SOURCE DEST
201cp SOURCE ... DEST-DIR
Neal Norwitz488609e2003-01-06 16:51:37 +0000202\end{verbatim}
203
Greg Wardb6f7fb72004-09-28 01:30:23 +0000204You can get pretty far with just that. Most \code{cp} implementations
205provide a bunch of options to tweak exactly how the files are copied:
206you can preserve mode and modification time, avoid following symlinks,
207ask before clobbering existing files, etc. But none of this distracts
208from the core mission of \code{cp}, which is to copy either one file to
209another, or several files to another directory.
Neal Norwitz488609e2003-01-06 16:51:37 +0000210
Neal Norwitz488609e2003-01-06 16:51:37 +0000211
Greg Wardb6f7fb72004-09-28 01:30:23 +0000212\subsubsection{What are positional arguments for?\label{optparse-what-are-positional-arguments-for?}}
213
214Positional arguments are for those pieces of information that your
215program absolutely, positively requires to run.
Neal Norwitz488609e2003-01-06 16:51:37 +0000216
217A good user interface should have as few absolute requirements as
218possible. If your program requires 17 distinct pieces of information in
219order to run successfully, it doesn't much matter \emph{how} you get that
Greg Wardb6f7fb72004-09-28 01:30:23 +0000220information from the user{---}most people will give up and walk away
Neal Norwitz488609e2003-01-06 16:51:37 +0000221before they successfully run the program. This applies whether the user
Greg Wardb6f7fb72004-09-28 01:30:23 +0000222interface is a command-line, a configuration file, or a GUI: if you make
223that many demands on your users, most of them will simply give up.
Neal Norwitz488609e2003-01-06 16:51:37 +0000224
225In short, try to minimize the amount of information that users are
Greg Wardb6f7fb72004-09-28 01:30:23 +0000226absolutely required to supply{---}use sensible defaults whenever
Neal Norwitz488609e2003-01-06 16:51:37 +0000227possible. Of course, you also want to make your programs reasonably
228flexible. That's what options are for. Again, it doesn't matter if
Greg Wardb6f7fb72004-09-28 01:30:23 +0000229they are entries in a config file, widgets in the ``Preferences'' dialog
230of a GUI, or command-line options{---}the more options you implement, the
231more flexible your program is, and the more complicated its
232implementation becomes. Too much flexibility has drawbacks as well, of
233course; too many options can overwhelm users and make your code much
234harder to maintain.
235% $Id$
Neal Norwitz488609e2003-01-06 16:51:37 +0000236
Neal Norwitz488609e2003-01-06 16:51:37 +0000237
Greg Wardb6f7fb72004-09-28 01:30:23 +0000238\subsection{Tutorial\label{optparse-tutorial}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000239
Greg Wardb6f7fb72004-09-28 01:30:23 +0000240While \module{optparse} is quite flexible and powerful, it's also straightforward to
241use in most cases. This section covers the code patterns that are
242common to any \module{optparse}-based program.
Neal Norwitz488609e2003-01-06 16:51:37 +0000243
Greg Wardb6f7fb72004-09-28 01:30:23 +0000244First, you need to import the OptionParser class; then, early in the
245main program, create an OptionParser instance:
Neal Norwitz488609e2003-01-06 16:51:37 +0000246\begin{verbatim}
247from optparse import OptionParser
Greg Wardb6f7fb72004-09-28 01:30:23 +0000248[...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000249parser = OptionParser()
250\end{verbatim}
251
Greg Wardb6f7fb72004-09-28 01:30:23 +0000252Then you can start defining options. The basic syntax is:
253\begin{verbatim}
254parser.add_option(opt_str, ...,
255 attr=value, ...)
256\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000257
Greg Wardb6f7fb72004-09-28 01:30:23 +0000258Each option has one or more option strings, such as \code{"-f"} or
259\code{"-{}-file"}, and several option attributes that tell \module{optparse} what to
260expect and what to do when it encounters that option on the command
261line.
262
263Typically, each option will have one short option string and one long
264option string, e.g.:
Neal Norwitz488609e2003-01-06 16:51:37 +0000265\begin{verbatim}
266parser.add_option("-f", "--file", ...)
267\end{verbatim}
268
Greg Wardb6f7fb72004-09-28 01:30:23 +0000269You're free to define as many short option strings and as many long
270option strings as you like (including zero), as long as there is at
271least one option string overall.
Neal Norwitz488609e2003-01-06 16:51:37 +0000272
Greg Wardb6f7fb72004-09-28 01:30:23 +0000273The option strings passed to \method{add{\_}option()} are effectively labels for
274the option defined by that call. For brevity, we will frequently refer
275to \emph{encountering an option} on the command line; in reality, \module{optparse}
276encounters \emph{option strings} and looks up options from them.
Neal Norwitz488609e2003-01-06 16:51:37 +0000277
Greg Wardb6f7fb72004-09-28 01:30:23 +0000278Once all of your options are defined, instruct \module{optparse} to parse your
279program's command line:
280\begin{verbatim}
281(options, args) = parser.parse_args()
282\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000283
Greg Wardb6f7fb72004-09-28 01:30:23 +0000284(If you like, you can pass a custom argument list to \method{parse{\_}args()},
285but that's rarely necessary: by default it uses \code{sys.argv{[}1:]}.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000286
Greg Wardb6f7fb72004-09-28 01:30:23 +0000287\method{parse{\_}args()} returns two values:
288\begin{itemize}
289\item {}
290\var{options}, an object containing values for all of your options{---}e.g. if \code{"-{}-file"} takes a single string argument, then
291\var{options.file} will be the filename supplied by the user, or
292\code{None} if the user did not supply that option
293
294\item {}
295\var{args}, the list of positional arguments leftover after parsing
296options
297
298\end{itemize}
299
300This tutorial section only covers the four most important option
301attributes: \member{action}, \member{type}, \member{dest} (destination), and \member{help}.
302Of these, \member{action} is the most fundamental.
303
304
305\subsubsection{Option actions\label{optparse-option-actions}}
306
307Actions tell \module{optparse} what to do when it encounters an option on the
308command line. There is a fixed set of actions hard-coded into \module{optparse};
309adding new actions is an advanced topic covered in section~\ref{optparse-extending}, Extending \module{optparse}.
310Most actions tell \module{optparse} to store a value in some variable{---}for
311example, take a string from the command line and store it in an
312attribute of \var{options}.
313
314If you don't specify an option action, \module{optparse} defaults to \code{store}.
315
316
317\subsubsection{The store action\label{optparse-the-store-action}}
318
319The most common option action is \code{store}, which tells \module{optparse} to take
320the next argument (or the remainder of the current argument), ensure
321that it is of the correct type, and store it to your chosen destination.
322
323For example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000324\begin{verbatim}
325parser.add_option("-f", "--file",
326 action="store", type="string", dest="filename")
327\end{verbatim}
328
Greg Wardb6f7fb72004-09-28 01:30:23 +0000329Now let's make up a fake command line and ask \module{optparse} to parse it:
Neal Norwitz488609e2003-01-06 16:51:37 +0000330\begin{verbatim}
331args = ["-f", "foo.txt"]
Greg Wardb6f7fb72004-09-28 01:30:23 +0000332(options, args) = parser.parse_args(args)
Neal Norwitz488609e2003-01-06 16:51:37 +0000333\end{verbatim}
334
Greg Wardb6f7fb72004-09-28 01:30:23 +0000335When \module{optparse} sees the option string \code{"-f"}, it consumes the next
336argument, \code{"foo.txt"}, and stores it in \var{options.filename}. So,
337after this call to \method{parse{\_}args()}, \var{options.filename} is
338\code{"foo.txt"}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000339
Greg Wardb6f7fb72004-09-28 01:30:23 +0000340Some other option types supported by \module{optparse} are \code{int} and \code{float}.
341Here's an option that expects an integer argument:
Neal Norwitz488609e2003-01-06 16:51:37 +0000342\begin{verbatim}
343parser.add_option("-n", type="int", dest="num")
344\end{verbatim}
345
Greg Wardb6f7fb72004-09-28 01:30:23 +0000346Note that this option has no long option string, which is perfectly
347acceptable. Also, there's no explicit action, since the default is
348\code{store}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000349
Greg Wardb6f7fb72004-09-28 01:30:23 +0000350Let's parse another fake command-line. This time, we'll jam the option
351argument right up against the option: since \code{"-n42"} (one argument) is
352equivalent to \code{"-n 42"} (two arguments), the code
Neal Norwitz488609e2003-01-06 16:51:37 +0000353\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000354(options, args) = parser.parse_args(["-n42"])
Neal Norwitz488609e2003-01-06 16:51:37 +0000355print options.num
356\end{verbatim}
357
Greg Wardb6f7fb72004-09-28 01:30:23 +0000358will print \code{"42"}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000359
Greg Wardb6f7fb72004-09-28 01:30:23 +0000360If you don't specify a type, \module{optparse} assumes \code{string}. Combined with the
361fact that the default action is \code{store}, that means our first example
362can be a lot shorter:
Neal Norwitz488609e2003-01-06 16:51:37 +0000363\begin{verbatim}
364parser.add_option("-f", "--file", dest="filename")
365\end{verbatim}
366
Greg Wardb6f7fb72004-09-28 01:30:23 +0000367If you don't supply a destination, \module{optparse} figures out a sensible default
368from the option strings: if the first long option string is
369\code{"-{}-foo-bar"}, then the default destination is \code{foo{\_}bar}. If there
370are no long option strings, \module{optparse} looks at the first short option
371string: the default destination for \code{"-f"} is \code{f}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000372
Greg Wardb6f7fb72004-09-28 01:30:23 +0000373\module{optparse} also includes built-in \code{long} and \code{complex} types. Adding
374types is covered in section~\ref{optparse-extending}, Extending \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000375
Neal Norwitz488609e2003-01-06 16:51:37 +0000376
Greg Wardb6f7fb72004-09-28 01:30:23 +0000377\subsubsection{Handling flag (boolean) options\label{optparse-handling-flag-(boolean)-options}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000378
Greg Wardb6f7fb72004-09-28 01:30:23 +0000379Flag options{---}set a variable to true or false when a particular option
380is seen{---}are quite common. \module{optparse} supports them with two separate
381actions, \code{store{\_}true} and \code{store{\_}false}. For example, you might have a
382\var{verbose} flag that is turned on with \code{"-v"} and off with \code{"-q"}:
Neal Norwitz488609e2003-01-06 16:51:37 +0000383\begin{verbatim}
384parser.add_option("-v", action="store_true", dest="verbose")
385parser.add_option("-q", action="store_false", dest="verbose")
386\end{verbatim}
387
388Here we have two different options with the same destination, which is
389perfectly OK. (It just means you have to be a bit careful when setting
Greg Wardb6f7fb72004-09-28 01:30:23 +0000390default values{---}see section~\ref{optparse-default-values}, Default values, below.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000391
Greg Wardb6f7fb72004-09-28 01:30:23 +0000392When \module{optparse} encounters \code{"-v"} on the command line, it sets
393\code{options.verbose} to \code{True}; when it encounters \code{"-q"},
394\code{options.verbose} is set to \code{False}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000395
Greg Wardb6f7fb72004-09-28 01:30:23 +0000396
397\subsubsection{Other actions\label{optparse-other-actions}}
398
399Some other actions supported by \module{optparse} are:
400\begin{description}
401\item[\code{store{\_}const}]
402store a constant value
403\item[\code{append}]
404append this option's argument to a list
405\item[\code{count}]
406increment a counter by one
407\item[\code{callback}]
408call a specified function
409\end{description}
410
411These are covered in the section~\ref{None}, Reference Guide and section~\ref{None}, Option Callbacks
412documents.
413
414
415\subsubsection{Default values\label{optparse-default-values}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000416
417All of the above examples involve setting some variable (the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000418``destination'') when certain command-line options are seen. What happens
419if those options are never seen? Since we didn't supply any defaults,
420they are all set to \code{None}. This is usually fine, but sometimes you
421want more control. \module{optparse} lets you supply a default value for each
422destination, which is assigned before the command line is parsed.
Neal Norwitz488609e2003-01-06 16:51:37 +0000423
Greg Wardb6f7fb72004-09-28 01:30:23 +0000424First, consider the verbose/quiet example. If we want \module{optparse} to set
425\var{verbose} to \code{True} unless \code{"-q"} is seen, then we can do this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000426\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000427parser.add_option("-v", action="store_true", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000428parser.add_option("-q", action="store_false", dest="verbose")
429\end{verbatim}
430
Greg Wardb6f7fb72004-09-28 01:30:23 +0000431Since default values apply to the \emph{destination} rather than to any
432particular option, and these two options happen to have the same
433destination, this is exactly equivalent:
Neal Norwitz488609e2003-01-06 16:51:37 +0000434\begin{verbatim}
435parser.add_option("-v", action="store_true", dest="verbose")
Greg Ward1f535172003-05-03 20:13:08 +0000436parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000437\end{verbatim}
438
Neal Norwitz488609e2003-01-06 16:51:37 +0000439Consider this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000440\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000441parser.add_option("-v", action="store_true", dest="verbose", default=False)
442parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000443\end{verbatim}
444
Greg Wardb6f7fb72004-09-28 01:30:23 +0000445Again, the default value for \var{verbose} will be \code{True}: the last
Greg Wardd7231282003-05-03 21:22:58 +0000446default value supplied for any particular destination is the one that
447counts.
Neal Norwitz488609e2003-01-06 16:51:37 +0000448
Greg Wardb6f7fb72004-09-28 01:30:23 +0000449A clearer way to specify default values is the \method{set{\_}defaults()}
450method of OptionParser, which you can call at any time before calling
451\method{parse{\_}args()}:
452\begin{verbatim}
453parser.set_defaults(verbose=True)
454parser.add_option(...)
455(options, args) = parser.parse_args()
456\end{verbatim}
457
458As before, the last value specified for a given option destination is
459the one that counts. For clarity, try to use one method or the other of
460setting default values, not both.
461
462
Neal Norwitz488609e2003-01-06 16:51:37 +0000463\subsubsection{Generating help\label{optparse-generating-help}}
464
Greg Wardb6f7fb72004-09-28 01:30:23 +0000465\module{optparse}'s ability to generate help and usage text automatically is useful
466for creating user-friendly command-line interfaces. All you have to do
467is supply a \member{help} value for each option, and optionally a short usage
468message for your whole program. Here's an OptionParser populated with
469user-friendly (documented) options:
Neal Norwitz488609e2003-01-06 16:51:37 +0000470\begin{verbatim}
471usage = "usage: %prog [options] arg1 arg2"
472parser = OptionParser(usage=usage)
473parser.add_option("-v", "--verbose",
Greg Ward1f535172003-05-03 20:13:08 +0000474 action="store_true", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +0000475 help="make lots of noise [default]")
476parser.add_option("-q", "--quiet",
477 action="store_false", dest="verbose",
478 help="be vewwy quiet (I'm hunting wabbits)")
Greg Wardb6f7fb72004-09-28 01:30:23 +0000479parser.add_option("-f", "--filename",
Neal Norwitz488609e2003-01-06 16:51:37 +0000480 metavar="FILE", help="write output to FILE"),
481parser.add_option("-m", "--mode",
482 default="intermediate",
Greg Wardb6f7fb72004-09-28 01:30:23 +0000483 help="interaction mode: novice, intermediate, "
484 "or expert [default: %default]")
Neal Norwitz488609e2003-01-06 16:51:37 +0000485\end{verbatim}
486
Greg Wardb6f7fb72004-09-28 01:30:23 +0000487If \module{optparse} encounters either \code{"-h"} or \code{"-{}-help"} on the command-line,
488or if you just call \method{parser.print{\_}help()}, it prints the following to
489standard output:
Neal Norwitz488609e2003-01-06 16:51:37 +0000490\begin{verbatim}
491usage: <yourscript> [options] arg1 arg2
492
493options:
Greg Wardb6f7fb72004-09-28 01:30:23 +0000494 -h, --help show this help message and exit
495 -v, --verbose make lots of noise [default]
496 -q, --quiet be vewwy quiet (I'm hunting wabbits)
497 -f FILE, --filename=FILE
498 write output to FILE
499 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
500 expert [default: intermediate]
Neal Norwitz488609e2003-01-06 16:51:37 +0000501\end{verbatim}
502
Greg Wardb6f7fb72004-09-28 01:30:23 +0000503(If the help output is triggered by a help option, \module{optparse} exits after
504printing the help text.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000505
Greg Wardb6f7fb72004-09-28 01:30:23 +0000506There's a lot going on here to help \module{optparse} generate the best possible
507help message:
Neal Norwitz488609e2003-01-06 16:51:37 +0000508\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000509\item {}
510the script defines its own usage message:
Neal Norwitz488609e2003-01-06 16:51:37 +0000511\begin{verbatim}
512usage = "usage: %prog [options] arg1 arg2"
513\end{verbatim}
514
Greg Wardb6f7fb72004-09-28 01:30:23 +0000515\module{optparse} expands \code{"{\%}prog"} in the usage string to the name of the current
516program, i.e. \code{os.path.basename(sys.argv{[}0])}. The expanded string
517is then printed before the detailed option help.
Neal Norwitz488609e2003-01-06 16:51:37 +0000518
Greg Wardb6f7fb72004-09-28 01:30:23 +0000519If you don't supply a usage string, \module{optparse} uses a bland but sensible
520default: ``\code{usage: {\%}prog {[}options]"}, which is fine if your script
521doesn't take any positional arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +0000522
Greg Wardb6f7fb72004-09-28 01:30:23 +0000523\item {}
524every option defines a help string, and doesn't worry about line-
525wrapping{---}\module{optparse} takes care of wrapping lines and making the
526help output look good.
Neal Norwitz488609e2003-01-06 16:51:37 +0000527
Greg Wardb6f7fb72004-09-28 01:30:23 +0000528\item {}
529options that take a value indicate this fact in their
Neal Norwitz488609e2003-01-06 16:51:37 +0000530automatically-generated help message, e.g. for the ``mode'' option:
Neal Norwitz488609e2003-01-06 16:51:37 +0000531\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000532-m MODE, --mode=MODE
Neal Norwitz488609e2003-01-06 16:51:37 +0000533\end{verbatim}
534
535Here, ``MODE'' is called the meta-variable: it stands for the argument
Greg Wardb6f7fb72004-09-28 01:30:23 +0000536that the user is expected to supply to \programopt{-m}/\longprogramopt{mode}. By default,
537\module{optparse} converts the destination variable name to uppercase and uses
538that for the meta-variable. Sometimes, that's not what you want{---}for example, the \longprogramopt{filename} option explicitly sets
539\code{metavar="FILE"}, resulting in this automatically-generated option
540description:
Neal Norwitz488609e2003-01-06 16:51:37 +0000541\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000542-f FILE, --filename=FILE
Neal Norwitz488609e2003-01-06 16:51:37 +0000543\end{verbatim}
544
545This is important for more than just saving space, though: the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000546manually written help text uses the meta-variable ``FILE'' to clue the
547user in that there's a connection between the semi-formal syntax ``-f
548FILE'' and the informal semantic description ``write output to FILE''.
549This is a simple but effective way to make your help text a lot
550clearer and more useful for end users.
551
552\item {}
553options that have a default value can include \code{{\%}default} in
554the help string{---}\module{optparse} will replace it with \function{str()} of the
555option's default value. If an option has no default value (or the
556default value is \code{None}), \code{{\%}default} expands to \code{none}.
557
Neal Norwitz488609e2003-01-06 16:51:37 +0000558\end{itemize}
559
Fred Drakecf6d74a2003-04-18 15:50:13 +0000560
Greg Wardb6f7fb72004-09-28 01:30:23 +0000561\subsubsection{Printing a version string\label{optparse-printing-a-version-string}}
Fred Drakecf6d74a2003-04-18 15:50:13 +0000562
Greg Wardb6f7fb72004-09-28 01:30:23 +0000563Similar to the brief usage string, \module{optparse} can also print a version string
564for your program. You have to supply the string as the \code{version}
565argument to OptionParser:
Neal Norwitz488609e2003-01-06 16:51:37 +0000566\begin{verbatim}
567parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
568\end{verbatim}
569
Greg Wardb6f7fb72004-09-28 01:30:23 +0000570Note that \code{"{\%}prog"} is expanded just like it is in \var{usage}. Apart
571from that, \code{version} can contain anything you like. When you supply
572it, \module{optparse} automatically adds a \code{"-{}-version"} option to your parser.
573If it encounters this option on the command line, it expands your
574\code{version} string (by replacing \code{"{\%}prog"}), prints it to stdout, and
575exits.
Neal Norwitz488609e2003-01-06 16:51:37 +0000576
Greg Wardb6f7fb72004-09-28 01:30:23 +0000577For example, if your script is called \code{/usr/bin/foo}:
Neal Norwitz488609e2003-01-06 16:51:37 +0000578\begin{verbatim}
579$ /usr/bin/foo --version
580foo 1.0
Greg Wardb6f7fb72004-09-28 01:30:23 +0000581\end{verbatim}
582
Neal Norwitz488609e2003-01-06 16:51:37 +0000583
584\subsubsection{Error-handling\label{optparse-error-handling}}
585
Greg Wardb6f7fb72004-09-28 01:30:23 +0000586There are two broad classes of errors that \module{optparse} has to worry about:
587programmer errors and user errors. Programmer errors are usually
588erroneous calls to \code{parse.add{\_}option()}, e.g. invalid option strings,
589unknown option attributes, missing option attributes, etc. These are
590dealt with in the usual way: raise an exception (either
591\code{optparse.OptionError} or \code{TypeError}) and let the program crash.
Neal Norwitz488609e2003-01-06 16:51:37 +0000592
Greg Wardb6f7fb72004-09-28 01:30:23 +0000593Handling user errors is much more important, since they are guaranteed
594to happen no matter how stable your code is. \module{optparse} can automatically
595detect some user errors, such as bad option arguments (passing \code{"-n
5964x"} where \programopt{-n} takes an integer argument), missing arguments
597(\code{"-n"} at the end of the command line, where \programopt{-n} takes an argument
598of any type). Also, you can call \code{parser.error()} to signal an
599application-defined error condition:
600\begin{verbatim}
601(options, args) = parser.parse_args()
602[...]
603if options.a and options.b:
604 parser.error("options -a and -b are mutually exclusive")
605\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000606
Greg Wardb6f7fb72004-09-28 01:30:23 +0000607In either case, \module{optparse} handles the error the same way: it prints the
608program's usage message and an error message to standard error and
609exits with error status 2.
Neal Norwitz488609e2003-01-06 16:51:37 +0000610
Greg Wardb6f7fb72004-09-28 01:30:23 +0000611Consider the first example above, where the user passes \code{"4x"} to an
612option that takes an integer:
613\begin{verbatim}
614$ /usr/bin/foo -n 4x
615usage: foo [options]
Neal Norwitz488609e2003-01-06 16:51:37 +0000616
Greg Wardb6f7fb72004-09-28 01:30:23 +0000617foo: error: option -n: invalid integer value: '4x'
618\end{verbatim}
619
620Or, where the user fails to pass a value at all:
621\begin{verbatim}
622$ /usr/bin/foo -n
623usage: foo [options]
624
625foo: error: -n option requires an argument
626\end{verbatim}
627
628\module{optparse}-generated error messages take care always to mention the option
629involved in the error; be sure to do the same when calling
630\code{parser.error()} from your application code.
631
632If \module{optparse}'s default error-handling behaviour does not suite your needs,
633you'll need to subclass OptionParser and override \code{exit()} and/or
634\method{error()}.
635
636
637\subsubsection{Putting it all together\label{optparse-putting-it-all-together}}
638
639Here's what \module{optparse}-based scripts usually look like:
Neal Norwitz488609e2003-01-06 16:51:37 +0000640\begin{verbatim}
641from optparse import OptionParser
Greg Wardd7231282003-05-03 21:22:58 +0000642[...]
643def main():
Greg Wardb6f7fb72004-09-28 01:30:23 +0000644 usage = "usage: %prog [options] arg"
Neal Norwitz488609e2003-01-06 16:51:37 +0000645 parser = OptionParser(usage)
Greg Wardb6f7fb72004-09-28 01:30:23 +0000646 parser.add_option("-f", "--file", dest="filename",
Neal Norwitz488609e2003-01-06 16:51:37 +0000647 help="read data from FILENAME")
648 parser.add_option("-v", "--verbose",
649 action="store_true", dest="verbose")
650 parser.add_option("-q", "--quiet",
651 action="store_false", dest="verbose")
Greg Wardb6f7fb72004-09-28 01:30:23 +0000652 [...]
653 (options, args) = parser.parse_args()
654 if len(args) != 1:
Neal Norwitz488609e2003-01-06 16:51:37 +0000655 parser.error("incorrect number of arguments")
Neal Norwitz488609e2003-01-06 16:51:37 +0000656 if options.verbose:
Johannes Gijsbersc9c37ca2004-09-11 15:47:30 +0000657 print "reading %s..." % options.filename
Greg Wardb6f7fb72004-09-28 01:30:23 +0000658 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000659
660if __name__ == "__main__":
661 main()
662\end{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000663% $Id$
Neal Norwitz488609e2003-01-06 16:51:37 +0000664
Neal Norwitz488609e2003-01-06 16:51:37 +0000665
Greg Wardb6f7fb72004-09-28 01:30:23 +0000666\subsection{Reference Guide\label{optparse-reference-guide}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000667
Neal Norwitz488609e2003-01-06 16:51:37 +0000668
Greg Wardb6f7fb72004-09-28 01:30:23 +0000669\subsubsection{Populating the parser\label{optparse-populating-the-parser}}
670
671There are several ways to populate the parser with options. The
672preferred way is by using \code{OptionParser.add{\_}option()}, as shown in
673section~\ref{None}, the tutorial section. \method{add{\_}option()} can be called in one of two
674ways:
675\begin{itemize}
676\item {}
677pass it an Option instance (as returned by \function{make{\_}option()})
678
679\item {}
680pass it any combination of positional and keyword arguments that are
681acceptable to \function{make{\_}option()} (i.e., to the Option constructor),
682and it will create the Option instance for you
683
684\end{itemize}
685
686The other alternative is to pass a list of pre-constructed Option
687instances to the OptionParser constructor, as in:
Neal Norwitz488609e2003-01-06 16:51:37 +0000688\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000689option_list = [
Neal Norwitz488609e2003-01-06 16:51:37 +0000690 make_option("-f", "--filename",
691 action="store", type="string", dest="filename"),
692 make_option("-q", "--quiet",
Greg Wardb6f7fb72004-09-28 01:30:23 +0000693 action="store_false", dest="verbose"),
694 ]
Neal Norwitz488609e2003-01-06 16:51:37 +0000695parser = OptionParser(option_list=option_list)
696\end{verbatim}
697
Greg Wardb6f7fb72004-09-28 01:30:23 +0000698(\function{make{\_}option()} is a factory function for creating Option instances;
699currently it is an alias for the Option constructor. A future version
700of \module{optparse} may split Option into several classes, and \function{make{\_}option()}
701will pick the right class to instantiate. Do not instantiate Option
702directly.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000703
Neal Norwitz488609e2003-01-06 16:51:37 +0000704
705\subsubsection{Defining options\label{optparse-defining-options}}
706
Greg Wardb6f7fb72004-09-28 01:30:23 +0000707Each Option instance represents a set of synonymous command-line option
708strings, e.g. programopt{\{}f{\}} and longprogramopt{\{}--file{\}}. You can
709specify any number of short or long option strings, but you must specify
710at least one overall option string.
711
712The canonical way to create an Option instance is by calling
713\function{make{\_}option()}, so that is what will be shown here. However, the
714most common and convenient way is to use \code{parser.add{\_}option()}. Note
715that \function{make{\_}option()} and \code{parser.add{\_}option()} have identical call
716signatures:
717\begin{verbatim}
718make_option(opt_str, ..., attr=value, ...)
719parser.add_option(opt_str, ..., attr=value, ...)
720\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000721
722To define an option with only a short option string:
Neal Norwitz488609e2003-01-06 16:51:37 +0000723\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000724make_option("-f", attr=value, ...)
Neal Norwitz488609e2003-01-06 16:51:37 +0000725\end{verbatim}
726
727And to define an option with only a long option string:
Neal Norwitz488609e2003-01-06 16:51:37 +0000728\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000729make_option("--foo", attr=value, ...)
Neal Norwitz488609e2003-01-06 16:51:37 +0000730\end{verbatim}
731
Greg Wardb6f7fb72004-09-28 01:30:23 +0000732The \code{attr=value} keyword arguments define option attributes,
733i.e. attributes of the Option object. The most important option
734attribute is \member{action}, and it largely determines what other attributes
735are relevant or required. If you pass irrelevant option attributes, or
736fail to pass required ones, \module{optparse} raises an OptionError exception
737explaining your mistake.
Neal Norwitz488609e2003-01-06 16:51:37 +0000738
Greg Wardb6f7fb72004-09-28 01:30:23 +0000739An options's \emph{action} determines what \module{optparse} does when it encounters
740this option on the command-line. The actions hard-coded into \module{optparse} are:
741\begin{description}
742\item[\code{store}]
743store this option's argument {[}default]
744\item[\code{store{\_}const}]
745store a constant value
746\item[\code{store{\_}true}]
747store a true value
748\item[\code{store{\_}false}]
749store a false value
750\item[\code{append}]
751append this option's argument to a list
752\item[\code{count}]
753increment a counter by one
754\item[\code{callback}]
755call a specified function
756\item[\member{help}]
757print a usage message including all options and the
758documentation for them
759\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +0000760
Greg Wardb6f7fb72004-09-28 01:30:23 +0000761(If you don't supply an action, the default is \code{store}. For this
762action, you may also supply \member{type} and \member{dest} option attributes; see
Neal Norwitz488609e2003-01-06 16:51:37 +0000763below.)
764
765As you can see, most actions involve storing or updating a value
Greg Wardb6f7fb72004-09-28 01:30:23 +0000766somewhere. \module{optparse} always creates an instance of \code{optparse.Values}
767specifically for this purpose; we refer to this instance as \var{options}.
768Option arguments (and various other values) are stored as attributes of
769this object, according to the \member{dest} (destination) option attribute.
Neal Norwitz488609e2003-01-06 16:51:37 +0000770
Greg Wardb6f7fb72004-09-28 01:30:23 +0000771For example, when you call
Neal Norwitz488609e2003-01-06 16:51:37 +0000772\begin{verbatim}
773parser.parse_args()
774\end{verbatim}
775
Greg Wardb6f7fb72004-09-28 01:30:23 +0000776one of the first things \module{optparse} does is create the \var{options} object:
Neal Norwitz488609e2003-01-06 16:51:37 +0000777\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000778options = Values()
Neal Norwitz488609e2003-01-06 16:51:37 +0000779\end{verbatim}
780
Greg Wardb6f7fb72004-09-28 01:30:23 +0000781If one of the options in this parser is defined with
Neal Norwitz488609e2003-01-06 16:51:37 +0000782\begin{verbatim}
783make_option("-f", "--file", action="store", type="string", dest="filename")
784\end{verbatim}
785
786and the command-line being parsed includes any of the following:
Neal Norwitz488609e2003-01-06 16:51:37 +0000787\begin{verbatim}
788-ffoo
789-f foo
790--file=foo
791--file foo
792\end{verbatim}
793
Greg Wardb6f7fb72004-09-28 01:30:23 +0000794then \module{optparse}, on seeing the \programopt{-f} or \longprogramopt{file} option, will do the
795equivalent of
Neal Norwitz488609e2003-01-06 16:51:37 +0000796\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000797options.filename = "foo"
Neal Norwitz488609e2003-01-06 16:51:37 +0000798\end{verbatim}
799
Greg Wardb6f7fb72004-09-28 01:30:23 +0000800The \member{type} and \member{dest} option attributes are almost as important as
801\member{action}, but \member{action} is the only one that makes sense for \emph{all}
802options.
803
Neal Norwitz488609e2003-01-06 16:51:37 +0000804
805\subsubsection{Option actions\label{optparse-option-actions}}
806
Greg Wardb6f7fb72004-09-28 01:30:23 +0000807The various option actions all have slightly different requirements and
808effects. Most actions have several relevant option attributes which you
809may specify to guide \module{optparse}'s behaviour; a few have required attributes,
810which you must specify for any option using that action.
811\begin{itemize}
812\item {}
813\code{store} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000814
Greg Wardb6f7fb72004-09-28 01:30:23 +0000815The option must be followed by an argument, which is
816converted to a value according to \member{type} and stored in
817\member{dest}. If \code{nargs} {\textgreater} 1, multiple arguments will be consumed
818from the command line; all will be converted according to
819\member{type} and stored to \member{dest} as a tuple. See the ``Option
820types'' section below.
Neal Norwitz488609e2003-01-06 16:51:37 +0000821
Greg Wardb6f7fb72004-09-28 01:30:23 +0000822If \code{choices} is supplied (a list or tuple of strings), the type
823defaults to \code{choice}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000824
Greg Wardb6f7fb72004-09-28 01:30:23 +0000825If \member{type} is not supplied, it defaults to \code{string}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000826
Greg Wardb6f7fb72004-09-28 01:30:23 +0000827If \member{dest} is not supplied, \module{optparse} derives a destination from the
828first long option string (e.g., \code{"-{}-foo-bar"} implies \code{foo{\_}bar}).
829If there are no long option strings, \module{optparse} derives a destination from
830the first short option string (e.g., \code{"-f"} implies \code{f}).
Neal Norwitz488609e2003-01-06 16:51:37 +0000831
832Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000833\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000834parser.add_option("-f")
835parser.add_option("-p", type="float", nargs=3, dest="point")
Neal Norwitz488609e2003-01-06 16:51:37 +0000836\end{verbatim}
837
Greg Wardb6f7fb72004-09-28 01:30:23 +0000838As it parses the command line
Neal Norwitz488609e2003-01-06 16:51:37 +0000839\begin{verbatim}
840-f foo.txt -p 1 -3.5 4 -fbar.txt
841\end{verbatim}
842
Greg Wardb6f7fb72004-09-28 01:30:23 +0000843\module{optparse} will set
Neal Norwitz488609e2003-01-06 16:51:37 +0000844\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000845options.f = "foo.txt"
846options.point = (1.0, -3.5, 4.0)
847options.f = "bar.txt"
Neal Norwitz488609e2003-01-06 16:51:37 +0000848\end{verbatim}
849
Greg Wardb6f7fb72004-09-28 01:30:23 +0000850\item {}
851\code{store{\_}const} {[}required: \code{const}; relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000852
Greg Wardb6f7fb72004-09-28 01:30:23 +0000853The value \code{const} is stored in \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000854
855Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000856\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000857parser.add_option("-q", "--quiet",
858 action="store_const", const=0, dest="verbose")
859parser.add_option("-v", "--verbose",
860 action="store_const", const=1, dest="verbose")
861parser.add_option("--noisy",
862 action="store_const", const=2, dest="verbose")
Neal Norwitz488609e2003-01-06 16:51:37 +0000863\end{verbatim}
864
Greg Wardb6f7fb72004-09-28 01:30:23 +0000865If \code{"-{}-noisy"} is seen, \module{optparse} will set
Neal Norwitz488609e2003-01-06 16:51:37 +0000866\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000867options.verbose = 2
Neal Norwitz488609e2003-01-06 16:51:37 +0000868\end{verbatim}
869
Greg Wardb6f7fb72004-09-28 01:30:23 +0000870\item {}
871\code{store{\_}true} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000872
Greg Wardb6f7fb72004-09-28 01:30:23 +0000873A special case of \code{store{\_}const} that stores a true value
874to \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000875
Greg Wardb6f7fb72004-09-28 01:30:23 +0000876\item {}
877\code{store{\_}false} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000878
Greg Wardb6f7fb72004-09-28 01:30:23 +0000879Like \code{store{\_}true}, but stores a false value.
Neal Norwitz488609e2003-01-06 16:51:37 +0000880
881Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000882\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000883parser.add_option("--clobber", action="store_true", dest="clobber")
884parser.add_option("--no-clobber", action="store_false", dest="clobber")
Neal Norwitz488609e2003-01-06 16:51:37 +0000885\end{verbatim}
886
Greg Wardb6f7fb72004-09-28 01:30:23 +0000887\item {}
888\code{append} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000889
890The option must be followed by an argument, which is appended to the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000891list in \member{dest}. If no default value for \member{dest} is supplied, an
892empty list is automatically created when \module{optparse} first encounters this
893option on the command-line. If \code{nargs} {\textgreater} 1, multiple arguments are
894consumed, and a tuple of length \code{nargs} is appended to \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000895
Greg Wardb6f7fb72004-09-28 01:30:23 +0000896The defaults for \member{type} and \member{dest} are the same as for the
897\code{store} action.
Neal Norwitz488609e2003-01-06 16:51:37 +0000898
899Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000900\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000901parser.add_option("-t", "--tracks", action="append", type="int")
Neal Norwitz488609e2003-01-06 16:51:37 +0000902\end{verbatim}
903
Greg Wardb6f7fb72004-09-28 01:30:23 +0000904If \code{"-t3"} is seen on the command-line, \module{optparse} does the equivalent of:
Neal Norwitz488609e2003-01-06 16:51:37 +0000905\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000906options.tracks = []
907options.tracks.append(int("3"))
Neal Norwitz488609e2003-01-06 16:51:37 +0000908\end{verbatim}
909
Greg Wardb6f7fb72004-09-28 01:30:23 +0000910If, a little later on, \code{"-{}-tracks=4"} is seen, it does:
Neal Norwitz488609e2003-01-06 16:51:37 +0000911\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000912options.tracks.append(int("4"))
Neal Norwitz488609e2003-01-06 16:51:37 +0000913\end{verbatim}
914
Greg Wardb6f7fb72004-09-28 01:30:23 +0000915\item {}
916\code{count} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000917
Greg Wardb6f7fb72004-09-28 01:30:23 +0000918Increment the integer stored at \member{dest}. If no default value is
919supplied, \member{dest} is set to zero before being incremented the first
920time.
Neal Norwitz488609e2003-01-06 16:51:37 +0000921
922Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000923\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000924parser.add_option("-v", action="count", dest="verbosity")
Neal Norwitz488609e2003-01-06 16:51:37 +0000925\end{verbatim}
926
Greg Wardb6f7fb72004-09-28 01:30:23 +0000927The first time \code{"-v"} is seen on the command line, \module{optparse} does the
928equivalent of:
Neal Norwitz488609e2003-01-06 16:51:37 +0000929\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000930options.verbosity = 0
931options.verbosity += 1
Neal Norwitz488609e2003-01-06 16:51:37 +0000932\end{verbatim}
933
Greg Wardb6f7fb72004-09-28 01:30:23 +0000934Every subsequent occurrence of \code{"-v"} results in
Neal Norwitz488609e2003-01-06 16:51:37 +0000935\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000936options.verbosity += 1
Neal Norwitz488609e2003-01-06 16:51:37 +0000937\end{verbatim}
938
Greg Wardb6f7fb72004-09-28 01:30:23 +0000939\item {}
940\code{callback} {[}required: \code{callback};
941relevant: \member{type}, \code{nargs}, \code{callback{\_}args}, \code{callback{\_}kwargs}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000942
Greg Wardb6f7fb72004-09-28 01:30:23 +0000943Call the function specified by \code{callback}. The signature of
944this function should be
Neal Norwitz488609e2003-01-06 16:51:37 +0000945\begin{verbatim}
946func(option : Option,
947 opt : string,
948 value : any,
949 parser : OptionParser,
950 *args, **kwargs)
951\end{verbatim}
952
Greg Wardb6f7fb72004-09-28 01:30:23 +0000953See section~\ref{None}, Option Callbacks for more detail.
Neal Norwitz488609e2003-01-06 16:51:37 +0000954
Greg Wardb6f7fb72004-09-28 01:30:23 +0000955\item {}
956\member{help}
Neal Norwitz488609e2003-01-06 16:51:37 +0000957
Greg Wardb6f7fb72004-09-28 01:30:23 +0000958Prints a complete help message for all the options in the
959current option parser. The help message is constructed from
960the \var{usage} string passed to OptionParser's constructor and
961the \member{help} string passed to every option.
Neal Norwitz488609e2003-01-06 16:51:37 +0000962
Greg Wardb6f7fb72004-09-28 01:30:23 +0000963If no \member{help} string is supplied for an option, it will still be
964listed in the help message. To omit an option entirely, use
965the special value \code{optparse.SUPPRESS{\_}HELP}.
966
967\module{optparse} automatically adds a \member{help} option to all OptionParsers, so
968you do not normally need to create one.
Neal Norwitz488609e2003-01-06 16:51:37 +0000969
970Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000971\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000972from optparse import OptionParser, SUPPRESS_HELP
Neal Norwitz488609e2003-01-06 16:51:37 +0000973
Greg Wardb6f7fb72004-09-28 01:30:23 +0000974parser = OptionParser()
975parser.add_option("-h", "--help", action="help"),
976parser.add_option("-v", action="store_true", dest="verbose",
977 help="Be moderately verbose")
978parser.add_option("--file", dest="filename",
979 help="Input file to read data from"),
980parser.add_option("--secret", help=SUPPRESS_HELP)
Neal Norwitz488609e2003-01-06 16:51:37 +0000981\end{verbatim}
982
Greg Wardb6f7fb72004-09-28 01:30:23 +0000983If \module{optparse} sees either \code{"-h"} or \code{"-{}-help"} on the command line, it
984will print something like the following help message to stdout
985(assuming \code{sys.argv{[}0]} is \code{"foo.py"}):
Neal Norwitz488609e2003-01-06 16:51:37 +0000986\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000987usage: foo.py [options]
Neal Norwitz488609e2003-01-06 16:51:37 +0000988
989options:
990 -h, --help Show this help message and exit
991 -v Be moderately verbose
992 --file=FILENAME Input file to read data from
993\end{verbatim}
994
995After printing the help message, \module{optparse} terminates your process
996with \code{sys.exit(0)}.
997
Greg Wardb6f7fb72004-09-28 01:30:23 +0000998\item {}
999\code{version}
Neal Norwitz488609e2003-01-06 16:51:37 +00001000
Greg Wardb6f7fb72004-09-28 01:30:23 +00001001Prints the version number supplied to the OptionParser to stdout and
1002exits. The version number is actually formatted and printed by the
1003\code{print{\_}version()} method of OptionParser. Generally only relevant
1004if the \code{version} argument is supplied to the OptionParser
1005constructor. As with \member{help} options, you will rarely create
1006\code{version} options, since \module{optparse} automatically adds them when needed.
1007
1008\end{itemize}
1009
Neal Norwitz488609e2003-01-06 16:51:37 +00001010
1011\subsubsection{Option types\label{optparse-option-types}}
1012
Greg Wardb6f7fb72004-09-28 01:30:23 +00001013\module{optparse} has six built-in option types: \code{string}, \code{int}, \code{long},
1014\code{choice}, \code{float} and \code{complex}. If you need to add new option
1015types, see section~\ref{optparse-extending}, Extending \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001016
Greg Wardb6f7fb72004-09-28 01:30:23 +00001017Arguments to string options are not checked or converted in any way: the
1018text on the command line is stored in the destination (or passed to the
1019callback) as-is.
Neal Norwitz488609e2003-01-06 16:51:37 +00001020
Greg Wardb6f7fb72004-09-28 01:30:23 +00001021Integer arguments are passed to \code{int()} to convert them to Python
1022integers. If \code{int()} fails, so will \module{optparse}, although with a more
1023useful error message. (Internally, \module{optparse} raises OptionValueError;
1024OptionParser catches this exception higher up and terminates your
1025program with a useful error message.)
Neal Norwitz488609e2003-01-06 16:51:37 +00001026
Greg Wardb6f7fb72004-09-28 01:30:23 +00001027Likewise, \code{float} arguments are passed to \code{float()} for conversion,
1028\code{long} arguments to \code{long()}, and \code{complex} arguments to
1029\code{complex()}. Apart from that, they are handled identically to integer
1030arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +00001031
Greg Wardb6f7fb72004-09-28 01:30:23 +00001032\code{choice} options are a subtype of \code{string} options. The \code{choices}
1033option attribute (a sequence of strings) defines the set of allowed
1034option arguments. \code{optparse.option.check{\_}choice()} compares
1035user-supplied option arguments against this master list and raises
1036OptionValueError if an invalid string is given.
Neal Norwitz488609e2003-01-06 16:51:37 +00001037
Greg Wardb6f7fb72004-09-28 01:30:23 +00001038
1039\subsubsection{Querying and manipulating your option parser\label{optparse-querying-and-manipulating-your-option-parser}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001040
1041Sometimes, it's useful to poke around your option parser and see what's
Greg Wardb6f7fb72004-09-28 01:30:23 +00001042there. OptionParser provides a couple of methods to help you out:
1043\begin{description}
1044\item[\code{has{\_}option(opt{\_}str)}]
1045Return true if the OptionParser has an option with
1046option string \code{opt{\_}str} (e.g., \code{"-q"} or \code{"-{}-verbose"}).
1047\item[\code{get{\_}option(opt{\_}str)}]
1048Returns the Option instance with the option string \code{opt{\_}str}, or
1049\code{None} if no options have that option string.
1050\item[\code{remove{\_}option(opt{\_}str)}]
1051If the OptionParser has an option corresponding to \code{opt{\_}str},
1052that option is removed. If that option provided any other
1053option strings, all of those option strings become invalid.
Neal Norwitz488609e2003-01-06 16:51:37 +00001054
Greg Wardb6f7fb72004-09-28 01:30:23 +00001055If \code{opt{\_}str} does not occur in any option belonging to this
1056OptionParser, raises ValueError.
1057\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001058
Neal Norwitz488609e2003-01-06 16:51:37 +00001059
Greg Wardb6f7fb72004-09-28 01:30:23 +00001060\subsubsection{Conflicts between options\label{optparse-conflicts-between-options}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001061
Greg Wardb6f7fb72004-09-28 01:30:23 +00001062If you're not careful, it's easy to define options with conflicting
1063option strings:
Neal Norwitz488609e2003-01-06 16:51:37 +00001064\begin{verbatim}
1065parser.add_option("-n", "--dry-run", ...)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001066[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001067parser.add_option("-n", "--noisy", ...)
Neal Norwitz488609e2003-01-06 16:51:37 +00001068\end{verbatim}
1069
Greg Wardb6f7fb72004-09-28 01:30:23 +00001070(This is particularly true if you've defined your own OptionParser
1071subclass with some standard options.)
Neal Norwitz488609e2003-01-06 16:51:37 +00001072
Greg Wardb6f7fb72004-09-28 01:30:23 +00001073Every time you add an option, \module{optparse} checks for conflicts with existing
1074options. If it finds any, it invokes the current conflict-handling
1075mechanism. You can set the conflict-handling mechanism either in the
1076constructor:
Neal Norwitz488609e2003-01-06 16:51:37 +00001077\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001078parser = OptionParser(..., conflict_handler="...")
Neal Norwitz488609e2003-01-06 16:51:37 +00001079\end{verbatim}
1080
Greg Wardb6f7fb72004-09-28 01:30:23 +00001081or with a separate call:
1082\begin{verbatim}
1083parser.set_conflict_handler("...")
1084\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +00001085
Greg Wardb6f7fb72004-09-28 01:30:23 +00001086The available conflict-handling mechanisms are:
1087\begin{quote}
1088\begin{description}
1089\item[\code{error} (default)]
1090assume option conflicts are a programming error and raise
1091OptionConflictError
1092\item[\code{resolve}]
1093resolve option conflicts intelligently (see below)
1094\end{description}
1095\end{quote}
Neal Norwitz488609e2003-01-06 16:51:37 +00001096
Greg Wardb6f7fb72004-09-28 01:30:23 +00001097As an example, let's define an OptionParser that resolves conflicts
1098intelligently and add conflicting options to it:
Neal Norwitz488609e2003-01-06 16:51:37 +00001099\begin{verbatim}
1100parser = OptionParser(conflict_handler="resolve")
Greg Wardb6f7fb72004-09-28 01:30:23 +00001101parser.add_option("-n", "--dry-run", ..., help="do no harm")
1102parser.add_option("-n", "--noisy", ..., help="be noisy")
Neal Norwitz488609e2003-01-06 16:51:37 +00001103\end{verbatim}
1104
Neal Norwitz488609e2003-01-06 16:51:37 +00001105At this point, \module{optparse} detects that a previously-added option is already
Greg Wardb6f7fb72004-09-28 01:30:23 +00001106using the \code{"-n"} option string. Since \code{conflict{\_}handler} is
1107\code{"resolve"}, it resolves the situation by removing \code{"-n"} from the
1108earlier option's list of option strings. Now \code{"-{}-dry-run"} is the
1109only way for the user to activate that option. If the user asks for
1110help, the help message will reflect that:
Neal Norwitz488609e2003-01-06 16:51:37 +00001111\begin{verbatim}
1112options:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001113 --dry-run do no harm
1114 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001115 -n, --noisy be noisy
1116\end{verbatim}
1117
Greg Wardb6f7fb72004-09-28 01:30:23 +00001118It's possible to whittle away the option strings for a previously-added
1119option until there are none left, and the user has no way of invoking
1120that option from the command-line. In that case, \module{optparse} removes that
1121option completely, so it doesn't show up in help text or anywhere else.
1122Carrying on with our existing OptionParser:
Neal Norwitz488609e2003-01-06 16:51:37 +00001123\begin{verbatim}
1124parser.add_option("--dry-run", ..., help="new dry-run option")
1125\end{verbatim}
1126
Greg Wardb6f7fb72004-09-28 01:30:23 +00001127At this point, the original \programopt{-n/-{}-dry-run} option is no longer
1128accessible, so \module{optparse} removes it, leaving this help text:
Neal Norwitz488609e2003-01-06 16:51:37 +00001129\begin{verbatim}
1130options:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001131 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001132 -n, --noisy be noisy
1133 --dry-run new dry-run option
1134\end{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001135% $Id$
Neal Norwitz488609e2003-01-06 16:51:37 +00001136
Neal Norwitz488609e2003-01-06 16:51:37 +00001137
Greg Wardb6f7fb72004-09-28 01:30:23 +00001138\subsection{Option Callbacks\label{optparse-option-callbacks}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001139
Greg Wardb6f7fb72004-09-28 01:30:23 +00001140When \module{optparse}'s built-in actions and types aren't quite enough for your
1141needs, you have two choices: extend \module{optparse} or define a callback option.
1142Extending \module{optparse} is more general, but overkill for a lot of simple
1143cases. Quite often a simple callback is all you need.
Neal Norwitz488609e2003-01-06 16:51:37 +00001144
Greg Wardb6f7fb72004-09-28 01:30:23 +00001145There are two steps to defining a callback option:
1146\begin{itemize}
1147\item {}
1148define the option itself using the \code{callback} action
Neal Norwitz488609e2003-01-06 16:51:37 +00001149
Greg Wardb6f7fb72004-09-28 01:30:23 +00001150\item {}
1151write the callback; this is a function (or method) that
1152takes at least four arguments, as described below
1153
1154\end{itemize}
1155
1156
1157\subsubsection{Defining a callback option\label{optparse-defining-a-callback-option}}
1158
1159As always, the easiest way to define a callback option is by using the
1160\code{parser.add{\_}option()} method. Apart from \member{action}, the only option
1161attribute you must specify is \code{callback}, the function to call:
Neal Norwitz488609e2003-01-06 16:51:37 +00001162\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001163parser.add_option("-c", action="callback", callback=my_callback)
Neal Norwitz488609e2003-01-06 16:51:37 +00001164\end{verbatim}
1165
Greg Wardb6f7fb72004-09-28 01:30:23 +00001166\code{callback} is a function (or other callable object), so you must have
1167already defined \code{my{\_}callback()} when you create this callback option.
1168In this simple case, \module{optparse} doesn't even know if \programopt{-c} takes any
1169arguments, which usually means that the option takes no arguments{---}the
1170mere presence of \programopt{-c} on the command-line is all it needs to know. In
1171some circumstances, though, you might want your callback to consume an
1172arbitrary number of command-line arguments. This is where writing
1173callbacks gets tricky; it's covered later in this section.
1174
1175\module{optparse} always passes four particular arguments to your callback, and it
1176will only pass additional arguments if you specify them via
1177\code{callback{\_}args} and \code{callback{\_}kwargs}. Thus, the minimal callback
1178function signature is:
1179\begin{verbatim}
1180def my_callback(option, opt, value, parser):
1181\end{verbatim}
1182
1183The four arguments to a callback are described below.
Neal Norwitz488609e2003-01-06 16:51:37 +00001184
1185There are several other option attributes that you can supply when you
Greg Wardb6f7fb72004-09-28 01:30:23 +00001186define a callback option:
1187\begin{description}
1188\item[\member{type}]
1189has its usual meaning: as with the \code{store} or \code{append} actions,
1190it instructs \module{optparse} to consume one argument and convert it to
1191\member{type}. Rather than storing the converted value(s) anywhere,
1192though, \module{optparse} passes it to your callback function.
1193\item[\code{nargs}]
1194also has its usual meaning: if it is supplied and {\textgreater} 1, \module{optparse} will
1195consume \code{nargs} arguments, each of which must be convertible to
1196\member{type}. It then passes a tuple of converted values to your
1197callback.
1198\item[\code{callback{\_}args}]
1199a tuple of extra positional arguments to pass to the callback
1200\item[\code{callback{\_}kwargs}]
1201a dictionary of extra keyword arguments to pass to the callback
1202\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001203
Neal Norwitz488609e2003-01-06 16:51:37 +00001204
Greg Wardb6f7fb72004-09-28 01:30:23 +00001205\subsubsection{How callbacks are called\label{optparse-how-callbacks-are-called}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001206
1207All callbacks are called as follows:
Neal Norwitz488609e2003-01-06 16:51:37 +00001208\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001209func(option, opt_str, value, parser, *args, **kwargs)
Neal Norwitz488609e2003-01-06 16:51:37 +00001210\end{verbatim}
1211
1212where
Greg Wardb6f7fb72004-09-28 01:30:23 +00001213\begin{description}
1214\item[\code{option}]
1215is the Option instance that's calling the callback
1216\item[\code{opt{\_}str}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001217is the option string seen on the command-line that's triggering the
Greg Wardb6f7fb72004-09-28 01:30:23 +00001218callback. (If an abbreviated long option was used, \code{opt{\_}str} will
1219be the full, canonical option string{---}e.g. if the user puts
1220\code{"-{}-foo"} on the command-line as an abbreviation for
1221\code{"-{}-foobar"}, then \code{opt{\_}str} will be \code{"-{}-foobar"}.)
1222\item[\code{value}]
1223is the argument to this option seen on the command-line. \module{optparse} will
1224only expect an argument if \member{type} is set; the type of \code{value}
1225will be the type implied by the option's type. If \member{type} for this
1226option is \code{None} (no argument expected), then \code{value} will be
1227\code{None}. If \code{nargs} {\textgreater} 1, \code{value} will be a tuple of values of
1228the appropriate type.
1229\item[\code{parser}]
1230is the OptionParser instance driving the whole thing, mainly
1231useful because you can access some other interesting data through
1232its instance attributes:
1233\begin{description}
1234\item[\code{parser.largs}]
1235the current list of leftover arguments, ie. arguments that have
1236been consumed but are neither options nor option arguments.
1237Feel free to modify \code{parser.largs}, e.g. by adding more
1238arguments to it. (This list will become \var{args}, the second
1239return value of \method{parse{\_}args()}.)
1240\item[\code{parser.rargs}]
1241the current list of remaining arguments, ie. with \code{opt{\_}str} and
1242\code{value} (if applicable) removed, and only the arguments
1243following them still there. Feel free to modify
1244\code{parser.rargs}, e.g. by consuming more arguments.
1245\item[\code{parser.values}]
1246the object where option values are by default stored (an
1247instance of optparse.OptionValues). This lets callbacks use the
1248same mechanism as the rest of \module{optparse} for storing option values;
1249you don't need to mess around with globals or closures. You can
1250also access or modify the value(s) of any options already
1251encountered on the command-line.
1252\end{description}
1253\item[\var{args}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001254is a tuple of arbitrary positional arguments supplied via the
Greg Wardb6f7fb72004-09-28 01:30:23 +00001255\code{callback{\_}args} option attribute.
1256\item[\code{kwargs}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001257is a dictionary of arbitrary keyword arguments supplied via
Greg Wardb6f7fb72004-09-28 01:30:23 +00001258\code{callback{\_}kwargs}.
1259\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001260
Neal Norwitz488609e2003-01-06 16:51:37 +00001261
Greg Wardb6f7fb72004-09-28 01:30:23 +00001262\subsubsection{Error handling\label{optparse-error-handling}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001263
Greg Wardb6f7fb72004-09-28 01:30:23 +00001264The callback function should raise OptionValueError if there are any
1265problems with the option or its argument(s). \module{optparse} catches this and
1266terminates the program, printing the error message you supply to
1267stderr. Your message should be clear, concise, accurate, and mention
1268the option at fault. Otherwise, the user will have a hard time
1269figuring out what he did wrong.
Neal Norwitz488609e2003-01-06 16:51:37 +00001270
Neal Norwitz488609e2003-01-06 16:51:37 +00001271
Greg Wardb6f7fb72004-09-28 01:30:23 +00001272\subsubsection{Callback example 1: trivial callback\label{optparse-callback-example-1:-trivial-callback}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001273
1274Here's an example of a callback option that takes no arguments, and
1275simply records that the option was seen:
Neal Norwitz488609e2003-01-06 16:51:37 +00001276\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001277def record_foo_seen(option, opt_str, value, parser):
1278 parser.saw_foo = True
Neal Norwitz488609e2003-01-06 16:51:37 +00001279
1280parser.add_option("--foo", action="callback", callback=record_foo_seen)
1281\end{verbatim}
1282
Greg Wardb6f7fb72004-09-28 01:30:23 +00001283Of course, you could do that with the \code{store{\_}true} action.
Neal Norwitz488609e2003-01-06 16:51:37 +00001284
Greg Wardb6f7fb72004-09-28 01:30:23 +00001285
1286\subsubsection{Callback example 2: check option order\label{optparse-callback-example-2:-check-option-order}}
1287
1288Here's a slightly more interesting example: record the fact that
1289\code{"-a"} is seen, but blow up if it comes after \code{"-b"} in the
1290command-line.
Neal Norwitz488609e2003-01-06 16:51:37 +00001291\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001292def check_order(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001293 if parser.values.b:
1294 raise OptionValueError("can't use -a after -b")
1295 parser.values.a = 1
Greg Wardb6f7fb72004-09-28 01:30:23 +00001296[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001297parser.add_option("-a", action="callback", callback=check_order)
1298parser.add_option("-b", action="store_true", dest="b")
1299\end{verbatim}
1300
Neal Norwitz488609e2003-01-06 16:51:37 +00001301
Greg Wardb6f7fb72004-09-28 01:30:23 +00001302\subsubsection{Callback example 3: check option order (generalized)\label{optparse-callback-example-3:-check-option-order-(generalized)}}
1303
1304If you want to re-use this callback for several similar options (set a
1305flag, but blow up if \code{"-b"} has already been seen), it needs a bit of
1306work: the error message and the flag that it sets must be
1307generalized.
Neal Norwitz488609e2003-01-06 16:51:37 +00001308\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001309def check_order(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001310 if parser.values.b:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001311 raise OptionValueError("can't use %s after -b" % opt_str)
Neal Norwitz488609e2003-01-06 16:51:37 +00001312 setattr(parser.values, option.dest, 1)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001313[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001314parser.add_option("-a", action="callback", callback=check_order, dest='a')
1315parser.add_option("-b", action="store_true", dest="b")
1316parser.add_option("-c", action="callback", callback=check_order, dest='c')
1317\end{verbatim}
1318
Greg Wardb6f7fb72004-09-28 01:30:23 +00001319
1320\subsubsection{Callback example 4: check arbitrary condition\label{optparse-callback-example-4:-check-arbitrary-condition}}
1321
1322Of course, you could put any condition in there{---}you're not limited
Neal Norwitz488609e2003-01-06 16:51:37 +00001323to checking the values of already-defined options. For example, if
1324you have options that should not be called when the moon is full, all
1325you have to do is this:
Neal Norwitz488609e2003-01-06 16:51:37 +00001326\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001327def check_moon(option, opt_str, value, parser):
1328 if is_moon_full():
1329 raise OptionValueError("%s option invalid when moon is full"
1330 % opt_str)
Neal Norwitz488609e2003-01-06 16:51:37 +00001331 setattr(parser.values, option.dest, 1)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001332[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001333parser.add_option("--foo",
1334 action="callback", callback=check_moon, dest="foo")
1335\end{verbatim}
1336
Greg Wardb6f7fb72004-09-28 01:30:23 +00001337(The definition of \code{is{\_}moon{\_}full()} is left as an exercise for the
Neal Norwitz488609e2003-01-06 16:51:37 +00001338reader.)
1339
Greg Wardb6f7fb72004-09-28 01:30:23 +00001340
1341\subsubsection{Callback example 5: fixed arguments\label{optparse-callback-example-5:-fixed-arguments}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001342
1343Things get slightly more interesting when you define callback options
1344that take a fixed number of arguments. Specifying that a callback
Greg Wardb6f7fb72004-09-28 01:30:23 +00001345option takes arguments is similar to defining a \code{store} or \code{append}
1346option: if you define \member{type}, then the option takes one argument that
1347must be convertible to that type; if you further define \code{nargs}, then
1348the option takes \code{nargs} arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +00001349
Greg Wardb6f7fb72004-09-28 01:30:23 +00001350Here's an example that just emulates the standard \code{store} action:
Neal Norwitz488609e2003-01-06 16:51:37 +00001351\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001352def store_value(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001353 setattr(parser.values, option.dest, value)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001354[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001355parser.add_option("--foo",
1356 action="callback", callback=store_value,
1357 type="int", nargs=3, dest="foo")
1358\end{verbatim}
1359
Greg Wardb6f7fb72004-09-28 01:30:23 +00001360Note that \module{optparse} takes care of consuming 3 arguments and converting them
1361to integers for you; all you have to do is store them. (Or whatever;
1362obviously you don't need a callback for this example.)
Neal Norwitz488609e2003-01-06 16:51:37 +00001363
Greg Wardb6f7fb72004-09-28 01:30:23 +00001364
1365\subsubsection{Callback example 6: variable arguments\label{optparse-callback-example-6:-variable-arguments}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001366
1367Things get hairy when you want an option to take a variable number of
Greg Wardb6f7fb72004-09-28 01:30:23 +00001368arguments. For this case, you must write a callback, as \module{optparse} doesn't
1369provide any built-in capabilities for it. And you have to deal with
1370certain intricacies of conventional \UNIX{} command-line parsing that \module{optparse}
1371normally handles for you. In particular, callbacks should implement
1372the conventional rules for bare \code{"-{}-"} and \code{"-"} arguments:
Neal Norwitz488609e2003-01-06 16:51:37 +00001373\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001374\item {}
1375either \code{"-{}-"} or \code{"-"} can be option arguments
Neal Norwitz488609e2003-01-06 16:51:37 +00001376
Greg Wardb6f7fb72004-09-28 01:30:23 +00001377\item {}
1378bare \code{"-{}-"} (if not the argument to some option): halt command-line
1379processing and discard the \code{"-{}-"}
Neal Norwitz488609e2003-01-06 16:51:37 +00001380
Greg Wardb6f7fb72004-09-28 01:30:23 +00001381\item {}
1382bare \code{"-"} (if not the argument to some option): halt command-line
1383processing but keep the \code{"-"} (append it to \code{parser.largs})
1384
Neal Norwitz488609e2003-01-06 16:51:37 +00001385\end{itemize}
1386
1387If you want an option that takes a variable number of arguments, there
1388are several subtle, tricky issues to worry about. The exact
1389implementation you choose will be based on which trade-offs you're
Greg Wardb6f7fb72004-09-28 01:30:23 +00001390willing to make for your application (which is why \module{optparse} doesn't support
1391this sort of thing directly).
Neal Norwitz488609e2003-01-06 16:51:37 +00001392
1393Nevertheless, here's a stab at a callback for an option with variable
1394arguments:
Neal Norwitz488609e2003-01-06 16:51:37 +00001395\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001396def vararg_callback(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001397 assert value is None
1398 done = 0
1399 value = []
1400 rargs = parser.rargs
1401 while rargs:
1402 arg = rargs[0]
1403
1404 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1405 # etc. Note that this also stops on "-3" or "-3.0", so if
1406 # your option takes numeric values, you will need to handle
1407 # this.
1408 if ((arg[:2] == "--" and len(arg) > 2) or
1409 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1410 break
1411 else:
1412 value.append(arg)
1413 del rargs[0]
1414
1415 setattr(parser.values, option.dest, value)
1416
Greg Wardb6f7fb72004-09-28 01:30:23 +00001417[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001418parser.add_option("-c", "--callback",
1419 action="callback", callback=varargs)
1420\end{verbatim}
1421
1422The main weakness with this particular implementation is that negative
Greg Wardb6f7fb72004-09-28 01:30:23 +00001423numbers in the arguments following \code{"-c"} will be interpreted as
1424further options (probably causing an error), rather than as arguments to
1425\code{"-c"}. Fixing this is left as an exercise for the reader.
1426% $Id$
Neal Norwitz488609e2003-01-06 16:51:37 +00001427