blob: 4ab325bc25dcfe32cfd5be675bc60f0072dddfd3 [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]}).
Greg Warde644a1b2004-10-01 01:16:39 +000072% $Id: intro.txt 413 2004-09-28 00:59:13Z greg $
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
Greg Warde644a1b2004-10-01 01:16:39 +0000178\subsubsection{What are options for?\label{optparse-what-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 Warde644a1b2004-10-01 01:16:39 +0000212\subsubsection{What are positional arguments for?\label{optparse-what-positional-arguments-for}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000213
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.
Greg Warde644a1b2004-10-01 01:16:39 +0000235% $Id: tao.txt 413 2004-09-28 00:59:13Z greg $
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
Greg Warde644a1b2004-10-01 01:16:39 +0000305\subsubsection{Understanding option actions\label{optparse-understanding-option-actions}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000306
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
Greg Warde644a1b2004-10-01 01:16:39 +0000317\subsubsection{The store action\label{optparse-store-action}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000318
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 Warde644a1b2004-10-01 01:16:39 +0000377\subsubsection{Handling boolean (flag) options\label{optparse-handling-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 Warde644a1b2004-10-01 01:16:39 +0000390default values{---}see 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
Greg Warde644a1b2004-10-01 01:16:39 +0000411These are covered in section~\ref{optparse-reference-guide}, Reference Guide and section~\ref{optparse-option-callbacks}, Option Callbacks.
Greg Wardb6f7fb72004-09-28 01:30:23 +0000412
413
414\subsubsection{Default values\label{optparse-default-values}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000415
416All of the above examples involve setting some variable (the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000417``destination'') when certain command-line options are seen. What happens
418if those options are never seen? Since we didn't supply any defaults,
419they are all set to \code{None}. This is usually fine, but sometimes you
420want more control. \module{optparse} lets you supply a default value for each
421destination, which is assigned before the command line is parsed.
Neal Norwitz488609e2003-01-06 16:51:37 +0000422
Greg Wardb6f7fb72004-09-28 01:30:23 +0000423First, consider the verbose/quiet example. If we want \module{optparse} to set
424\var{verbose} to \code{True} unless \code{"-q"} is seen, then we can do this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000425\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000426parser.add_option("-v", action="store_true", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000427parser.add_option("-q", action="store_false", dest="verbose")
428\end{verbatim}
429
Greg Wardb6f7fb72004-09-28 01:30:23 +0000430Since default values apply to the \emph{destination} rather than to any
431particular option, and these two options happen to have the same
432destination, this is exactly equivalent:
Neal Norwitz488609e2003-01-06 16:51:37 +0000433\begin{verbatim}
434parser.add_option("-v", action="store_true", dest="verbose")
Greg Ward1f535172003-05-03 20:13:08 +0000435parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000436\end{verbatim}
437
Neal Norwitz488609e2003-01-06 16:51:37 +0000438Consider this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000439\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000440parser.add_option("-v", action="store_true", dest="verbose", default=False)
441parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000442\end{verbatim}
443
Greg Wardb6f7fb72004-09-28 01:30:23 +0000444Again, the default value for \var{verbose} will be \code{True}: the last
Greg Wardd7231282003-05-03 21:22:58 +0000445default value supplied for any particular destination is the one that
446counts.
Neal Norwitz488609e2003-01-06 16:51:37 +0000447
Greg Wardb6f7fb72004-09-28 01:30:23 +0000448A clearer way to specify default values is the \method{set{\_}defaults()}
449method of OptionParser, which you can call at any time before calling
450\method{parse{\_}args()}:
451\begin{verbatim}
452parser.set_defaults(verbose=True)
453parser.add_option(...)
454(options, args) = parser.parse_args()
455\end{verbatim}
456
457As before, the last value specified for a given option destination is
458the one that counts. For clarity, try to use one method or the other of
459setting default values, not both.
460
461
Neal Norwitz488609e2003-01-06 16:51:37 +0000462\subsubsection{Generating help\label{optparse-generating-help}}
463
Greg Wardb6f7fb72004-09-28 01:30:23 +0000464\module{optparse}'s ability to generate help and usage text automatically is useful
465for creating user-friendly command-line interfaces. All you have to do
466is supply a \member{help} value for each option, and optionally a short usage
467message for your whole program. Here's an OptionParser populated with
468user-friendly (documented) options:
Neal Norwitz488609e2003-01-06 16:51:37 +0000469\begin{verbatim}
470usage = "usage: %prog [options] arg1 arg2"
471parser = OptionParser(usage=usage)
472parser.add_option("-v", "--verbose",
Greg Ward1f535172003-05-03 20:13:08 +0000473 action="store_true", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +0000474 help="make lots of noise [default]")
475parser.add_option("-q", "--quiet",
476 action="store_false", dest="verbose",
477 help="be vewwy quiet (I'm hunting wabbits)")
Greg Wardb6f7fb72004-09-28 01:30:23 +0000478parser.add_option("-f", "--filename",
Neal Norwitz488609e2003-01-06 16:51:37 +0000479 metavar="FILE", help="write output to FILE"),
480parser.add_option("-m", "--mode",
481 default="intermediate",
Greg Wardb6f7fb72004-09-28 01:30:23 +0000482 help="interaction mode: novice, intermediate, "
483 "or expert [default: %default]")
Neal Norwitz488609e2003-01-06 16:51:37 +0000484\end{verbatim}
485
Greg Wardb6f7fb72004-09-28 01:30:23 +0000486If \module{optparse} encounters either \code{"-h"} or \code{"-{}-help"} on the command-line,
487or if you just call \method{parser.print{\_}help()}, it prints the following to
488standard output:
Neal Norwitz488609e2003-01-06 16:51:37 +0000489\begin{verbatim}
490usage: <yourscript> [options] arg1 arg2
491
492options:
Greg Wardb6f7fb72004-09-28 01:30:23 +0000493 -h, --help show this help message and exit
494 -v, --verbose make lots of noise [default]
495 -q, --quiet be vewwy quiet (I'm hunting wabbits)
496 -f FILE, --filename=FILE
497 write output to FILE
498 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
499 expert [default: intermediate]
Neal Norwitz488609e2003-01-06 16:51:37 +0000500\end{verbatim}
501
Greg Wardb6f7fb72004-09-28 01:30:23 +0000502(If the help output is triggered by a help option, \module{optparse} exits after
503printing the help text.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000504
Greg Wardb6f7fb72004-09-28 01:30:23 +0000505There's a lot going on here to help \module{optparse} generate the best possible
506help message:
Neal Norwitz488609e2003-01-06 16:51:37 +0000507\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000508\item {}
509the script defines its own usage message:
Neal Norwitz488609e2003-01-06 16:51:37 +0000510\begin{verbatim}
511usage = "usage: %prog [options] arg1 arg2"
512\end{verbatim}
513
Greg Wardb6f7fb72004-09-28 01:30:23 +0000514\module{optparse} expands \code{"{\%}prog"} in the usage string to the name of the current
515program, i.e. \code{os.path.basename(sys.argv{[}0])}. The expanded string
516is then printed before the detailed option help.
Neal Norwitz488609e2003-01-06 16:51:37 +0000517
Greg Wardb6f7fb72004-09-28 01:30:23 +0000518If you don't supply a usage string, \module{optparse} uses a bland but sensible
519default: ``\code{usage: {\%}prog {[}options]"}, which is fine if your script
520doesn't take any positional arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +0000521
Greg Wardb6f7fb72004-09-28 01:30:23 +0000522\item {}
523every option defines a help string, and doesn't worry about line-
524wrapping{---}\module{optparse} takes care of wrapping lines and making the
525help output look good.
Neal Norwitz488609e2003-01-06 16:51:37 +0000526
Greg Wardb6f7fb72004-09-28 01:30:23 +0000527\item {}
528options that take a value indicate this fact in their
Neal Norwitz488609e2003-01-06 16:51:37 +0000529automatically-generated help message, e.g. for the ``mode'' option:
Neal Norwitz488609e2003-01-06 16:51:37 +0000530\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000531-m MODE, --mode=MODE
Neal Norwitz488609e2003-01-06 16:51:37 +0000532\end{verbatim}
533
534Here, ``MODE'' is called the meta-variable: it stands for the argument
Greg Wardb6f7fb72004-09-28 01:30:23 +0000535that the user is expected to supply to \programopt{-m}/\longprogramopt{mode}. By default,
536\module{optparse} converts the destination variable name to uppercase and uses
537that for the meta-variable. Sometimes, that's not what you want{---}for example, the \longprogramopt{filename} option explicitly sets
538\code{metavar="FILE"}, resulting in this automatically-generated option
539description:
Neal Norwitz488609e2003-01-06 16:51:37 +0000540\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000541-f FILE, --filename=FILE
Neal Norwitz488609e2003-01-06 16:51:37 +0000542\end{verbatim}
543
544This is important for more than just saving space, though: the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000545manually written help text uses the meta-variable ``FILE'' to clue the
546user in that there's a connection between the semi-formal syntax ``-f
547FILE'' and the informal semantic description ``write output to FILE''.
548This is a simple but effective way to make your help text a lot
549clearer and more useful for end users.
550
551\item {}
552options that have a default value can include \code{{\%}default} in
553the help string{---}\module{optparse} will replace it with \function{str()} of the
554option's default value. If an option has no default value (or the
555default value is \code{None}), \code{{\%}default} expands to \code{none}.
556
Neal Norwitz488609e2003-01-06 16:51:37 +0000557\end{itemize}
558
Fred Drakecf6d74a2003-04-18 15:50:13 +0000559
Greg Warde644a1b2004-10-01 01:16:39 +0000560\subsubsection{Printing a version string\label{optparse-printing-version-string}}
Fred Drakecf6d74a2003-04-18 15:50:13 +0000561
Greg Wardb6f7fb72004-09-28 01:30:23 +0000562Similar to the brief usage string, \module{optparse} can also print a version string
563for your program. You have to supply the string as the \code{version}
564argument to OptionParser:
Neal Norwitz488609e2003-01-06 16:51:37 +0000565\begin{verbatim}
566parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
567\end{verbatim}
568
Greg Wardb6f7fb72004-09-28 01:30:23 +0000569Note that \code{"{\%}prog"} is expanded just like it is in \var{usage}. Apart
570from that, \code{version} can contain anything you like. When you supply
571it, \module{optparse} automatically adds a \code{"-{}-version"} option to your parser.
572If it encounters this option on the command line, it expands your
573\code{version} string (by replacing \code{"{\%}prog"}), prints it to stdout, and
574exits.
Neal Norwitz488609e2003-01-06 16:51:37 +0000575
Greg Wardb6f7fb72004-09-28 01:30:23 +0000576For example, if your script is called \code{/usr/bin/foo}:
Neal Norwitz488609e2003-01-06 16:51:37 +0000577\begin{verbatim}
578$ /usr/bin/foo --version
579foo 1.0
Greg Wardb6f7fb72004-09-28 01:30:23 +0000580\end{verbatim}
581
Neal Norwitz488609e2003-01-06 16:51:37 +0000582
Greg Warde644a1b2004-10-01 01:16:39 +0000583\subsubsection{How \module{optparse} handles errors\label{optparse-how-optik-handles-errors}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000584
Greg Wardb6f7fb72004-09-28 01:30:23 +0000585There are two broad classes of errors that \module{optparse} has to worry about:
586programmer errors and user errors. Programmer errors are usually
587erroneous calls to \code{parse.add{\_}option()}, e.g. invalid option strings,
588unknown option attributes, missing option attributes, etc. These are
589dealt with in the usual way: raise an exception (either
590\code{optparse.OptionError} or \code{TypeError}) and let the program crash.
Neal Norwitz488609e2003-01-06 16:51:37 +0000591
Greg Wardb6f7fb72004-09-28 01:30:23 +0000592Handling user errors is much more important, since they are guaranteed
593to happen no matter how stable your code is. \module{optparse} can automatically
594detect some user errors, such as bad option arguments (passing \code{"-n
5954x"} where \programopt{-n} takes an integer argument), missing arguments
596(\code{"-n"} at the end of the command line, where \programopt{-n} takes an argument
597of any type). Also, you can call \code{parser.error()} to signal an
598application-defined error condition:
599\begin{verbatim}
600(options, args) = parser.parse_args()
601[...]
602if options.a and options.b:
603 parser.error("options -a and -b are mutually exclusive")
604\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000605
Greg Wardb6f7fb72004-09-28 01:30:23 +0000606In either case, \module{optparse} handles the error the same way: it prints the
607program's usage message and an error message to standard error and
608exits with error status 2.
Neal Norwitz488609e2003-01-06 16:51:37 +0000609
Greg Wardb6f7fb72004-09-28 01:30:23 +0000610Consider the first example above, where the user passes \code{"4x"} to an
611option that takes an integer:
612\begin{verbatim}
613$ /usr/bin/foo -n 4x
614usage: foo [options]
Neal Norwitz488609e2003-01-06 16:51:37 +0000615
Greg Wardb6f7fb72004-09-28 01:30:23 +0000616foo: error: option -n: invalid integer value: '4x'
617\end{verbatim}
618
619Or, where the user fails to pass a value at all:
620\begin{verbatim}
621$ /usr/bin/foo -n
622usage: foo [options]
623
624foo: error: -n option requires an argument
625\end{verbatim}
626
627\module{optparse}-generated error messages take care always to mention the option
628involved in the error; be sure to do the same when calling
629\code{parser.error()} from your application code.
630
631If \module{optparse}'s default error-handling behaviour does not suite your needs,
632you'll need to subclass OptionParser and override \code{exit()} and/or
633\method{error()}.
634
635
636\subsubsection{Putting it all together\label{optparse-putting-it-all-together}}
637
638Here's what \module{optparse}-based scripts usually look like:
Neal Norwitz488609e2003-01-06 16:51:37 +0000639\begin{verbatim}
640from optparse import OptionParser
Greg Wardd7231282003-05-03 21:22:58 +0000641[...]
642def main():
Greg Wardb6f7fb72004-09-28 01:30:23 +0000643 usage = "usage: %prog [options] arg"
Neal Norwitz488609e2003-01-06 16:51:37 +0000644 parser = OptionParser(usage)
Greg Wardb6f7fb72004-09-28 01:30:23 +0000645 parser.add_option("-f", "--file", dest="filename",
Neal Norwitz488609e2003-01-06 16:51:37 +0000646 help="read data from FILENAME")
647 parser.add_option("-v", "--verbose",
648 action="store_true", dest="verbose")
649 parser.add_option("-q", "--quiet",
650 action="store_false", dest="verbose")
Greg Wardb6f7fb72004-09-28 01:30:23 +0000651 [...]
652 (options, args) = parser.parse_args()
653 if len(args) != 1:
Neal Norwitz488609e2003-01-06 16:51:37 +0000654 parser.error("incorrect number of arguments")
Neal Norwitz488609e2003-01-06 16:51:37 +0000655 if options.verbose:
Johannes Gijsbersc9c37ca2004-09-11 15:47:30 +0000656 print "reading %s..." % options.filename
Greg Wardb6f7fb72004-09-28 01:30:23 +0000657 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000658
659if __name__ == "__main__":
660 main()
661\end{verbatim}
Greg Warde644a1b2004-10-01 01:16:39 +0000662% $Id: tutorial.txt 415 2004-09-30 02:26:17Z greg $
Neal Norwitz488609e2003-01-06 16:51:37 +0000663
Neal Norwitz488609e2003-01-06 16:51:37 +0000664
Greg Wardb6f7fb72004-09-28 01:30:23 +0000665\subsection{Reference Guide\label{optparse-reference-guide}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000666
Neal Norwitz488609e2003-01-06 16:51:37 +0000667
Greg Warde644a1b2004-10-01 01:16:39 +0000668\subsubsection{Populating the parser\label{optparse-populating-parser}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000669
670There are several ways to populate the parser with options. The
671preferred way is by using \code{OptionParser.add{\_}option()}, as shown in
Greg Warde644a1b2004-10-01 01:16:39 +0000672section~\ref{optparse-tutorial}, the tutorial. \method{add{\_}option()} can be called in one of two
Greg Wardb6f7fb72004-09-28 01:30:23 +0000673ways:
674\begin{itemize}
675\item {}
676pass it an Option instance (as returned by \function{make{\_}option()})
677
678\item {}
679pass it any combination of positional and keyword arguments that are
680acceptable to \function{make{\_}option()} (i.e., to the Option constructor),
681and it will create the Option instance for you
682
683\end{itemize}
684
685The other alternative is to pass a list of pre-constructed Option
686instances to the OptionParser constructor, as in:
Neal Norwitz488609e2003-01-06 16:51:37 +0000687\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000688option_list = [
Neal Norwitz488609e2003-01-06 16:51:37 +0000689 make_option("-f", "--filename",
690 action="store", type="string", dest="filename"),
691 make_option("-q", "--quiet",
Greg Wardb6f7fb72004-09-28 01:30:23 +0000692 action="store_false", dest="verbose"),
693 ]
Neal Norwitz488609e2003-01-06 16:51:37 +0000694parser = OptionParser(option_list=option_list)
695\end{verbatim}
696
Greg Wardb6f7fb72004-09-28 01:30:23 +0000697(\function{make{\_}option()} is a factory function for creating Option instances;
698currently it is an alias for the Option constructor. A future version
699of \module{optparse} may split Option into several classes, and \function{make{\_}option()}
700will pick the right class to instantiate. Do not instantiate Option
701directly.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000702
Neal Norwitz488609e2003-01-06 16:51:37 +0000703
704\subsubsection{Defining options\label{optparse-defining-options}}
705
Greg Wardb6f7fb72004-09-28 01:30:23 +0000706Each Option instance represents a set of synonymous command-line option
Greg Ward961eda72004-11-12 01:20:17 +0000707strings, e.g. \programopt{-f} and \longprogramopt{file}. You can
Greg Wardb6f7fb72004-09-28 01:30:23 +0000708specify any number of short or long option strings, but you must specify
709at least one overall option string.
710
711The canonical way to create an Option instance is by calling
712\function{make{\_}option()}, so that is what will be shown here. However, the
713most common and convenient way is to use \code{parser.add{\_}option()}. Note
714that \function{make{\_}option()} and \code{parser.add{\_}option()} have identical call
715signatures:
716\begin{verbatim}
717make_option(opt_str, ..., attr=value, ...)
718parser.add_option(opt_str, ..., attr=value, ...)
719\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000720
721To define an option with only a short option string:
Neal Norwitz488609e2003-01-06 16:51:37 +0000722\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000723make_option("-f", attr=value, ...)
Neal Norwitz488609e2003-01-06 16:51:37 +0000724\end{verbatim}
725
726And to define an option with only a long option string:
Neal Norwitz488609e2003-01-06 16:51:37 +0000727\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000728make_option("--foo", attr=value, ...)
Neal Norwitz488609e2003-01-06 16:51:37 +0000729\end{verbatim}
730
Greg Wardb6f7fb72004-09-28 01:30:23 +0000731The \code{attr=value} keyword arguments define option attributes,
732i.e. attributes of the Option object. The most important option
733attribute is \member{action}, and it largely determines what other attributes
734are relevant or required. If you pass irrelevant option attributes, or
735fail to pass required ones, \module{optparse} raises an OptionError exception
736explaining your mistake.
Neal Norwitz488609e2003-01-06 16:51:37 +0000737
Greg Wardb6f7fb72004-09-28 01:30:23 +0000738An options's \emph{action} determines what \module{optparse} does when it encounters
739this option on the command-line. The actions hard-coded into \module{optparse} are:
740\begin{description}
741\item[\code{store}]
742store this option's argument {[}default]
743\item[\code{store{\_}const}]
744store a constant value
745\item[\code{store{\_}true}]
746store a true value
747\item[\code{store{\_}false}]
748store a false value
749\item[\code{append}]
750append this option's argument to a list
751\item[\code{count}]
752increment a counter by one
753\item[\code{callback}]
754call a specified function
755\item[\member{help}]
756print a usage message including all options and the
757documentation for them
758\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +0000759
Greg Wardb6f7fb72004-09-28 01:30:23 +0000760(If you don't supply an action, the default is \code{store}. For this
761action, you may also supply \member{type} and \member{dest} option attributes; see
Neal Norwitz488609e2003-01-06 16:51:37 +0000762below.)
763
764As you can see, most actions involve storing or updating a value
Greg Wardb6f7fb72004-09-28 01:30:23 +0000765somewhere. \module{optparse} always creates an instance of \code{optparse.Values}
766specifically for this purpose; we refer to this instance as \var{options}.
767Option arguments (and various other values) are stored as attributes of
768this object, according to the \member{dest} (destination) option attribute.
Neal Norwitz488609e2003-01-06 16:51:37 +0000769
Greg Wardb6f7fb72004-09-28 01:30:23 +0000770For example, when you call
Neal Norwitz488609e2003-01-06 16:51:37 +0000771\begin{verbatim}
772parser.parse_args()
773\end{verbatim}
774
Greg Wardb6f7fb72004-09-28 01:30:23 +0000775one of the first things \module{optparse} does is create the \var{options} object:
Neal Norwitz488609e2003-01-06 16:51:37 +0000776\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000777options = Values()
Neal Norwitz488609e2003-01-06 16:51:37 +0000778\end{verbatim}
779
Greg Wardb6f7fb72004-09-28 01:30:23 +0000780If one of the options in this parser is defined with
Neal Norwitz488609e2003-01-06 16:51:37 +0000781\begin{verbatim}
782make_option("-f", "--file", action="store", type="string", dest="filename")
783\end{verbatim}
784
785and the command-line being parsed includes any of the following:
Neal Norwitz488609e2003-01-06 16:51:37 +0000786\begin{verbatim}
787-ffoo
788-f foo
789--file=foo
790--file foo
791\end{verbatim}
792
Greg Wardb6f7fb72004-09-28 01:30:23 +0000793then \module{optparse}, on seeing the \programopt{-f} or \longprogramopt{file} option, will do the
794equivalent of
Neal Norwitz488609e2003-01-06 16:51:37 +0000795\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000796options.filename = "foo"
Neal Norwitz488609e2003-01-06 16:51:37 +0000797\end{verbatim}
798
Greg Wardb6f7fb72004-09-28 01:30:23 +0000799The \member{type} and \member{dest} option attributes are almost as important as
800\member{action}, but \member{action} is the only one that makes sense for \emph{all}
801options.
802
Neal Norwitz488609e2003-01-06 16:51:37 +0000803
Greg Warde644a1b2004-10-01 01:16:39 +0000804\subsubsection{Standard option actions\label{optparse-standard-option-actions}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000805
Greg Wardb6f7fb72004-09-28 01:30:23 +0000806The various option actions all have slightly different requirements and
807effects. Most actions have several relevant option attributes which you
808may specify to guide \module{optparse}'s behaviour; a few have required attributes,
809which you must specify for any option using that action.
810\begin{itemize}
811\item {}
812\code{store} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000813
Greg Wardb6f7fb72004-09-28 01:30:23 +0000814The option must be followed by an argument, which is
815converted to a value according to \member{type} and stored in
816\member{dest}. If \code{nargs} {\textgreater} 1, multiple arguments will be consumed
817from the command line; all will be converted according to
818\member{type} and stored to \member{dest} as a tuple. See the ``Option
819types'' section below.
Neal Norwitz488609e2003-01-06 16:51:37 +0000820
Greg Wardb6f7fb72004-09-28 01:30:23 +0000821If \code{choices} is supplied (a list or tuple of strings), the type
822defaults to \code{choice}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000823
Greg Wardb6f7fb72004-09-28 01:30:23 +0000824If \member{type} is not supplied, it defaults to \code{string}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000825
Greg Wardb6f7fb72004-09-28 01:30:23 +0000826If \member{dest} is not supplied, \module{optparse} derives a destination from the
827first long option string (e.g., \code{"-{}-foo-bar"} implies \code{foo{\_}bar}).
828If there are no long option strings, \module{optparse} derives a destination from
829the first short option string (e.g., \code{"-f"} implies \code{f}).
Neal Norwitz488609e2003-01-06 16:51:37 +0000830
831Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000832\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000833parser.add_option("-f")
834parser.add_option("-p", type="float", nargs=3, dest="point")
Neal Norwitz488609e2003-01-06 16:51:37 +0000835\end{verbatim}
836
Greg Wardb6f7fb72004-09-28 01:30:23 +0000837As it parses the command line
Neal Norwitz488609e2003-01-06 16:51:37 +0000838\begin{verbatim}
839-f foo.txt -p 1 -3.5 4 -fbar.txt
840\end{verbatim}
841
Greg Wardb6f7fb72004-09-28 01:30:23 +0000842\module{optparse} will set
Neal Norwitz488609e2003-01-06 16:51:37 +0000843\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000844options.f = "foo.txt"
845options.point = (1.0, -3.5, 4.0)
846options.f = "bar.txt"
Neal Norwitz488609e2003-01-06 16:51:37 +0000847\end{verbatim}
848
Greg Wardb6f7fb72004-09-28 01:30:23 +0000849\item {}
850\code{store{\_}const} {[}required: \code{const}; relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000851
Greg Wardb6f7fb72004-09-28 01:30:23 +0000852The value \code{const} is stored in \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000853
854Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000855\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000856parser.add_option("-q", "--quiet",
857 action="store_const", const=0, dest="verbose")
858parser.add_option("-v", "--verbose",
859 action="store_const", const=1, dest="verbose")
860parser.add_option("--noisy",
861 action="store_const", const=2, dest="verbose")
Neal Norwitz488609e2003-01-06 16:51:37 +0000862\end{verbatim}
863
Greg Wardb6f7fb72004-09-28 01:30:23 +0000864If \code{"-{}-noisy"} is seen, \module{optparse} will set
Neal Norwitz488609e2003-01-06 16:51:37 +0000865\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000866options.verbose = 2
Neal Norwitz488609e2003-01-06 16:51:37 +0000867\end{verbatim}
868
Greg Wardb6f7fb72004-09-28 01:30:23 +0000869\item {}
870\code{store{\_}true} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000871
Greg Wardb6f7fb72004-09-28 01:30:23 +0000872A special case of \code{store{\_}const} that stores a true value
873to \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000874
Greg Wardb6f7fb72004-09-28 01:30:23 +0000875\item {}
876\code{store{\_}false} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000877
Greg Wardb6f7fb72004-09-28 01:30:23 +0000878Like \code{store{\_}true}, but stores a false value.
Neal Norwitz488609e2003-01-06 16:51:37 +0000879
880Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000881\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000882parser.add_option("--clobber", action="store_true", dest="clobber")
883parser.add_option("--no-clobber", action="store_false", dest="clobber")
Neal Norwitz488609e2003-01-06 16:51:37 +0000884\end{verbatim}
885
Greg Wardb6f7fb72004-09-28 01:30:23 +0000886\item {}
887\code{append} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000888
889The option must be followed by an argument, which is appended to the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000890list in \member{dest}. If no default value for \member{dest} is supplied, an
891empty list is automatically created when \module{optparse} first encounters this
892option on the command-line. If \code{nargs} {\textgreater} 1, multiple arguments are
893consumed, and a tuple of length \code{nargs} is appended to \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000894
Greg Wardb6f7fb72004-09-28 01:30:23 +0000895The defaults for \member{type} and \member{dest} are the same as for the
896\code{store} action.
Neal Norwitz488609e2003-01-06 16:51:37 +0000897
898Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000899\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000900parser.add_option("-t", "--tracks", action="append", type="int")
Neal Norwitz488609e2003-01-06 16:51:37 +0000901\end{verbatim}
902
Greg Wardb6f7fb72004-09-28 01:30:23 +0000903If \code{"-t3"} is seen on the command-line, \module{optparse} does the equivalent of:
Neal Norwitz488609e2003-01-06 16:51:37 +0000904\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000905options.tracks = []
906options.tracks.append(int("3"))
Neal Norwitz488609e2003-01-06 16:51:37 +0000907\end{verbatim}
908
Greg Wardb6f7fb72004-09-28 01:30:23 +0000909If, a little later on, \code{"-{}-tracks=4"} is seen, it does:
Neal Norwitz488609e2003-01-06 16:51:37 +0000910\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000911options.tracks.append(int("4"))
Neal Norwitz488609e2003-01-06 16:51:37 +0000912\end{verbatim}
913
Greg Wardb6f7fb72004-09-28 01:30:23 +0000914\item {}
915\code{count} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000916
Greg Wardb6f7fb72004-09-28 01:30:23 +0000917Increment the integer stored at \member{dest}. If no default value is
918supplied, \member{dest} is set to zero before being incremented the first
919time.
Neal Norwitz488609e2003-01-06 16:51:37 +0000920
921Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000922\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000923parser.add_option("-v", action="count", dest="verbosity")
Neal Norwitz488609e2003-01-06 16:51:37 +0000924\end{verbatim}
925
Greg Wardb6f7fb72004-09-28 01:30:23 +0000926The first time \code{"-v"} is seen on the command line, \module{optparse} does the
927equivalent of:
Neal Norwitz488609e2003-01-06 16:51:37 +0000928\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000929options.verbosity = 0
930options.verbosity += 1
Neal Norwitz488609e2003-01-06 16:51:37 +0000931\end{verbatim}
932
Greg Wardb6f7fb72004-09-28 01:30:23 +0000933Every subsequent occurrence of \code{"-v"} results in
Neal Norwitz488609e2003-01-06 16:51:37 +0000934\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000935options.verbosity += 1
Neal Norwitz488609e2003-01-06 16:51:37 +0000936\end{verbatim}
937
Greg Wardb6f7fb72004-09-28 01:30:23 +0000938\item {}
939\code{callback} {[}required: \code{callback};
940relevant: \member{type}, \code{nargs}, \code{callback{\_}args}, \code{callback{\_}kwargs}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000941
Greg Wardb6f7fb72004-09-28 01:30:23 +0000942Call the function specified by \code{callback}. The signature of
943this function should be
Neal Norwitz488609e2003-01-06 16:51:37 +0000944\begin{verbatim}
945func(option : Option,
946 opt : string,
947 value : any,
948 parser : OptionParser,
949 *args, **kwargs)
950\end{verbatim}
951
Greg Warde644a1b2004-10-01 01:16:39 +0000952See section~\ref{optparse-option-callbacks}, Option Callbacks for more detail.
Neal Norwitz488609e2003-01-06 16:51:37 +0000953
Greg Wardb6f7fb72004-09-28 01:30:23 +0000954\item {}
955\member{help}
Neal Norwitz488609e2003-01-06 16:51:37 +0000956
Greg Wardb6f7fb72004-09-28 01:30:23 +0000957Prints a complete help message for all the options in the
958current option parser. The help message is constructed from
959the \var{usage} string passed to OptionParser's constructor and
960the \member{help} string passed to every option.
Neal Norwitz488609e2003-01-06 16:51:37 +0000961
Greg Wardb6f7fb72004-09-28 01:30:23 +0000962If no \member{help} string is supplied for an option, it will still be
963listed in the help message. To omit an option entirely, use
964the special value \code{optparse.SUPPRESS{\_}HELP}.
965
966\module{optparse} automatically adds a \member{help} option to all OptionParsers, so
967you do not normally need to create one.
Neal Norwitz488609e2003-01-06 16:51:37 +0000968
969Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000970\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000971from optparse import OptionParser, SUPPRESS_HELP
Neal Norwitz488609e2003-01-06 16:51:37 +0000972
Greg Wardb6f7fb72004-09-28 01:30:23 +0000973parser = OptionParser()
974parser.add_option("-h", "--help", action="help"),
975parser.add_option("-v", action="store_true", dest="verbose",
976 help="Be moderately verbose")
977parser.add_option("--file", dest="filename",
978 help="Input file to read data from"),
979parser.add_option("--secret", help=SUPPRESS_HELP)
Neal Norwitz488609e2003-01-06 16:51:37 +0000980\end{verbatim}
981
Greg Wardb6f7fb72004-09-28 01:30:23 +0000982If \module{optparse} sees either \code{"-h"} or \code{"-{}-help"} on the command line, it
983will print something like the following help message to stdout
984(assuming \code{sys.argv{[}0]} is \code{"foo.py"}):
Neal Norwitz488609e2003-01-06 16:51:37 +0000985\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000986usage: foo.py [options]
Neal Norwitz488609e2003-01-06 16:51:37 +0000987
988options:
989 -h, --help Show this help message and exit
990 -v Be moderately verbose
991 --file=FILENAME Input file to read data from
992\end{verbatim}
993
994After printing the help message, \module{optparse} terminates your process
995with \code{sys.exit(0)}.
996
Greg Wardb6f7fb72004-09-28 01:30:23 +0000997\item {}
998\code{version}
Neal Norwitz488609e2003-01-06 16:51:37 +0000999
Greg Wardb6f7fb72004-09-28 01:30:23 +00001000Prints the version number supplied to the OptionParser to stdout and
1001exits. The version number is actually formatted and printed by the
1002\code{print{\_}version()} method of OptionParser. Generally only relevant
1003if the \code{version} argument is supplied to the OptionParser
1004constructor. As with \member{help} options, you will rarely create
1005\code{version} options, since \module{optparse} automatically adds them when needed.
1006
1007\end{itemize}
1008
Neal Norwitz488609e2003-01-06 16:51:37 +00001009
Greg Warde644a1b2004-10-01 01:16:39 +00001010\subsubsection{Standard option types\label{optparse-standard-option-types}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001011
Greg Wardb6f7fb72004-09-28 01:30:23 +00001012\module{optparse} has six built-in option types: \code{string}, \code{int}, \code{long},
1013\code{choice}, \code{float} and \code{complex}. If you need to add new option
1014types, see section~\ref{optparse-extending}, Extending \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001015
Greg Wardb6f7fb72004-09-28 01:30:23 +00001016Arguments to string options are not checked or converted in any way: the
1017text on the command line is stored in the destination (or passed to the
1018callback) as-is.
Neal Norwitz488609e2003-01-06 16:51:37 +00001019
Greg Wardb6f7fb72004-09-28 01:30:23 +00001020Integer arguments are passed to \code{int()} to convert them to Python
1021integers. If \code{int()} fails, so will \module{optparse}, although with a more
1022useful error message. (Internally, \module{optparse} raises OptionValueError;
1023OptionParser catches this exception higher up and terminates your
1024program with a useful error message.)
Neal Norwitz488609e2003-01-06 16:51:37 +00001025
Greg Wardb6f7fb72004-09-28 01:30:23 +00001026Likewise, \code{float} arguments are passed to \code{float()} for conversion,
1027\code{long} arguments to \code{long()}, and \code{complex} arguments to
1028\code{complex()}. Apart from that, they are handled identically to integer
1029arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +00001030
Greg Wardb6f7fb72004-09-28 01:30:23 +00001031\code{choice} options are a subtype of \code{string} options. The \code{choices}
1032option attribute (a sequence of strings) defines the set of allowed
1033option arguments. \code{optparse.option.check{\_}choice()} compares
1034user-supplied option arguments against this master list and raises
1035OptionValueError if an invalid string is given.
Neal Norwitz488609e2003-01-06 16:51:37 +00001036
Greg Wardb6f7fb72004-09-28 01:30:23 +00001037
Greg Warde644a1b2004-10-01 01:16:39 +00001038\subsubsection{Querying and manipulating your option parser\label{optparse-querying-manipulating-option-parser}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001039
1040Sometimes, it's useful to poke around your option parser and see what's
Greg Wardb6f7fb72004-09-28 01:30:23 +00001041there. OptionParser provides a couple of methods to help you out:
1042\begin{description}
1043\item[\code{has{\_}option(opt{\_}str)}]
1044Return true if the OptionParser has an option with
1045option string \code{opt{\_}str} (e.g., \code{"-q"} or \code{"-{}-verbose"}).
1046\item[\code{get{\_}option(opt{\_}str)}]
1047Returns the Option instance with the option string \code{opt{\_}str}, or
1048\code{None} if no options have that option string.
1049\item[\code{remove{\_}option(opt{\_}str)}]
1050If the OptionParser has an option corresponding to \code{opt{\_}str},
1051that option is removed. If that option provided any other
1052option strings, all of those option strings become invalid.
Neal Norwitz488609e2003-01-06 16:51:37 +00001053
Greg Wardb6f7fb72004-09-28 01:30:23 +00001054If \code{opt{\_}str} does not occur in any option belonging to this
1055OptionParser, raises ValueError.
1056\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001057
Neal Norwitz488609e2003-01-06 16:51:37 +00001058
Greg Wardb6f7fb72004-09-28 01:30:23 +00001059\subsubsection{Conflicts between options\label{optparse-conflicts-between-options}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001060
Greg Wardb6f7fb72004-09-28 01:30:23 +00001061If you're not careful, it's easy to define options with conflicting
1062option strings:
Neal Norwitz488609e2003-01-06 16:51:37 +00001063\begin{verbatim}
1064parser.add_option("-n", "--dry-run", ...)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001065[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001066parser.add_option("-n", "--noisy", ...)
Neal Norwitz488609e2003-01-06 16:51:37 +00001067\end{verbatim}
1068
Greg Wardb6f7fb72004-09-28 01:30:23 +00001069(This is particularly true if you've defined your own OptionParser
1070subclass with some standard options.)
Neal Norwitz488609e2003-01-06 16:51:37 +00001071
Greg Wardb6f7fb72004-09-28 01:30:23 +00001072Every time you add an option, \module{optparse} checks for conflicts with existing
1073options. If it finds any, it invokes the current conflict-handling
1074mechanism. You can set the conflict-handling mechanism either in the
1075constructor:
Neal Norwitz488609e2003-01-06 16:51:37 +00001076\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001077parser = OptionParser(..., conflict_handler="...")
Neal Norwitz488609e2003-01-06 16:51:37 +00001078\end{verbatim}
1079
Greg Wardb6f7fb72004-09-28 01:30:23 +00001080or with a separate call:
1081\begin{verbatim}
1082parser.set_conflict_handler("...")
1083\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +00001084
Greg Wardb6f7fb72004-09-28 01:30:23 +00001085The available conflict-handling mechanisms are:
1086\begin{quote}
1087\begin{description}
1088\item[\code{error} (default)]
1089assume option conflicts are a programming error and raise
1090OptionConflictError
1091\item[\code{resolve}]
1092resolve option conflicts intelligently (see below)
1093\end{description}
1094\end{quote}
Neal Norwitz488609e2003-01-06 16:51:37 +00001095
Greg Wardb6f7fb72004-09-28 01:30:23 +00001096As an example, let's define an OptionParser that resolves conflicts
1097intelligently and add conflicting options to it:
Neal Norwitz488609e2003-01-06 16:51:37 +00001098\begin{verbatim}
1099parser = OptionParser(conflict_handler="resolve")
Greg Wardb6f7fb72004-09-28 01:30:23 +00001100parser.add_option("-n", "--dry-run", ..., help="do no harm")
1101parser.add_option("-n", "--noisy", ..., help="be noisy")
Neal Norwitz488609e2003-01-06 16:51:37 +00001102\end{verbatim}
1103
Neal Norwitz488609e2003-01-06 16:51:37 +00001104At this point, \module{optparse} detects that a previously-added option is already
Greg Wardb6f7fb72004-09-28 01:30:23 +00001105using the \code{"-n"} option string. Since \code{conflict{\_}handler} is
1106\code{"resolve"}, it resolves the situation by removing \code{"-n"} from the
1107earlier option's list of option strings. Now \code{"-{}-dry-run"} is the
1108only way for the user to activate that option. If the user asks for
1109help, the help message will reflect that:
Neal Norwitz488609e2003-01-06 16:51:37 +00001110\begin{verbatim}
1111options:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001112 --dry-run do no harm
1113 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001114 -n, --noisy be noisy
1115\end{verbatim}
1116
Greg Wardb6f7fb72004-09-28 01:30:23 +00001117It's possible to whittle away the option strings for a previously-added
1118option until there are none left, and the user has no way of invoking
1119that option from the command-line. In that case, \module{optparse} removes that
1120option completely, so it doesn't show up in help text or anywhere else.
1121Carrying on with our existing OptionParser:
Neal Norwitz488609e2003-01-06 16:51:37 +00001122\begin{verbatim}
1123parser.add_option("--dry-run", ..., help="new dry-run option")
1124\end{verbatim}
1125
Greg Wardb6f7fb72004-09-28 01:30:23 +00001126At this point, the original \programopt{-n/-{}-dry-run} option is no longer
1127accessible, so \module{optparse} removes it, leaving this help text:
Neal Norwitz488609e2003-01-06 16:51:37 +00001128\begin{verbatim}
1129options:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001130 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001131 -n, --noisy be noisy
1132 --dry-run new dry-run option
1133\end{verbatim}
Greg Warde644a1b2004-10-01 01:16:39 +00001134% $Id: reference.txt 415 2004-09-30 02:26:17Z greg $
Neal Norwitz488609e2003-01-06 16:51:37 +00001135
Neal Norwitz488609e2003-01-06 16:51:37 +00001136
Greg Wardb6f7fb72004-09-28 01:30:23 +00001137\subsection{Option Callbacks\label{optparse-option-callbacks}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001138
Greg Wardb6f7fb72004-09-28 01:30:23 +00001139When \module{optparse}'s built-in actions and types aren't quite enough for your
1140needs, you have two choices: extend \module{optparse} or define a callback option.
1141Extending \module{optparse} is more general, but overkill for a lot of simple
1142cases. Quite often a simple callback is all you need.
Neal Norwitz488609e2003-01-06 16:51:37 +00001143
Greg Wardb6f7fb72004-09-28 01:30:23 +00001144There are two steps to defining a callback option:
1145\begin{itemize}
1146\item {}
1147define the option itself using the \code{callback} action
Neal Norwitz488609e2003-01-06 16:51:37 +00001148
Greg Wardb6f7fb72004-09-28 01:30:23 +00001149\item {}
1150write the callback; this is a function (or method) that
1151takes at least four arguments, as described below
1152
1153\end{itemize}
1154
1155
Greg Warde644a1b2004-10-01 01:16:39 +00001156\subsubsection{Defining a callback option\label{optparse-defining-callback-option}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001157
1158As always, the easiest way to define a callback option is by using the
1159\code{parser.add{\_}option()} method. Apart from \member{action}, the only option
1160attribute you must specify is \code{callback}, the function to call:
Neal Norwitz488609e2003-01-06 16:51:37 +00001161\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001162parser.add_option("-c", action="callback", callback=my_callback)
Neal Norwitz488609e2003-01-06 16:51:37 +00001163\end{verbatim}
1164
Greg Wardb6f7fb72004-09-28 01:30:23 +00001165\code{callback} is a function (or other callable object), so you must have
1166already defined \code{my{\_}callback()} when you create this callback option.
1167In this simple case, \module{optparse} doesn't even know if \programopt{-c} takes any
1168arguments, which usually means that the option takes no arguments{---}the
1169mere presence of \programopt{-c} on the command-line is all it needs to know. In
1170some circumstances, though, you might want your callback to consume an
1171arbitrary number of command-line arguments. This is where writing
1172callbacks gets tricky; it's covered later in this section.
1173
1174\module{optparse} always passes four particular arguments to your callback, and it
1175will only pass additional arguments if you specify them via
1176\code{callback{\_}args} and \code{callback{\_}kwargs}. Thus, the minimal callback
1177function signature is:
1178\begin{verbatim}
1179def my_callback(option, opt, value, parser):
1180\end{verbatim}
1181
1182The four arguments to a callback are described below.
Neal Norwitz488609e2003-01-06 16:51:37 +00001183
1184There are several other option attributes that you can supply when you
Greg Wardb6f7fb72004-09-28 01:30:23 +00001185define a callback option:
1186\begin{description}
1187\item[\member{type}]
1188has its usual meaning: as with the \code{store} or \code{append} actions,
1189it instructs \module{optparse} to consume one argument and convert it to
1190\member{type}. Rather than storing the converted value(s) anywhere,
1191though, \module{optparse} passes it to your callback function.
1192\item[\code{nargs}]
1193also has its usual meaning: if it is supplied and {\textgreater} 1, \module{optparse} will
1194consume \code{nargs} arguments, each of which must be convertible to
1195\member{type}. It then passes a tuple of converted values to your
1196callback.
1197\item[\code{callback{\_}args}]
1198a tuple of extra positional arguments to pass to the callback
1199\item[\code{callback{\_}kwargs}]
1200a dictionary of extra keyword arguments to pass to the callback
1201\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001202
Neal Norwitz488609e2003-01-06 16:51:37 +00001203
Greg Warde644a1b2004-10-01 01:16:39 +00001204\subsubsection{How callbacks are called\label{optparse-how-callbacks-called}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001205
1206All callbacks are called as follows:
Neal Norwitz488609e2003-01-06 16:51:37 +00001207\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001208func(option, opt_str, value, parser, *args, **kwargs)
Neal Norwitz488609e2003-01-06 16:51:37 +00001209\end{verbatim}
1210
1211where
Greg Wardb6f7fb72004-09-28 01:30:23 +00001212\begin{description}
1213\item[\code{option}]
1214is the Option instance that's calling the callback
1215\item[\code{opt{\_}str}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001216is the option string seen on the command-line that's triggering the
Greg Wardb6f7fb72004-09-28 01:30:23 +00001217callback. (If an abbreviated long option was used, \code{opt{\_}str} will
1218be the full, canonical option string{---}e.g. if the user puts
1219\code{"-{}-foo"} on the command-line as an abbreviation for
1220\code{"-{}-foobar"}, then \code{opt{\_}str} will be \code{"-{}-foobar"}.)
1221\item[\code{value}]
1222is the argument to this option seen on the command-line. \module{optparse} will
1223only expect an argument if \member{type} is set; the type of \code{value}
1224will be the type implied by the option's type. If \member{type} for this
1225option is \code{None} (no argument expected), then \code{value} will be
1226\code{None}. If \code{nargs} {\textgreater} 1, \code{value} will be a tuple of values of
1227the appropriate type.
1228\item[\code{parser}]
1229is the OptionParser instance driving the whole thing, mainly
1230useful because you can access some other interesting data through
1231its instance attributes:
1232\begin{description}
1233\item[\code{parser.largs}]
1234the current list of leftover arguments, ie. arguments that have
1235been consumed but are neither options nor option arguments.
1236Feel free to modify \code{parser.largs}, e.g. by adding more
1237arguments to it. (This list will become \var{args}, the second
1238return value of \method{parse{\_}args()}.)
1239\item[\code{parser.rargs}]
1240the current list of remaining arguments, ie. with \code{opt{\_}str} and
1241\code{value} (if applicable) removed, and only the arguments
1242following them still there. Feel free to modify
1243\code{parser.rargs}, e.g. by consuming more arguments.
1244\item[\code{parser.values}]
1245the object where option values are by default stored (an
1246instance of optparse.OptionValues). This lets callbacks use the
1247same mechanism as the rest of \module{optparse} for storing option values;
1248you don't need to mess around with globals or closures. You can
1249also access or modify the value(s) of any options already
1250encountered on the command-line.
1251\end{description}
Raymond Hettinger79e05312004-12-31 01:07:27 +00001252\item[\code{args}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001253is a tuple of arbitrary positional arguments supplied via the
Greg Wardb6f7fb72004-09-28 01:30:23 +00001254\code{callback{\_}args} option attribute.
1255\item[\code{kwargs}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001256is a dictionary of arbitrary keyword arguments supplied via
Greg Wardb6f7fb72004-09-28 01:30:23 +00001257\code{callback{\_}kwargs}.
1258\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001259
Neal Norwitz488609e2003-01-06 16:51:37 +00001260
Greg Warde644a1b2004-10-01 01:16:39 +00001261\subsubsection{Raising errors in a callback\label{optparse-raising-errors-in-callback}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001262
Greg Wardb6f7fb72004-09-28 01:30:23 +00001263The callback function should raise OptionValueError if there are any
1264problems with the option or its argument(s). \module{optparse} catches this and
1265terminates the program, printing the error message you supply to
1266stderr. Your message should be clear, concise, accurate, and mention
1267the option at fault. Otherwise, the user will have a hard time
1268figuring out what he did wrong.
Neal Norwitz488609e2003-01-06 16:51:37 +00001269
Neal Norwitz488609e2003-01-06 16:51:37 +00001270
Greg Warde644a1b2004-10-01 01:16:39 +00001271\subsubsection{Callback example 1: trivial callback\label{optparse-callback-example-1}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001272
1273Here's an example of a callback option that takes no arguments, and
1274simply records that the option was seen:
Neal Norwitz488609e2003-01-06 16:51:37 +00001275\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001276def record_foo_seen(option, opt_str, value, parser):
1277 parser.saw_foo = True
Neal Norwitz488609e2003-01-06 16:51:37 +00001278
1279parser.add_option("--foo", action="callback", callback=record_foo_seen)
1280\end{verbatim}
1281
Greg Wardb6f7fb72004-09-28 01:30:23 +00001282Of course, you could do that with the \code{store{\_}true} action.
Neal Norwitz488609e2003-01-06 16:51:37 +00001283
Greg Wardb6f7fb72004-09-28 01:30:23 +00001284
Greg Warde644a1b2004-10-01 01:16:39 +00001285\subsubsection{Callback example 2: check option order\label{optparse-callback-example-2}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001286
1287Here's a slightly more interesting example: record the fact that
1288\code{"-a"} is seen, but blow up if it comes after \code{"-b"} in the
1289command-line.
Neal Norwitz488609e2003-01-06 16:51:37 +00001290\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001291def check_order(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001292 if parser.values.b:
1293 raise OptionValueError("can't use -a after -b")
1294 parser.values.a = 1
Greg Wardb6f7fb72004-09-28 01:30:23 +00001295[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001296parser.add_option("-a", action="callback", callback=check_order)
1297parser.add_option("-b", action="store_true", dest="b")
1298\end{verbatim}
1299
Neal Norwitz488609e2003-01-06 16:51:37 +00001300
Greg Warde644a1b2004-10-01 01:16:39 +00001301\subsubsection{Callback example 3: check option order (generalized)\label{optparse-callback-example-3}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001302
1303If you want to re-use this callback for several similar options (set a
1304flag, but blow up if \code{"-b"} has already been seen), it needs a bit of
1305work: the error message and the flag that it sets must be
1306generalized.
Neal Norwitz488609e2003-01-06 16:51:37 +00001307\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001308def check_order(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001309 if parser.values.b:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001310 raise OptionValueError("can't use %s after -b" % opt_str)
Neal Norwitz488609e2003-01-06 16:51:37 +00001311 setattr(parser.values, option.dest, 1)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001312[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001313parser.add_option("-a", action="callback", callback=check_order, dest='a')
1314parser.add_option("-b", action="store_true", dest="b")
1315parser.add_option("-c", action="callback", callback=check_order, dest='c')
1316\end{verbatim}
1317
Greg Wardb6f7fb72004-09-28 01:30:23 +00001318
Greg Warde644a1b2004-10-01 01:16:39 +00001319\subsubsection{Callback example 4: check arbitrary condition\label{optparse-callback-example-4}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001320
1321Of course, you could put any condition in there{---}you're not limited
Neal Norwitz488609e2003-01-06 16:51:37 +00001322to checking the values of already-defined options. For example, if
1323you have options that should not be called when the moon is full, all
1324you have to do is this:
Neal Norwitz488609e2003-01-06 16:51:37 +00001325\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001326def check_moon(option, opt_str, value, parser):
1327 if is_moon_full():
1328 raise OptionValueError("%s option invalid when moon is full"
1329 % opt_str)
Neal Norwitz488609e2003-01-06 16:51:37 +00001330 setattr(parser.values, option.dest, 1)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001331[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001332parser.add_option("--foo",
1333 action="callback", callback=check_moon, dest="foo")
1334\end{verbatim}
1335
Greg Wardb6f7fb72004-09-28 01:30:23 +00001336(The definition of \code{is{\_}moon{\_}full()} is left as an exercise for the
Neal Norwitz488609e2003-01-06 16:51:37 +00001337reader.)
1338
Greg Wardb6f7fb72004-09-28 01:30:23 +00001339
Greg Warde644a1b2004-10-01 01:16:39 +00001340\subsubsection{Callback example 5: fixed arguments\label{optparse-callback-example-5}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001341
1342Things get slightly more interesting when you define callback options
1343that take a fixed number of arguments. Specifying that a callback
Greg Wardb6f7fb72004-09-28 01:30:23 +00001344option takes arguments is similar to defining a \code{store} or \code{append}
1345option: if you define \member{type}, then the option takes one argument that
1346must be convertible to that type; if you further define \code{nargs}, then
1347the option takes \code{nargs} arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +00001348
Greg Wardb6f7fb72004-09-28 01:30:23 +00001349Here's an example that just emulates the standard \code{store} action:
Neal Norwitz488609e2003-01-06 16:51:37 +00001350\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001351def store_value(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001352 setattr(parser.values, option.dest, value)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001353[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001354parser.add_option("--foo",
1355 action="callback", callback=store_value,
1356 type="int", nargs=3, dest="foo")
1357\end{verbatim}
1358
Greg Wardb6f7fb72004-09-28 01:30:23 +00001359Note that \module{optparse} takes care of consuming 3 arguments and converting them
1360to integers for you; all you have to do is store them. (Or whatever;
1361obviously you don't need a callback for this example.)
Neal Norwitz488609e2003-01-06 16:51:37 +00001362
Greg Wardb6f7fb72004-09-28 01:30:23 +00001363
Greg Warde644a1b2004-10-01 01:16:39 +00001364\subsubsection{Callback example 6: variable arguments\label{optparse-callback-example-6}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001365
1366Things get hairy when you want an option to take a variable number of
Greg Wardb6f7fb72004-09-28 01:30:23 +00001367arguments. For this case, you must write a callback, as \module{optparse} doesn't
1368provide any built-in capabilities for it. And you have to deal with
1369certain intricacies of conventional \UNIX{} command-line parsing that \module{optparse}
1370normally handles for you. In particular, callbacks should implement
1371the conventional rules for bare \code{"-{}-"} and \code{"-"} arguments:
Neal Norwitz488609e2003-01-06 16:51:37 +00001372\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001373\item {}
1374either \code{"-{}-"} or \code{"-"} can be option arguments
Neal Norwitz488609e2003-01-06 16:51:37 +00001375
Greg Wardb6f7fb72004-09-28 01:30:23 +00001376\item {}
1377bare \code{"-{}-"} (if not the argument to some option): halt command-line
1378processing and discard the \code{"-{}-"}
Neal Norwitz488609e2003-01-06 16:51:37 +00001379
Greg Wardb6f7fb72004-09-28 01:30:23 +00001380\item {}
1381bare \code{"-"} (if not the argument to some option): halt command-line
1382processing but keep the \code{"-"} (append it to \code{parser.largs})
1383
Neal Norwitz488609e2003-01-06 16:51:37 +00001384\end{itemize}
1385
1386If you want an option that takes a variable number of arguments, there
1387are several subtle, tricky issues to worry about. The exact
1388implementation you choose will be based on which trade-offs you're
Greg Wardb6f7fb72004-09-28 01:30:23 +00001389willing to make for your application (which is why \module{optparse} doesn't support
1390this sort of thing directly).
Neal Norwitz488609e2003-01-06 16:51:37 +00001391
1392Nevertheless, here's a stab at a callback for an option with variable
1393arguments:
Neal Norwitz488609e2003-01-06 16:51:37 +00001394\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001395def vararg_callback(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001396 assert value is None
1397 done = 0
1398 value = []
1399 rargs = parser.rargs
1400 while rargs:
1401 arg = rargs[0]
1402
1403 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1404 # etc. Note that this also stops on "-3" or "-3.0", so if
1405 # your option takes numeric values, you will need to handle
1406 # this.
1407 if ((arg[:2] == "--" and len(arg) > 2) or
1408 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1409 break
1410 else:
1411 value.append(arg)
1412 del rargs[0]
1413
1414 setattr(parser.values, option.dest, value)
1415
Greg Wardb6f7fb72004-09-28 01:30:23 +00001416[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001417parser.add_option("-c", "--callback",
1418 action="callback", callback=varargs)
1419\end{verbatim}
1420
1421The main weakness with this particular implementation is that negative
Greg Wardb6f7fb72004-09-28 01:30:23 +00001422numbers in the arguments following \code{"-c"} will be interpreted as
1423further options (probably causing an error), rather than as arguments to
1424\code{"-c"}. Fixing this is left as an exercise for the reader.
Greg Warde644a1b2004-10-01 01:16:39 +00001425% $Id: callbacks.txt 415 2004-09-30 02:26:17Z greg $
Neal Norwitz488609e2003-01-06 16:51:37 +00001426