blob: e50247ab4ad4bf5e8047bfce3921a5db87a10b82 [file] [log] [blame]
Greg Wardc5221e12006-06-10 16:40:01 +00001% THIS FILE IS AUTO-GENERATED! DO NOT EDIT!
2% (Your changes will be lost the next time it is generated.)
Greg Wardb6f7fb72004-09-28 01:30:23 +00003\section{\module{optparse} --- More powerful command line option parser}
Neal Norwitz488609e2003-01-06 16:51:37 +00004\declaremodule{standard}{optparse}
5\moduleauthor{Greg Ward}{gward@python.net}
Greg Wardb6f7fb72004-09-28 01:30:23 +00006\modulesynopsis{More convenient, flexible, and powerful command-line parsing library.}
Neal Norwitz488609e2003-01-06 16:51:37 +00007\versionadded{2.3}
Greg Wardb6f7fb72004-09-28 01:30:23 +00008\sectionauthor{Greg Ward}{gward@python.net}
9% An intro blurb used only when generating LaTeX docs for the Python
10% manual (based on README.txt).
Neal Norwitz488609e2003-01-06 16:51:37 +000011
Greg Wardb6f7fb72004-09-28 01:30:23 +000012\code{optparse} is a more convenient, flexible, and powerful library for
13parsing command-line options than \code{getopt}. \code{optparse} uses a more
14declarative style of command-line parsing: you create an instance of
15\class{OptionParser}, populate it with options, and parse the command line.
16\code{optparse} allows users to specify options in the conventional GNU/POSIX
17syntax, and additionally generates usage and help messages for you.
Neal Norwitz488609e2003-01-06 16:51:37 +000018
Greg Wardb6f7fb72004-09-28 01:30:23 +000019Here's an example of using \code{optparse} in a simple script:
Neal Norwitz488609e2003-01-06 16:51:37 +000020\begin{verbatim}
21from optparse import OptionParser
Greg Wardb6f7fb72004-09-28 01:30:23 +000022[...]
Neal Norwitz488609e2003-01-06 16:51:37 +000023parser = OptionParser()
24parser.add_option("-f", "--file", dest="filename",
25 help="write report to FILE", metavar="FILE")
26parser.add_option("-q", "--quiet",
Greg Ward1f535172003-05-03 20:13:08 +000027 action="store_false", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +000028 help="don't print status messages to stdout")
29
Greg Wardb6f7fb72004-09-28 01:30:23 +000030(options, args) = parser.parse_args()
Neal Norwitz488609e2003-01-06 16:51:37 +000031\end{verbatim}
32
33With these few lines of code, users of your script can now do the
Greg Wardb6f7fb72004-09-28 01:30:23 +000034``usual thing'' on the command-line, for example:
Neal Norwitz488609e2003-01-06 16:51:37 +000035\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +000036<yourscript> --file=outfile -q
Neal Norwitz488609e2003-01-06 16:51:37 +000037\end{verbatim}
38
Greg Wardb6f7fb72004-09-28 01:30:23 +000039As it parses the command line, \code{optparse} sets attributes of the
Greg Wardab05edc2006-04-23 03:47:58 +000040\code{options} object returned by \method{parse{\_}args()} based on user-supplied
Greg Wardb6f7fb72004-09-28 01:30:23 +000041command-line values. When \method{parse{\_}args()} returns from parsing this
Greg Wardab05edc2006-04-23 03:47:58 +000042command line, \code{options.filename} will be \code{"outfile"} and
Greg Wardb6f7fb72004-09-28 01:30:23 +000043\code{options.verbose} will be \code{False}. \code{optparse} supports both long
44and short options, allows short options to be merged together, and
45allows options to be associated with their arguments in a variety of
46ways. Thus, the following command lines are all equivalent to the above
47example:
Neal Norwitz488609e2003-01-06 16:51:37 +000048\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +000049<yourscript> -f outfile --quiet
50<yourscript> --quiet --file outfile
51<yourscript> -q -foutfile
52<yourscript> -qfoutfile
Neal Norwitz488609e2003-01-06 16:51:37 +000053\end{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +000054
55Additionally, users can run one of
56\begin{verbatim}
57<yourscript> -h
58<yourscript> --help
59\end{verbatim}
60
61and \code{optparse} will print out a brief summary of your script's
Neal Norwitz488609e2003-01-06 16:51:37 +000062options:
Neal Norwitz488609e2003-01-06 16:51:37 +000063\begin{verbatim}
64usage: <yourscript> [options]
65
66options:
Greg Wardb6f7fb72004-09-28 01:30:23 +000067 -h, --help show this help message and exit
68 -f FILE, --file=FILE write report to FILE
69 -q, --quiet don't print status messages to stdout
Neal Norwitz488609e2003-01-06 16:51:37 +000070\end{verbatim}
71
Greg Wardb6f7fb72004-09-28 01:30:23 +000072where the value of \emph{yourscript} is determined at runtime (normally
73from \code{sys.argv{[}0]}).
Greg Warde644a1b2004-10-01 01:16:39 +000074% $Id: intro.txt 413 2004-09-28 00:59:13Z greg $
Neal Norwitz488609e2003-01-06 16:51:37 +000075
Neal Norwitz488609e2003-01-06 16:51:37 +000076
Greg Wardb6f7fb72004-09-28 01:30:23 +000077\subsection{Background\label{optparse-background}}
78
79\module{optparse} was explicitly designed to encourage the creation of programs with
80straightforward, conventional command-line interfaces. To that end, it
81supports only the most common command-line syntax and semantics
82conventionally used under \UNIX{}. If you are unfamiliar with these
83conventions, read this section to acquaint yourself with them.
84
Neal Norwitz488609e2003-01-06 16:51:37 +000085
86\subsubsection{Terminology\label{optparse-terminology}}
Greg Wardb6f7fb72004-09-28 01:30:23 +000087\begin{description}
88\item[argument]
89a string entered on the command-line, and passed by the shell to
90\code{execl()} or \code{execv()}. In Python, arguments are elements of
91\code{sys.argv{[}1:]} (\code{sys.argv{[}0]} is the name of the program being
92executed). \UNIX{} shells also use the term ``word''.
Neal Norwitz488609e2003-01-06 16:51:37 +000093
Greg Wardb6f7fb72004-09-28 01:30:23 +000094It is occasionally desirable to substitute an argument list other
95than \code{sys.argv{[}1:]}, so you should read ``argument'' as ``an element of
96\code{sys.argv{[}1:]}, or of some other list provided as a substitute for
97\code{sys.argv{[}1:]}''.
98\item[option ]
99an argument used to supply extra information to guide or customize the
100execution of a program. There are many different syntaxes for
101options; the traditional \UNIX{} syntax is a hyphen (``-'') followed by a
102single letter, e.g. \code{"-x"} or \code{"-F"}. Also, traditional \UNIX{}
103syntax allows multiple options to be merged into a single argument,
104e.g. \code{"-x -F"} is equivalent to \code{"-xF"}. The GNU project
Greg Wardab05edc2006-04-23 03:47:58 +0000105introduced \code{"-{}-"} followed by a series of hyphen-separated words,
106e.g. \code{"-{}-file"} or \code{"-{}-dry-run"}. These are the only two option
Greg Wardb6f7fb72004-09-28 01:30:23 +0000107syntaxes provided by \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000108
Greg Wardb6f7fb72004-09-28 01:30:23 +0000109Some other option syntaxes that the world has seen include:
Neal Norwitz488609e2003-01-06 16:51:37 +0000110\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000111\item {}
112a hyphen followed by a few letters, e.g. \code{"-pf"} (this is
113\emph{not} the same as multiple options merged into a single argument)
114
115\item {}
116a hyphen followed by a whole word, e.g. \code{"-file"} (this is
117technically equivalent to the previous syntax, but they aren't
118usually seen in the same program)
119
120\item {}
121a plus sign followed by a single letter, or a few letters,
122or a word, e.g. \code{"+f"}, \code{"+rgb"}
123
124\item {}
125a slash followed by a letter, or a few letters, or a word, e.g.
126\code{"/f"}, \code{"/file"}
127
Neal Norwitz488609e2003-01-06 16:51:37 +0000128\end{itemize}
129
Greg Wardb6f7fb72004-09-28 01:30:23 +0000130These option syntaxes are not supported by \module{optparse}, and they never will
131be. This is deliberate: the first three are non-standard on any
132environment, and the last only makes sense if you're exclusively
133targeting VMS, MS-DOS, and/or Windows.
134\item[option argument]
Neal Norwitz488609e2003-01-06 16:51:37 +0000135an argument that follows an option, is closely associated with that
Greg Wardb6f7fb72004-09-28 01:30:23 +0000136option, and is consumed from the argument list when that option is.
137With \module{optparse}, option arguments may either be in a separate argument
138from their option:
Neal Norwitz488609e2003-01-06 16:51:37 +0000139\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000140-f foo
141--file foo
Neal Norwitz488609e2003-01-06 16:51:37 +0000142\end{verbatim}
143
Greg Wardb6f7fb72004-09-28 01:30:23 +0000144or included in the same argument:
Neal Norwitz488609e2003-01-06 16:51:37 +0000145\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000146-ffoo
147--file=foo
Neal Norwitz488609e2003-01-06 16:51:37 +0000148\end{verbatim}
149
Greg Wardb6f7fb72004-09-28 01:30:23 +0000150Typically, a given option either takes an argument or it doesn't.
151Lots of people want an ``optional option arguments'' feature, meaning
152that some options will take an argument if they see it, and won't if
153they don't. This is somewhat controversial, because it makes parsing
154ambiguous: if \code{"-a"} takes an optional argument and \code{"-b"} is
155another option entirely, how do we interpret \code{"-ab"}? Because of
156this ambiguity, \module{optparse} does not support this feature.
157\item[positional argument]
Neal Norwitz488609e2003-01-06 16:51:37 +0000158something leftover in the argument list after options have been
Greg Wardb6f7fb72004-09-28 01:30:23 +0000159parsed, i.e. after options and their arguments have been parsed and
Neal Norwitz488609e2003-01-06 16:51:37 +0000160removed from the argument list.
Greg Wardb6f7fb72004-09-28 01:30:23 +0000161\item[required option]
162an option that must be supplied on the command-line; note that the
163phrase ``required option'' is self-contradictory in English. \module{optparse}
164doesn't prevent you from implementing required options, but doesn't
165give you much help at it either. See \code{examples/required{\_}1.py} and
166\code{examples/required{\_}2.py} in the \module{optparse} source distribution for two
167ways to implement required options with \module{optparse}.
168\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +0000169
170For example, consider this hypothetical command-line:
Neal Norwitz488609e2003-01-06 16:51:37 +0000171\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000172prog -v --report /tmp/report.txt foo bar
Neal Norwitz488609e2003-01-06 16:51:37 +0000173\end{verbatim}
174
Greg Wardab05edc2006-04-23 03:47:58 +0000175\code{"-v"} and \code{"-{}-report"} are both options. Assuming that
Greg Wardb6f7fb72004-09-28 01:30:23 +0000176\longprogramopt{report} takes one argument, \code{"/tmp/report.txt"} is an option
177argument. \code{"foo"} and \code{"bar"} are positional arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +0000178
Greg Wardb6f7fb72004-09-28 01:30:23 +0000179
Greg Warde644a1b2004-10-01 01:16:39 +0000180\subsubsection{What are options for?\label{optparse-what-options-for}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000181
182Options are used to provide extra information to tune or customize the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000183execution of a program. In case it wasn't clear, options are usually
184\emph{optional}. A program should be able to run just fine with no options
185whatsoever. (Pick a random program from the \UNIX{} or GNU toolsets. Can
186it run without any options at all and still make sense? The main
187exceptions are \code{find}, \code{tar}, and \code{dd}{---}all of which are mutant
188oddballs that have been rightly criticized for their non-standard syntax
189and confusing interfaces.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000190
Greg Wardb6f7fb72004-09-28 01:30:23 +0000191Lots of people want their programs to have ``required options''. Think
192about it. If it's required, then it's \emph{not optional}! If there is a
193piece of information that your program absolutely requires in order to
194run successfully, that's what positional arguments are for.
Neal Norwitz488609e2003-01-06 16:51:37 +0000195
Greg Wardb6f7fb72004-09-28 01:30:23 +0000196As an example of good command-line interface design, consider the humble
197\code{cp} utility, for copying files. It doesn't make much sense to try to
198copy files without supplying a destination and at least one source.
199Hence, \code{cp} fails if you run it with no arguments. However, it has a
200flexible, useful syntax that does not require any options at all:
Neal Norwitz488609e2003-01-06 16:51:37 +0000201\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000202cp SOURCE DEST
203cp SOURCE ... DEST-DIR
Neal Norwitz488609e2003-01-06 16:51:37 +0000204\end{verbatim}
205
Greg Wardb6f7fb72004-09-28 01:30:23 +0000206You can get pretty far with just that. Most \code{cp} implementations
207provide a bunch of options to tweak exactly how the files are copied:
208you can preserve mode and modification time, avoid following symlinks,
209ask before clobbering existing files, etc. But none of this distracts
210from the core mission of \code{cp}, which is to copy either one file to
211another, or several files to another directory.
Neal Norwitz488609e2003-01-06 16:51:37 +0000212
Neal Norwitz488609e2003-01-06 16:51:37 +0000213
Greg Warde644a1b2004-10-01 01:16:39 +0000214\subsubsection{What are positional arguments for?\label{optparse-what-positional-arguments-for}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000215
216Positional arguments are for those pieces of information that your
217program absolutely, positively requires to run.
Neal Norwitz488609e2003-01-06 16:51:37 +0000218
219A good user interface should have as few absolute requirements as
220possible. If your program requires 17 distinct pieces of information in
221order to run successfully, it doesn't much matter \emph{how} you get that
Greg Wardb6f7fb72004-09-28 01:30:23 +0000222information from the user{---}most people will give up and walk away
Neal Norwitz488609e2003-01-06 16:51:37 +0000223before they successfully run the program. This applies whether the user
Greg Wardb6f7fb72004-09-28 01:30:23 +0000224interface is a command-line, a configuration file, or a GUI: if you make
225that many demands on your users, most of them will simply give up.
Neal Norwitz488609e2003-01-06 16:51:37 +0000226
227In short, try to minimize the amount of information that users are
Greg Wardb6f7fb72004-09-28 01:30:23 +0000228absolutely required to supply{---}use sensible defaults whenever
Neal Norwitz488609e2003-01-06 16:51:37 +0000229possible. Of course, you also want to make your programs reasonably
230flexible. That's what options are for. Again, it doesn't matter if
Greg Wardb6f7fb72004-09-28 01:30:23 +0000231they are entries in a config file, widgets in the ``Preferences'' dialog
232of a GUI, or command-line options{---}the more options you implement, the
233more flexible your program is, and the more complicated its
234implementation becomes. Too much flexibility has drawbacks as well, of
235course; too many options can overwhelm users and make your code much
236harder to maintain.
Greg Warde644a1b2004-10-01 01:16:39 +0000237% $Id: tao.txt 413 2004-09-28 00:59:13Z greg $
Neal Norwitz488609e2003-01-06 16:51:37 +0000238
Neal Norwitz488609e2003-01-06 16:51:37 +0000239
Greg Wardb6f7fb72004-09-28 01:30:23 +0000240\subsection{Tutorial\label{optparse-tutorial}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000241
Greg Wardb6f7fb72004-09-28 01:30:23 +0000242While \module{optparse} is quite flexible and powerful, it's also straightforward to
243use in most cases. This section covers the code patterns that are
244common to any \module{optparse}-based program.
Neal Norwitz488609e2003-01-06 16:51:37 +0000245
Greg Wardb6f7fb72004-09-28 01:30:23 +0000246First, you need to import the OptionParser class; then, early in the
247main program, create an OptionParser instance:
Neal Norwitz488609e2003-01-06 16:51:37 +0000248\begin{verbatim}
249from optparse import OptionParser
Greg Wardb6f7fb72004-09-28 01:30:23 +0000250[...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000251parser = OptionParser()
252\end{verbatim}
253
Greg Wardb6f7fb72004-09-28 01:30:23 +0000254Then you can start defining options. The basic syntax is:
255\begin{verbatim}
256parser.add_option(opt_str, ...,
257 attr=value, ...)
258\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000259
Greg Wardb6f7fb72004-09-28 01:30:23 +0000260Each option has one or more option strings, such as \code{"-f"} or
261\code{"-{}-file"}, and several option attributes that tell \module{optparse} what to
262expect and what to do when it encounters that option on the command
263line.
264
265Typically, each option will have one short option string and one long
266option string, e.g.:
Neal Norwitz488609e2003-01-06 16:51:37 +0000267\begin{verbatim}
268parser.add_option("-f", "--file", ...)
269\end{verbatim}
270
Greg Wardb6f7fb72004-09-28 01:30:23 +0000271You're free to define as many short option strings and as many long
272option strings as you like (including zero), as long as there is at
273least one option string overall.
Neal Norwitz488609e2003-01-06 16:51:37 +0000274
Greg Wardb6f7fb72004-09-28 01:30:23 +0000275The option strings passed to \method{add{\_}option()} are effectively labels for
276the option defined by that call. For brevity, we will frequently refer
277to \emph{encountering an option} on the command line; in reality, \module{optparse}
278encounters \emph{option strings} and looks up options from them.
Neal Norwitz488609e2003-01-06 16:51:37 +0000279
Greg Wardb6f7fb72004-09-28 01:30:23 +0000280Once all of your options are defined, instruct \module{optparse} to parse your
281program's command line:
282\begin{verbatim}
283(options, args) = parser.parse_args()
284\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000285
Greg Wardb6f7fb72004-09-28 01:30:23 +0000286(If you like, you can pass a custom argument list to \method{parse{\_}args()},
287but that's rarely necessary: by default it uses \code{sys.argv{[}1:]}.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000288
Greg Wardb6f7fb72004-09-28 01:30:23 +0000289\method{parse{\_}args()} returns two values:
290\begin{itemize}
291\item {}
Greg Wardab05edc2006-04-23 03:47:58 +0000292\code{options}, an object containing values for all of your options{---}e.g. if \code{"-{}-file"} takes a single string argument, then
293\code{options.file} will be the filename supplied by the user, or
Greg Wardb6f7fb72004-09-28 01:30:23 +0000294\code{None} if the user did not supply that option
295
296\item {}
Greg Wardab05edc2006-04-23 03:47:58 +0000297\code{args}, the list of positional arguments leftover after parsing
Greg Wardb6f7fb72004-09-28 01:30:23 +0000298options
299
300\end{itemize}
301
302This tutorial section only covers the four most important option
303attributes: \member{action}, \member{type}, \member{dest} (destination), and \member{help}.
304Of these, \member{action} is the most fundamental.
305
306
Greg Warde644a1b2004-10-01 01:16:39 +0000307\subsubsection{Understanding option actions\label{optparse-understanding-option-actions}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000308
309Actions tell \module{optparse} what to do when it encounters an option on the
310command line. There is a fixed set of actions hard-coded into \module{optparse};
Greg Wardc5221e12006-06-10 16:40:01 +0000311adding new actions is an advanced topic covered in section~\ref{optparse-extending-optparse}, Extending \module{optparse}.
Greg Wardb6f7fb72004-09-28 01:30:23 +0000312Most actions tell \module{optparse} to store a value in some variable{---}for
313example, take a string from the command line and store it in an
Greg Wardab05edc2006-04-23 03:47:58 +0000314attribute of \code{options}.
Greg Wardb6f7fb72004-09-28 01:30:23 +0000315
316If you don't specify an option action, \module{optparse} defaults to \code{store}.
317
318
Greg Warde644a1b2004-10-01 01:16:39 +0000319\subsubsection{The store action\label{optparse-store-action}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000320
321The most common option action is \code{store}, which tells \module{optparse} to take
322the next argument (or the remainder of the current argument), ensure
323that it is of the correct type, and store it to your chosen destination.
324
325For example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000326\begin{verbatim}
327parser.add_option("-f", "--file",
328 action="store", type="string", dest="filename")
329\end{verbatim}
330
Greg Wardb6f7fb72004-09-28 01:30:23 +0000331Now let's make up a fake command line and ask \module{optparse} to parse it:
Neal Norwitz488609e2003-01-06 16:51:37 +0000332\begin{verbatim}
333args = ["-f", "foo.txt"]
Greg Wardb6f7fb72004-09-28 01:30:23 +0000334(options, args) = parser.parse_args(args)
Neal Norwitz488609e2003-01-06 16:51:37 +0000335\end{verbatim}
336
Greg Wardb6f7fb72004-09-28 01:30:23 +0000337When \module{optparse} sees the option string \code{"-f"}, it consumes the next
Greg Wardab05edc2006-04-23 03:47:58 +0000338argument, \code{"foo.txt"}, and stores it in \code{options.filename}. So,
339after this call to \method{parse{\_}args()}, \code{options.filename} is
Greg Wardb6f7fb72004-09-28 01:30:23 +0000340\code{"foo.txt"}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000341
Greg Wardb6f7fb72004-09-28 01:30:23 +0000342Some other option types supported by \module{optparse} are \code{int} and \code{float}.
343Here's an option that expects an integer argument:
Neal Norwitz488609e2003-01-06 16:51:37 +0000344\begin{verbatim}
345parser.add_option("-n", type="int", dest="num")
346\end{verbatim}
347
Greg Wardb6f7fb72004-09-28 01:30:23 +0000348Note that this option has no long option string, which is perfectly
349acceptable. Also, there's no explicit action, since the default is
350\code{store}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000351
Greg Wardb6f7fb72004-09-28 01:30:23 +0000352Let's parse another fake command-line. This time, we'll jam the option
353argument right up against the option: since \code{"-n42"} (one argument) is
354equivalent to \code{"-n 42"} (two arguments), the code
Neal Norwitz488609e2003-01-06 16:51:37 +0000355\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000356(options, args) = parser.parse_args(["-n42"])
Neal Norwitz488609e2003-01-06 16:51:37 +0000357print options.num
358\end{verbatim}
359
Greg Wardb6f7fb72004-09-28 01:30:23 +0000360will print \code{"42"}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000361
Greg Wardb6f7fb72004-09-28 01:30:23 +0000362If you don't specify a type, \module{optparse} assumes \code{string}. Combined with the
363fact that the default action is \code{store}, that means our first example
364can be a lot shorter:
Neal Norwitz488609e2003-01-06 16:51:37 +0000365\begin{verbatim}
366parser.add_option("-f", "--file", dest="filename")
367\end{verbatim}
368
Greg Wardb6f7fb72004-09-28 01:30:23 +0000369If you don't supply a destination, \module{optparse} figures out a sensible default
370from the option strings: if the first long option string is
371\code{"-{}-foo-bar"}, then the default destination is \code{foo{\_}bar}. If there
372are no long option strings, \module{optparse} looks at the first short option
373string: the default destination for \code{"-f"} is \code{f}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000374
Greg Wardb6f7fb72004-09-28 01:30:23 +0000375\module{optparse} also includes built-in \code{long} and \code{complex} types. Adding
Greg Wardc5221e12006-06-10 16:40:01 +0000376types is covered in section~\ref{optparse-extending-optparse}, Extending \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000377
Neal Norwitz488609e2003-01-06 16:51:37 +0000378
Greg Warde644a1b2004-10-01 01:16:39 +0000379\subsubsection{Handling boolean (flag) options\label{optparse-handling-boolean-options}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000380
Greg Wardb6f7fb72004-09-28 01:30:23 +0000381Flag options{---}set a variable to true or false when a particular option
382is seen{---}are quite common. \module{optparse} supports them with two separate
383actions, \code{store{\_}true} and \code{store{\_}false}. For example, you might have a
Greg Wardab05edc2006-04-23 03:47:58 +0000384\code{verbose} flag that is turned on with \code{"-v"} and off with \code{"-q"}:
Neal Norwitz488609e2003-01-06 16:51:37 +0000385\begin{verbatim}
386parser.add_option("-v", action="store_true", dest="verbose")
387parser.add_option("-q", action="store_false", dest="verbose")
388\end{verbatim}
389
390Here we have two different options with the same destination, which is
391perfectly OK. (It just means you have to be a bit careful when setting
Greg Warde644a1b2004-10-01 01:16:39 +0000392default values{---}see below.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000393
Greg Wardb6f7fb72004-09-28 01:30:23 +0000394When \module{optparse} encounters \code{"-v"} on the command line, it sets
395\code{options.verbose} to \code{True}; when it encounters \code{"-q"},
396\code{options.verbose} is set to \code{False}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000397
Greg Wardb6f7fb72004-09-28 01:30:23 +0000398
399\subsubsection{Other actions\label{optparse-other-actions}}
400
401Some other actions supported by \module{optparse} are:
402\begin{description}
403\item[\code{store{\_}const}]
404store a constant value
405\item[\code{append}]
406append this option's argument to a list
407\item[\code{count}]
408increment a counter by one
409\item[\code{callback}]
410call a specified function
411\end{description}
412
Greg Warde644a1b2004-10-01 01:16:39 +0000413These 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 +0000414
415
416\subsubsection{Default values\label{optparse-default-values}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000417
418All of the above examples involve setting some variable (the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000419``destination'') when certain command-line options are seen. What happens
420if those options are never seen? Since we didn't supply any defaults,
421they are all set to \code{None}. This is usually fine, but sometimes you
422want more control. \module{optparse} lets you supply a default value for each
423destination, which is assigned before the command line is parsed.
Neal Norwitz488609e2003-01-06 16:51:37 +0000424
Greg Wardb6f7fb72004-09-28 01:30:23 +0000425First, consider the verbose/quiet example. If we want \module{optparse} to set
Greg Wardab05edc2006-04-23 03:47:58 +0000426\code{verbose} to \code{True} unless \code{"-q"} is seen, then we can do this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000427\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000428parser.add_option("-v", action="store_true", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000429parser.add_option("-q", action="store_false", dest="verbose")
430\end{verbatim}
431
Greg Wardb6f7fb72004-09-28 01:30:23 +0000432Since default values apply to the \emph{destination} rather than to any
433particular option, and these two options happen to have the same
434destination, this is exactly equivalent:
Neal Norwitz488609e2003-01-06 16:51:37 +0000435\begin{verbatim}
436parser.add_option("-v", action="store_true", dest="verbose")
Greg Ward1f535172003-05-03 20:13:08 +0000437parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000438\end{verbatim}
439
Neal Norwitz488609e2003-01-06 16:51:37 +0000440Consider this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000441\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000442parser.add_option("-v", action="store_true", dest="verbose", default=False)
443parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000444\end{verbatim}
445
Greg Wardab05edc2006-04-23 03:47:58 +0000446Again, the default value for \code{verbose} will be \code{True}: the last
Greg Wardd7231282003-05-03 21:22:58 +0000447default value supplied for any particular destination is the one that
448counts.
Neal Norwitz488609e2003-01-06 16:51:37 +0000449
Greg Wardb6f7fb72004-09-28 01:30:23 +0000450A clearer way to specify default values is the \method{set{\_}defaults()}
451method of OptionParser, which you can call at any time before calling
452\method{parse{\_}args()}:
453\begin{verbatim}
454parser.set_defaults(verbose=True)
455parser.add_option(...)
456(options, args) = parser.parse_args()
457\end{verbatim}
458
459As before, the last value specified for a given option destination is
460the one that counts. For clarity, try to use one method or the other of
461setting default values, not both.
462
463
Neal Norwitz488609e2003-01-06 16:51:37 +0000464\subsubsection{Generating help\label{optparse-generating-help}}
465
Greg Wardb6f7fb72004-09-28 01:30:23 +0000466\module{optparse}'s ability to generate help and usage text automatically is useful
467for creating user-friendly command-line interfaces. All you have to do
468is supply a \member{help} value for each option, and optionally a short usage
469message for your whole program. Here's an OptionParser populated with
470user-friendly (documented) options:
Neal Norwitz488609e2003-01-06 16:51:37 +0000471\begin{verbatim}
472usage = "usage: %prog [options] arg1 arg2"
473parser = OptionParser(usage=usage)
474parser.add_option("-v", "--verbose",
Greg Ward1f535172003-05-03 20:13:08 +0000475 action="store_true", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +0000476 help="make lots of noise [default]")
477parser.add_option("-q", "--quiet",
478 action="store_false", dest="verbose",
479 help="be vewwy quiet (I'm hunting wabbits)")
Greg Wardb6f7fb72004-09-28 01:30:23 +0000480parser.add_option("-f", "--filename",
Neal Norwitz488609e2003-01-06 16:51:37 +0000481 metavar="FILE", help="write output to FILE"),
482parser.add_option("-m", "--mode",
483 default="intermediate",
Greg Wardb6f7fb72004-09-28 01:30:23 +0000484 help="interaction mode: novice, intermediate, "
485 "or expert [default: %default]")
Neal Norwitz488609e2003-01-06 16:51:37 +0000486\end{verbatim}
487
Greg Wardb6f7fb72004-09-28 01:30:23 +0000488If \module{optparse} encounters either \code{"-h"} or \code{"-{}-help"} on the command-line,
489or if you just call \method{parser.print{\_}help()}, it prints the following to
490standard output:
Neal Norwitz488609e2003-01-06 16:51:37 +0000491\begin{verbatim}
492usage: <yourscript> [options] arg1 arg2
493
494options:
Greg Wardb6f7fb72004-09-28 01:30:23 +0000495 -h, --help show this help message and exit
496 -v, --verbose make lots of noise [default]
497 -q, --quiet be vewwy quiet (I'm hunting wabbits)
498 -f FILE, --filename=FILE
499 write output to FILE
500 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
501 expert [default: intermediate]
Neal Norwitz488609e2003-01-06 16:51:37 +0000502\end{verbatim}
503
Greg Wardb6f7fb72004-09-28 01:30:23 +0000504(If the help output is triggered by a help option, \module{optparse} exits after
505printing the help text.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000506
Greg Wardb6f7fb72004-09-28 01:30:23 +0000507There's a lot going on here to help \module{optparse} generate the best possible
508help message:
Neal Norwitz488609e2003-01-06 16:51:37 +0000509\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000510\item {}
511the script defines its own usage message:
Neal Norwitz488609e2003-01-06 16:51:37 +0000512\begin{verbatim}
513usage = "usage: %prog [options] arg1 arg2"
514\end{verbatim}
515
Greg Wardb6f7fb72004-09-28 01:30:23 +0000516\module{optparse} expands \code{"{\%}prog"} in the usage string to the name of the current
517program, i.e. \code{os.path.basename(sys.argv{[}0])}. The expanded string
518is then printed before the detailed option help.
Neal Norwitz488609e2003-01-06 16:51:37 +0000519
Greg Wardb6f7fb72004-09-28 01:30:23 +0000520If you don't supply a usage string, \module{optparse} uses a bland but sensible
521default: ``\code{usage: {\%}prog {[}options]"}, which is fine if your script
522doesn't take any positional arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +0000523
Greg Wardb6f7fb72004-09-28 01:30:23 +0000524\item {}
525every option defines a help string, and doesn't worry about line-
526wrapping{---}\module{optparse} takes care of wrapping lines and making the
527help output look good.
Neal Norwitz488609e2003-01-06 16:51:37 +0000528
Greg Wardb6f7fb72004-09-28 01:30:23 +0000529\item {}
530options that take a value indicate this fact in their
Neal Norwitz488609e2003-01-06 16:51:37 +0000531automatically-generated help message, e.g. for the ``mode'' option:
Neal Norwitz488609e2003-01-06 16:51:37 +0000532\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000533-m MODE, --mode=MODE
Neal Norwitz488609e2003-01-06 16:51:37 +0000534\end{verbatim}
535
536Here, ``MODE'' is called the meta-variable: it stands for the argument
Greg Wardb6f7fb72004-09-28 01:30:23 +0000537that the user is expected to supply to \programopt{-m}/\longprogramopt{mode}. By default,
538\module{optparse} converts the destination variable name to uppercase and uses
539that for the meta-variable. Sometimes, that's not what you want{---}for example, the \longprogramopt{filename} option explicitly sets
540\code{metavar="FILE"}, resulting in this automatically-generated option
541description:
Neal Norwitz488609e2003-01-06 16:51:37 +0000542\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000543-f FILE, --filename=FILE
Neal Norwitz488609e2003-01-06 16:51:37 +0000544\end{verbatim}
545
546This is important for more than just saving space, though: the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000547manually written help text uses the meta-variable ``FILE'' to clue the
548user in that there's a connection between the semi-formal syntax ``-f
549FILE'' and the informal semantic description ``write output to FILE''.
550This is a simple but effective way to make your help text a lot
551clearer and more useful for end users.
552
553\item {}
554options that have a default value can include \code{{\%}default} in
555the help string{---}\module{optparse} will replace it with \function{str()} of the
556option's default value. If an option has no default value (or the
557default value is \code{None}), \code{{\%}default} expands to \code{none}.
558
Neal Norwitz488609e2003-01-06 16:51:37 +0000559\end{itemize}
560
Fred Drakecf6d74a2003-04-18 15:50:13 +0000561
Greg Warde644a1b2004-10-01 01:16:39 +0000562\subsubsection{Printing a version string\label{optparse-printing-version-string}}
Fred Drakecf6d74a2003-04-18 15:50:13 +0000563
Greg Wardb6f7fb72004-09-28 01:30:23 +0000564Similar to the brief usage string, \module{optparse} can also print a version string
565for your program. You have to supply the string as the \code{version}
566argument to OptionParser:
Neal Norwitz488609e2003-01-06 16:51:37 +0000567\begin{verbatim}
568parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
569\end{verbatim}
570
Greg Wardc5221e12006-06-10 16:40:01 +0000571\code{"{\%}prog"} is expanded just like it is in \code{usage}. Apart
Greg Wardb6f7fb72004-09-28 01:30:23 +0000572from that, \code{version} can contain anything you like. When you supply
573it, \module{optparse} automatically adds a \code{"-{}-version"} option to your parser.
574If it encounters this option on the command line, it expands your
575\code{version} string (by replacing \code{"{\%}prog"}), prints it to stdout, and
576exits.
Neal Norwitz488609e2003-01-06 16:51:37 +0000577
Greg Wardb6f7fb72004-09-28 01:30:23 +0000578For example, if your script is called \code{/usr/bin/foo}:
Neal Norwitz488609e2003-01-06 16:51:37 +0000579\begin{verbatim}
580$ /usr/bin/foo --version
581foo 1.0
Greg Wardb6f7fb72004-09-28 01:30:23 +0000582\end{verbatim}
583
Neal Norwitz488609e2003-01-06 16:51:37 +0000584
Greg Wardab05edc2006-04-23 03:47:58 +0000585\subsubsection{How \module{optparse} handles errors\label{optparse-how-optparse-handles-errors}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000586
Greg Wardb6f7fb72004-09-28 01:30:23 +0000587There are two broad classes of errors that \module{optparse} has to worry about:
588programmer errors and user errors. Programmer errors are usually
Greg Wardab05edc2006-04-23 03:47:58 +0000589erroneous calls to \code{parser.add{\_}option()}, e.g. invalid option strings,
Greg Wardb6f7fb72004-09-28 01:30:23 +0000590unknown option attributes, missing option attributes, etc. These are
591dealt with in the usual way: raise an exception (either
Greg Wardab05edc2006-04-23 03:47:58 +0000592\code{optparse.OptionError} or \code{TypeError}) and let the program crash.
Neal Norwitz488609e2003-01-06 16:51:37 +0000593
Greg Wardb6f7fb72004-09-28 01:30:23 +0000594Handling user errors is much more important, since they are guaranteed
595to happen no matter how stable your code is. \module{optparse} can automatically
596detect some user errors, such as bad option arguments (passing \code{"-n
5974x"} where \programopt{-n} takes an integer argument), missing arguments
598(\code{"-n"} at the end of the command line, where \programopt{-n} takes an argument
599of any type). Also, you can call \code{parser.error()} to signal an
600application-defined error condition:
601\begin{verbatim}
602(options, args) = parser.parse_args()
603[...]
604if options.a and options.b:
605 parser.error("options -a and -b are mutually exclusive")
606\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000607
Greg Wardb6f7fb72004-09-28 01:30:23 +0000608In either case, \module{optparse} handles the error the same way: it prints the
609program's usage message and an error message to standard error and
610exits with error status 2.
Neal Norwitz488609e2003-01-06 16:51:37 +0000611
Greg Wardb6f7fb72004-09-28 01:30:23 +0000612Consider the first example above, where the user passes \code{"4x"} to an
613option that takes an integer:
614\begin{verbatim}
615$ /usr/bin/foo -n 4x
616usage: foo [options]
Neal Norwitz488609e2003-01-06 16:51:37 +0000617
Greg Wardb6f7fb72004-09-28 01:30:23 +0000618foo: error: option -n: invalid integer value: '4x'
619\end{verbatim}
620
621Or, where the user fails to pass a value at all:
622\begin{verbatim}
623$ /usr/bin/foo -n
624usage: foo [options]
625
626foo: error: -n option requires an argument
627\end{verbatim}
628
629\module{optparse}-generated error messages take care always to mention the option
630involved in the error; be sure to do the same when calling
631\code{parser.error()} from your application code.
632
633If \module{optparse}'s default error-handling behaviour does not suite your needs,
634you'll need to subclass OptionParser and override \code{exit()} and/or
635\method{error()}.
636
637
638\subsubsection{Putting it all together\label{optparse-putting-it-all-together}}
639
640Here's what \module{optparse}-based scripts usually look like:
Neal Norwitz488609e2003-01-06 16:51:37 +0000641\begin{verbatim}
642from optparse import OptionParser
Greg Wardd7231282003-05-03 21:22:58 +0000643[...]
644def main():
Greg Wardb6f7fb72004-09-28 01:30:23 +0000645 usage = "usage: %prog [options] arg"
Neal Norwitz488609e2003-01-06 16:51:37 +0000646 parser = OptionParser(usage)
Greg Wardb6f7fb72004-09-28 01:30:23 +0000647 parser.add_option("-f", "--file", dest="filename",
Neal Norwitz488609e2003-01-06 16:51:37 +0000648 help="read data from FILENAME")
649 parser.add_option("-v", "--verbose",
650 action="store_true", dest="verbose")
651 parser.add_option("-q", "--quiet",
652 action="store_false", dest="verbose")
Greg Wardb6f7fb72004-09-28 01:30:23 +0000653 [...]
654 (options, args) = parser.parse_args()
655 if len(args) != 1:
Neal Norwitz488609e2003-01-06 16:51:37 +0000656 parser.error("incorrect number of arguments")
Neal Norwitz488609e2003-01-06 16:51:37 +0000657 if options.verbose:
Johannes Gijsbersc9c37ca2004-09-11 15:47:30 +0000658 print "reading %s..." % options.filename
Greg Wardb6f7fb72004-09-28 01:30:23 +0000659 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000660
661if __name__ == "__main__":
662 main()
663\end{verbatim}
Greg Wardc5221e12006-06-10 16:40:01 +0000664% $Id: tutorial.txt 515 2006-06-10 15:37:45Z gward $
Neal Norwitz488609e2003-01-06 16:51:37 +0000665
Neal Norwitz488609e2003-01-06 16:51:37 +0000666
Greg Wardb6f7fb72004-09-28 01:30:23 +0000667\subsection{Reference Guide\label{optparse-reference-guide}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000668
Neal Norwitz488609e2003-01-06 16:51:37 +0000669
Greg Wardab05edc2006-04-23 03:47:58 +0000670\subsubsection{Creating the parser\label{optparse-creating-parser}}
671
672The first step in using \module{optparse} is to create an OptionParser instance:
673\begin{verbatim}
674parser = OptionParser(...)
675\end{verbatim}
676
677The OptionParser constructor has no required arguments, but a number of
678optional keyword arguments. You should always pass them as keyword
679arguments, i.e. do not rely on the order in which the arguments are
680declared.
681\begin{quote}
682\begin{description}
683\item[\code{usage} (default: \code{"{\%}prog {[}options]"})]
684The usage summary to print when your program is run incorrectly or
685with a help option. When \module{optparse} prints the usage string, it expands
686\code{{\%}prog} to \code{os.path.basename(sys.argv{[}0])} (or to \code{prog} if
687you passed that keyword argument). To suppress a usage message,
688pass the special value \code{optparse.SUPPRESS{\_}USAGE}.
689\item[\code{option{\_}list} (default: \code{{[}]})]
690A list of Option objects to populate the parser with. The options
691in \code{option{\_}list} are added after any options in
692\code{standard{\_}option{\_}list} (a class attribute that may be set by
693OptionParser subclasses), but before any version or help options.
694Deprecated; use \method{add{\_}option()} after creating the parser instead.
695\item[\code{option{\_}class} (default: optparse.Option)]
696Class to use when adding options to the parser in \method{add{\_}option()}.
697\item[\code{version} (default: \code{None})]
698A version string to print when the user supplies a version option.
699If you supply a true value for \code{version}, \module{optparse} automatically adds
700a version option with the single option string \code{"-{}-version"}. The
701substring \code{"{\%}prog"} is expanded the same as for \code{usage}.
702\item[\code{conflict{\_}handler} (default: \code{"error"})]
703Specifies what to do when options with conflicting option strings
704are added to the parser; see section~\ref{optparse-conflicts-between-options}, Conflicts between options.
705\item[\code{description} (default: \code{None})]
706A paragraph of text giving a brief overview of your program. \module{optparse}
707reformats this paragraph to fit the current terminal width and
708prints it when the user requests help (after \code{usage}, but before
709the list of options).
710\item[\code{formatter} (default: a new IndentedHelpFormatter)]
711An instance of optparse.HelpFormatter that will be used for
712printing help text. \module{optparse} provides two concrete classes for this
713purpose: IndentedHelpFormatter and TitledHelpFormatter.
714\item[\code{add{\_}help{\_}option} (default: \code{True})]
715If true, \module{optparse} will add a help option (with option strings \code{"-h"}
716and \code{"-{}-help"}) to the parser.
717\item[\code{prog}]
718The string to use when expanding \code{"{\%}prog"} in \code{usage} and
719\code{version} instead of \code{os.path.basename(sys.argv{[}0])}.
720\end{description}
721\end{quote}
722
723
Greg Warde644a1b2004-10-01 01:16:39 +0000724\subsubsection{Populating the parser\label{optparse-populating-parser}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000725
726There are several ways to populate the parser with options. The
727preferred way is by using \code{OptionParser.add{\_}option()}, as shown in
Greg Warde644a1b2004-10-01 01:16:39 +0000728section~\ref{optparse-tutorial}, the tutorial. \method{add{\_}option()} can be called in one of two
Greg Wardb6f7fb72004-09-28 01:30:23 +0000729ways:
730\begin{itemize}
731\item {}
732pass it an Option instance (as returned by \function{make{\_}option()})
733
734\item {}
735pass it any combination of positional and keyword arguments that are
736acceptable to \function{make{\_}option()} (i.e., to the Option constructor),
737and it will create the Option instance for you
738
739\end{itemize}
740
741The other alternative is to pass a list of pre-constructed Option
742instances to the OptionParser constructor, as in:
Neal Norwitz488609e2003-01-06 16:51:37 +0000743\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000744option_list = [
Neal Norwitz488609e2003-01-06 16:51:37 +0000745 make_option("-f", "--filename",
746 action="store", type="string", dest="filename"),
747 make_option("-q", "--quiet",
Greg Wardb6f7fb72004-09-28 01:30:23 +0000748 action="store_false", dest="verbose"),
749 ]
Neal Norwitz488609e2003-01-06 16:51:37 +0000750parser = OptionParser(option_list=option_list)
751\end{verbatim}
752
Greg Wardb6f7fb72004-09-28 01:30:23 +0000753(\function{make{\_}option()} is a factory function for creating Option instances;
754currently it is an alias for the Option constructor. A future version
755of \module{optparse} may split Option into several classes, and \function{make{\_}option()}
756will pick the right class to instantiate. Do not instantiate Option
757directly.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000758
Neal Norwitz488609e2003-01-06 16:51:37 +0000759
760\subsubsection{Defining options\label{optparse-defining-options}}
761
Greg Wardb6f7fb72004-09-28 01:30:23 +0000762Each Option instance represents a set of synonymous command-line option
Greg Ward961eda72004-11-12 01:20:17 +0000763strings, e.g. \programopt{-f} and \longprogramopt{file}. You can
Greg Wardb6f7fb72004-09-28 01:30:23 +0000764specify any number of short or long option strings, but you must specify
765at least one overall option string.
766
Greg Wardab05edc2006-04-23 03:47:58 +0000767The canonical way to create an Option instance is with the
768\method{add{\_}option()} method of \class{OptionParser}:
Greg Wardb6f7fb72004-09-28 01:30:23 +0000769\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +0000770parser.add_option(opt_str[, ...], attr=value, ...)
Greg Wardb6f7fb72004-09-28 01:30:23 +0000771\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000772
773To define an option with only a short option string:
Neal Norwitz488609e2003-01-06 16:51:37 +0000774\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +0000775parser.add_option("-f", attr=value, ...)
Neal Norwitz488609e2003-01-06 16:51:37 +0000776\end{verbatim}
777
778And to define an option with only a long option string:
Neal Norwitz488609e2003-01-06 16:51:37 +0000779\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +0000780parser.add_option("--foo", attr=value, ...)
Neal Norwitz488609e2003-01-06 16:51:37 +0000781\end{verbatim}
782
Greg Wardab05edc2006-04-23 03:47:58 +0000783The keyword arguments define attributes of the new Option object. The
784most important option attribute is \member{action}, and it largely determines
785which other attributes are relevant or required. If you pass irrelevant
786option attributes, or fail to pass required ones, \module{optparse} raises an
787OptionError exception explaining your mistake.
Neal Norwitz488609e2003-01-06 16:51:37 +0000788
Greg Wardab05edc2006-04-23 03:47:58 +0000789An options's \emph{action} determines what \module{optparse} does when it encounters this
790option on the command-line. The standard option actions hard-coded into
791\module{optparse} are:
Greg Wardb6f7fb72004-09-28 01:30:23 +0000792\begin{description}
793\item[\code{store}]
Greg Wardab05edc2006-04-23 03:47:58 +0000794store this option's argument (default)
Greg Wardb6f7fb72004-09-28 01:30:23 +0000795\item[\code{store{\_}const}]
796store a constant value
797\item[\code{store{\_}true}]
798store a true value
799\item[\code{store{\_}false}]
800store a false value
801\item[\code{append}]
802append this option's argument to a list
Greg Wardab05edc2006-04-23 03:47:58 +0000803\item[\code{append{\_}const}]
804append a constant value to a list
Greg Wardb6f7fb72004-09-28 01:30:23 +0000805\item[\code{count}]
806increment a counter by one
807\item[\code{callback}]
808call a specified function
809\item[\member{help}]
810print a usage message including all options and the
811documentation for them
812\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +0000813
Greg Wardb6f7fb72004-09-28 01:30:23 +0000814(If you don't supply an action, the default is \code{store}. For this
815action, you may also supply \member{type} and \member{dest} option attributes; see
Neal Norwitz488609e2003-01-06 16:51:37 +0000816below.)
817
818As you can see, most actions involve storing or updating a value
Greg Wardab05edc2006-04-23 03:47:58 +0000819somewhere. \module{optparse} always creates a special object for this,
820conventionally called \code{options} (it happens to be an instance of
821\code{optparse.Values}). Option arguments (and various other values) are
822stored as attributes of this object, according to the \member{dest}
823(destination) option attribute.
Neal Norwitz488609e2003-01-06 16:51:37 +0000824
Greg Wardb6f7fb72004-09-28 01:30:23 +0000825For example, when you call
Neal Norwitz488609e2003-01-06 16:51:37 +0000826\begin{verbatim}
827parser.parse_args()
828\end{verbatim}
829
Greg Wardab05edc2006-04-23 03:47:58 +0000830one of the first things \module{optparse} does is create the \code{options} object:
Neal Norwitz488609e2003-01-06 16:51:37 +0000831\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000832options = Values()
Neal Norwitz488609e2003-01-06 16:51:37 +0000833\end{verbatim}
834
Greg Wardb6f7fb72004-09-28 01:30:23 +0000835If one of the options in this parser is defined with
Neal Norwitz488609e2003-01-06 16:51:37 +0000836\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +0000837parser.add_option("-f", "--file", action="store", type="string", dest="filename")
Neal Norwitz488609e2003-01-06 16:51:37 +0000838\end{verbatim}
839
840and the command-line being parsed includes any of the following:
Neal Norwitz488609e2003-01-06 16:51:37 +0000841\begin{verbatim}
842-ffoo
843-f foo
844--file=foo
845--file foo
846\end{verbatim}
847
Greg Wardab05edc2006-04-23 03:47:58 +0000848then \module{optparse}, on seeing this option, will do the equivalent of
Neal Norwitz488609e2003-01-06 16:51:37 +0000849\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000850options.filename = "foo"
Neal Norwitz488609e2003-01-06 16:51:37 +0000851\end{verbatim}
852
Greg Wardb6f7fb72004-09-28 01:30:23 +0000853The \member{type} and \member{dest} option attributes are almost as important as
854\member{action}, but \member{action} is the only one that makes sense for \emph{all}
855options.
856
Neal Norwitz488609e2003-01-06 16:51:37 +0000857
Greg Warde644a1b2004-10-01 01:16:39 +0000858\subsubsection{Standard option actions\label{optparse-standard-option-actions}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000859
Greg Wardb6f7fb72004-09-28 01:30:23 +0000860The various option actions all have slightly different requirements and
861effects. Most actions have several relevant option attributes which you
862may specify to guide \module{optparse}'s behaviour; a few have required attributes,
863which you must specify for any option using that action.
864\begin{itemize}
865\item {}
866\code{store} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000867
Greg Wardb6f7fb72004-09-28 01:30:23 +0000868The option must be followed by an argument, which is
869converted to a value according to \member{type} and stored in
870\member{dest}. If \code{nargs} {\textgreater} 1, multiple arguments will be consumed
871from the command line; all will be converted according to
872\member{type} and stored to \member{dest} as a tuple. See the ``Option
873types'' section below.
Neal Norwitz488609e2003-01-06 16:51:37 +0000874
Greg Wardb6f7fb72004-09-28 01:30:23 +0000875If \code{choices} is supplied (a list or tuple of strings), the type
876defaults to \code{choice}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000877
Greg Wardb6f7fb72004-09-28 01:30:23 +0000878If \member{type} is not supplied, it defaults to \code{string}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000879
Greg Wardb6f7fb72004-09-28 01:30:23 +0000880If \member{dest} is not supplied, \module{optparse} derives a destination from the
881first long option string (e.g., \code{"-{}-foo-bar"} implies \code{foo{\_}bar}).
882If there are no long option strings, \module{optparse} derives a destination from
883the first short option string (e.g., \code{"-f"} implies \code{f}).
Neal Norwitz488609e2003-01-06 16:51:37 +0000884
885Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000886\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000887parser.add_option("-f")
888parser.add_option("-p", type="float", nargs=3, dest="point")
Neal Norwitz488609e2003-01-06 16:51:37 +0000889\end{verbatim}
890
Greg Wardb6f7fb72004-09-28 01:30:23 +0000891As it parses the command line
Neal Norwitz488609e2003-01-06 16:51:37 +0000892\begin{verbatim}
893-f foo.txt -p 1 -3.5 4 -fbar.txt
894\end{verbatim}
895
Greg Wardb6f7fb72004-09-28 01:30:23 +0000896\module{optparse} will set
Neal Norwitz488609e2003-01-06 16:51:37 +0000897\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000898options.f = "foo.txt"
899options.point = (1.0, -3.5, 4.0)
900options.f = "bar.txt"
Neal Norwitz488609e2003-01-06 16:51:37 +0000901\end{verbatim}
902
Greg Wardb6f7fb72004-09-28 01:30:23 +0000903\item {}
904\code{store{\_}const} {[}required: \code{const}; relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000905
Greg Wardb6f7fb72004-09-28 01:30:23 +0000906The value \code{const} is stored in \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000907
908Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000909\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000910parser.add_option("-q", "--quiet",
911 action="store_const", const=0, dest="verbose")
912parser.add_option("-v", "--verbose",
913 action="store_const", const=1, dest="verbose")
914parser.add_option("--noisy",
915 action="store_const", const=2, dest="verbose")
Neal Norwitz488609e2003-01-06 16:51:37 +0000916\end{verbatim}
917
Greg Wardb6f7fb72004-09-28 01:30:23 +0000918If \code{"-{}-noisy"} is seen, \module{optparse} will set
Neal Norwitz488609e2003-01-06 16:51:37 +0000919\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000920options.verbose = 2
Neal Norwitz488609e2003-01-06 16:51:37 +0000921\end{verbatim}
922
Greg Wardb6f7fb72004-09-28 01:30:23 +0000923\item {}
924\code{store{\_}true} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000925
Greg Wardb6f7fb72004-09-28 01:30:23 +0000926A special case of \code{store{\_}const} that stores a true value
927to \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000928
Greg Wardb6f7fb72004-09-28 01:30:23 +0000929\item {}
930\code{store{\_}false} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000931
Greg Wardb6f7fb72004-09-28 01:30:23 +0000932Like \code{store{\_}true}, but stores a false value.
Neal Norwitz488609e2003-01-06 16:51:37 +0000933
934Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000935\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000936parser.add_option("--clobber", action="store_true", dest="clobber")
937parser.add_option("--no-clobber", action="store_false", dest="clobber")
Neal Norwitz488609e2003-01-06 16:51:37 +0000938\end{verbatim}
939
Greg Wardb6f7fb72004-09-28 01:30:23 +0000940\item {}
941\code{append} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000942
943The option must be followed by an argument, which is appended to the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000944list in \member{dest}. If no default value for \member{dest} is supplied, an
945empty list is automatically created when \module{optparse} first encounters this
946option on the command-line. If \code{nargs} {\textgreater} 1, multiple arguments are
947consumed, and a tuple of length \code{nargs} is appended to \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000948
Greg Wardb6f7fb72004-09-28 01:30:23 +0000949The defaults for \member{type} and \member{dest} are the same as for the
950\code{store} action.
Neal Norwitz488609e2003-01-06 16:51:37 +0000951
952Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000953\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000954parser.add_option("-t", "--tracks", action="append", type="int")
Neal Norwitz488609e2003-01-06 16:51:37 +0000955\end{verbatim}
956
Greg Wardb6f7fb72004-09-28 01:30:23 +0000957If \code{"-t3"} is seen on the command-line, \module{optparse} does the equivalent of:
Neal Norwitz488609e2003-01-06 16:51:37 +0000958\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000959options.tracks = []
960options.tracks.append(int("3"))
Neal Norwitz488609e2003-01-06 16:51:37 +0000961\end{verbatim}
962
Greg Wardb6f7fb72004-09-28 01:30:23 +0000963If, a little later on, \code{"-{}-tracks=4"} is seen, it does:
Neal Norwitz488609e2003-01-06 16:51:37 +0000964\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000965options.tracks.append(int("4"))
Neal Norwitz488609e2003-01-06 16:51:37 +0000966\end{verbatim}
967
Greg Wardb6f7fb72004-09-28 01:30:23 +0000968\item {}
Greg Wardab05edc2006-04-23 03:47:58 +0000969\code{append{\_}const} {[}required: \code{const}; relevant: \member{dest}]
970
971Like \code{store{\_}const}, but the value \code{const} is appended to \member{dest};
972as with \code{append}, \member{dest} defaults to \code{None}, and an an empty list is
973automatically created the first time the option is encountered.
974
975\item {}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000976\code{count} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000977
Greg Wardb6f7fb72004-09-28 01:30:23 +0000978Increment the integer stored at \member{dest}. If no default value is
979supplied, \member{dest} is set to zero before being incremented the first
980time.
Neal Norwitz488609e2003-01-06 16:51:37 +0000981
982Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000983\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000984parser.add_option("-v", action="count", dest="verbosity")
Neal Norwitz488609e2003-01-06 16:51:37 +0000985\end{verbatim}
986
Greg Wardb6f7fb72004-09-28 01:30:23 +0000987The first time \code{"-v"} is seen on the command line, \module{optparse} does the
988equivalent of:
Neal Norwitz488609e2003-01-06 16:51:37 +0000989\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000990options.verbosity = 0
991options.verbosity += 1
Neal Norwitz488609e2003-01-06 16:51:37 +0000992\end{verbatim}
993
Greg Wardb6f7fb72004-09-28 01:30:23 +0000994Every subsequent occurrence of \code{"-v"} results in
Neal Norwitz488609e2003-01-06 16:51:37 +0000995\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000996options.verbosity += 1
Neal Norwitz488609e2003-01-06 16:51:37 +0000997\end{verbatim}
998
Greg Wardb6f7fb72004-09-28 01:30:23 +0000999\item {}
1000\code{callback} {[}required: \code{callback};
1001relevant: \member{type}, \code{nargs}, \code{callback{\_}args}, \code{callback{\_}kwargs}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001002
Greg Wardab05edc2006-04-23 03:47:58 +00001003Call the function specified by \code{callback}, which is called as
Neal Norwitz488609e2003-01-06 16:51:37 +00001004\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +00001005func(option, opt_str, value, parser, *args, **kwargs)
Neal Norwitz488609e2003-01-06 16:51:37 +00001006\end{verbatim}
1007
Greg Warde644a1b2004-10-01 01:16:39 +00001008See section~\ref{optparse-option-callbacks}, Option Callbacks for more detail.
Neal Norwitz488609e2003-01-06 16:51:37 +00001009
Greg Wardb6f7fb72004-09-28 01:30:23 +00001010\item {}
1011\member{help}
Neal Norwitz488609e2003-01-06 16:51:37 +00001012
Greg Wardb6f7fb72004-09-28 01:30:23 +00001013Prints a complete help message for all the options in the
1014current option parser. The help message is constructed from
Greg Wardab05edc2006-04-23 03:47:58 +00001015the \code{usage} string passed to OptionParser's constructor and
Greg Wardb6f7fb72004-09-28 01:30:23 +00001016the \member{help} string passed to every option.
Neal Norwitz488609e2003-01-06 16:51:37 +00001017
Greg Wardb6f7fb72004-09-28 01:30:23 +00001018If no \member{help} string is supplied for an option, it will still be
1019listed in the help message. To omit an option entirely, use
1020the special value \code{optparse.SUPPRESS{\_}HELP}.
1021
1022\module{optparse} automatically adds a \member{help} option to all OptionParsers, so
1023you do not normally need to create one.
Neal Norwitz488609e2003-01-06 16:51:37 +00001024
1025Example:
Neal Norwitz488609e2003-01-06 16:51:37 +00001026\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001027from optparse import OptionParser, SUPPRESS_HELP
Neal Norwitz488609e2003-01-06 16:51:37 +00001028
Greg Wardb6f7fb72004-09-28 01:30:23 +00001029parser = OptionParser()
1030parser.add_option("-h", "--help", action="help"),
1031parser.add_option("-v", action="store_true", dest="verbose",
1032 help="Be moderately verbose")
1033parser.add_option("--file", dest="filename",
1034 help="Input file to read data from"),
1035parser.add_option("--secret", help=SUPPRESS_HELP)
Neal Norwitz488609e2003-01-06 16:51:37 +00001036\end{verbatim}
1037
Greg Wardb6f7fb72004-09-28 01:30:23 +00001038If \module{optparse} sees either \code{"-h"} or \code{"-{}-help"} on the command line, it
1039will print something like the following help message to stdout
1040(assuming \code{sys.argv{[}0]} is \code{"foo.py"}):
Neal Norwitz488609e2003-01-06 16:51:37 +00001041\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001042usage: foo.py [options]
Neal Norwitz488609e2003-01-06 16:51:37 +00001043
1044options:
1045 -h, --help Show this help message and exit
1046 -v Be moderately verbose
1047 --file=FILENAME Input file to read data from
1048\end{verbatim}
1049
1050After printing the help message, \module{optparse} terminates your process
1051with \code{sys.exit(0)}.
1052
Greg Wardb6f7fb72004-09-28 01:30:23 +00001053\item {}
1054\code{version}
Neal Norwitz488609e2003-01-06 16:51:37 +00001055
Greg Wardb6f7fb72004-09-28 01:30:23 +00001056Prints the version number supplied to the OptionParser to stdout and
1057exits. The version number is actually formatted and printed by the
1058\code{print{\_}version()} method of OptionParser. Generally only relevant
1059if the \code{version} argument is supplied to the OptionParser
1060constructor. As with \member{help} options, you will rarely create
1061\code{version} options, since \module{optparse} automatically adds them when needed.
1062
1063\end{itemize}
1064
Neal Norwitz488609e2003-01-06 16:51:37 +00001065
Greg Wardab05edc2006-04-23 03:47:58 +00001066\subsubsection{Option attributes\label{optparse-option-attributes}}
1067
1068The following option attributes may be passed as keyword arguments
1069to \code{parser.add{\_}option()}. If you pass an option attribute
1070that is not relevant to a particular option, or fail to pass a required
1071option attribute, \module{optparse} raises OptionError.
1072\begin{itemize}
1073\item {}
1074\member{action} (default: \code{"store"})
1075
1076Determines \module{optparse}'s behaviour when this option is seen on the command
1077line; the available options are documented above.
1078
1079\item {}
1080\member{type} (default: \code{"string"})
1081
1082The argument type expected by this option (e.g., \code{"string"} or
1083\code{"int"}); the available option types are documented below.
1084
1085\item {}
1086\member{dest} (default: derived from option strings)
1087
1088If the option's action implies writing or modifying a value somewhere,
1089this tells \module{optparse} where to write it: \member{dest} names an attribute of the
1090\code{options} object that \module{optparse} builds as it parses the command line.
1091
1092\item {}
1093\code{default} (deprecated)
1094
1095The value to use for this option's destination if the option is not
1096seen on the command line. Deprecated; use \code{parser.set{\_}defaults()}
1097instead.
1098
1099\item {}
1100\code{nargs} (default: 1)
1101
1102How many arguments of type \member{type} should be consumed when this
1103option is seen. If {\textgreater} 1, \module{optparse} will store a tuple of values to
1104\member{dest}.
1105
1106\item {}
1107\code{const}
1108
1109For actions that store a constant value, the constant value to store.
1110
1111\item {}
1112\code{choices}
1113
1114For options of type \code{"choice"}, the list of strings the user
1115may choose from.
1116
1117\item {}
1118\code{callback}
1119
1120For options with action \code{"callback"}, the callable to call when this
1121option is seen. See section~\ref{optparse-option-callbacks}, Option Callbacks for detail on the arguments
1122passed to \code{callable}.
1123
1124\item {}
1125\code{callback{\_}args}, \code{callback{\_}kwargs}
1126
1127Additional positional and keyword arguments to pass to \code{callback}
1128after the four standard callback arguments.
1129
1130\item {}
1131\member{help}
1132
1133Help text to print for this option when listing all available options
1134after the user supplies a \member{help} option (such as \code{"-{}-help"}).
1135If no help text is supplied, the option will be listed without help
1136text. To hide this option, use the special value \code{SUPPRESS{\_}HELP}.
1137
1138\item {}
1139\code{metavar} (default: derived from option strings)
1140
1141Stand-in for the option argument(s) to use when printing help text.
1142See section~\ref{optparse-tutorial}, the tutorial for an example.
1143
1144\end{itemize}
1145
1146
Greg Warde644a1b2004-10-01 01:16:39 +00001147\subsubsection{Standard option types\label{optparse-standard-option-types}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001148
Greg Wardb6f7fb72004-09-28 01:30:23 +00001149\module{optparse} has six built-in option types: \code{string}, \code{int}, \code{long},
1150\code{choice}, \code{float} and \code{complex}. If you need to add new option
Greg Wardc5221e12006-06-10 16:40:01 +00001151types, see section~\ref{optparse-extending-optparse}, Extending \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001152
Greg Wardb6f7fb72004-09-28 01:30:23 +00001153Arguments to string options are not checked or converted in any way: the
1154text on the command line is stored in the destination (or passed to the
1155callback) as-is.
Neal Norwitz488609e2003-01-06 16:51:37 +00001156
Greg Wardab05edc2006-04-23 03:47:58 +00001157Integer arguments (type \code{int} or \code{long}) are parsed as follows:
1158\begin{quote}
1159\begin{itemize}
1160\item {}
1161if the number starts with \code{0x}, it is parsed as a hexadecimal number
Neal Norwitz488609e2003-01-06 16:51:37 +00001162
Greg Wardab05edc2006-04-23 03:47:58 +00001163\item {}
1164if the number starts with \code{0}, it is parsed as an octal number
1165
1166\item {}
1167if the number starts with \code{0b}, is is parsed as a binary number
1168
1169\item {}
1170otherwise, the number is parsed as a decimal number
1171
1172\end{itemize}
1173\end{quote}
1174
1175The conversion is done by calling either \code{int()} or \code{long()} with
1176the appropriate base (2, 8, 10, or 16). If this fails, so will \module{optparse},
1177although with a more useful error message.
1178
1179\code{float} and \code{complex} option arguments are converted directly with
1180\code{float()} and \code{complex()}, with similar error-handling.
Neal Norwitz488609e2003-01-06 16:51:37 +00001181
Greg Wardb6f7fb72004-09-28 01:30:23 +00001182\code{choice} options are a subtype of \code{string} options. The \code{choices}
1183option attribute (a sequence of strings) defines the set of allowed
Greg Wardab05edc2006-04-23 03:47:58 +00001184option arguments. \code{optparse.check{\_}choice()} compares
Greg Wardb6f7fb72004-09-28 01:30:23 +00001185user-supplied option arguments against this master list and raises
Greg Wardab05edc2006-04-23 03:47:58 +00001186OptionValueError if an invalid string is given.
1187
1188
1189\subsubsection{Parsing arguments\label{optparse-parsing-arguments}}
1190
1191The whole point of creating and populating an OptionParser is to call
1192its \method{parse{\_}args()} method:
1193\begin{verbatim}
1194(options, args) = parser.parse_args(args=None, options=None)
1195\end{verbatim}
1196
1197where the input parameters are
1198\begin{description}
1199\item[\code{args}]
Greg Wardd1c797e2006-06-11 14:42:41 +00001200the list of arguments to process (default: \code{sys.argv{[}1:]})
Greg Wardab05edc2006-04-23 03:47:58 +00001201\item[\code{options}]
Greg Wardd1c797e2006-06-11 14:42:41 +00001202object to store option arguments in (default: a new instance of
1203optparse.Values)
Greg Wardab05edc2006-04-23 03:47:58 +00001204\end{description}
1205
1206and the return values are
1207\begin{description}
1208\item[\code{options}]
Greg Wardd1c797e2006-06-11 14:42:41 +00001209the same object that was passed in as \code{options}, or the
Greg Wardab05edc2006-04-23 03:47:58 +00001210optparse.Values instance created by \module{optparse}
1211\item[\code{args}]
1212the leftover positional arguments after all options have been
1213processed
1214\end{description}
1215
1216The most common usage is to supply neither keyword argument. If you
Greg Wardd1c797e2006-06-11 14:42:41 +00001217supply \code{options}, it will be modified with repeated \code{setattr()}
1218calls (roughly one for every option argument stored to an option
1219destination) and returned by \method{parse{\_}args()}.
Greg Wardab05edc2006-04-23 03:47:58 +00001220
1221If \method{parse{\_}args()} encounters any errors in the argument list, it calls
1222the OptionParser's \method{error()} method with an appropriate end-user error
1223message. This ultimately terminates your process with an exit status of
12242 (the traditional \UNIX{} exit status for command-line errors).
Neal Norwitz488609e2003-01-06 16:51:37 +00001225
Greg Wardb6f7fb72004-09-28 01:30:23 +00001226
Greg Warde644a1b2004-10-01 01:16:39 +00001227\subsubsection{Querying and manipulating your option parser\label{optparse-querying-manipulating-option-parser}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001228
1229Sometimes, it's useful to poke around your option parser and see what's
Greg Wardb6f7fb72004-09-28 01:30:23 +00001230there. OptionParser provides a couple of methods to help you out:
1231\begin{description}
1232\item[\code{has{\_}option(opt{\_}str)}]
1233Return true if the OptionParser has an option with
1234option string \code{opt{\_}str} (e.g., \code{"-q"} or \code{"-{}-verbose"}).
1235\item[\code{get{\_}option(opt{\_}str)}]
1236Returns the Option instance with the option string \code{opt{\_}str}, or
1237\code{None} if no options have that option string.
1238\item[\code{remove{\_}option(opt{\_}str)}]
1239If the OptionParser has an option corresponding to \code{opt{\_}str},
1240that option is removed. If that option provided any other
1241option strings, all of those option strings become invalid.
Greg Wardb6f7fb72004-09-28 01:30:23 +00001242If \code{opt{\_}str} does not occur in any option belonging to this
Greg Wardab05edc2006-04-23 03:47:58 +00001243OptionParser, raises ValueError.
Greg Wardb6f7fb72004-09-28 01:30:23 +00001244\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001245
Neal Norwitz488609e2003-01-06 16:51:37 +00001246
Greg Wardb6f7fb72004-09-28 01:30:23 +00001247\subsubsection{Conflicts between options\label{optparse-conflicts-between-options}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001248
Greg Wardb6f7fb72004-09-28 01:30:23 +00001249If you're not careful, it's easy to define options with conflicting
1250option strings:
Neal Norwitz488609e2003-01-06 16:51:37 +00001251\begin{verbatim}
1252parser.add_option("-n", "--dry-run", ...)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001253[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001254parser.add_option("-n", "--noisy", ...)
Neal Norwitz488609e2003-01-06 16:51:37 +00001255\end{verbatim}
1256
Greg Wardb6f7fb72004-09-28 01:30:23 +00001257(This is particularly true if you've defined your own OptionParser
1258subclass with some standard options.)
Neal Norwitz488609e2003-01-06 16:51:37 +00001259
Greg Wardb6f7fb72004-09-28 01:30:23 +00001260Every time you add an option, \module{optparse} checks for conflicts with existing
1261options. If it finds any, it invokes the current conflict-handling
1262mechanism. You can set the conflict-handling mechanism either in the
1263constructor:
Neal Norwitz488609e2003-01-06 16:51:37 +00001264\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +00001265parser = OptionParser(..., conflict_handler=handler)
Neal Norwitz488609e2003-01-06 16:51:37 +00001266\end{verbatim}
1267
Greg Wardb6f7fb72004-09-28 01:30:23 +00001268or with a separate call:
1269\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +00001270parser.set_conflict_handler(handler)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001271\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +00001272
Greg Wardab05edc2006-04-23 03:47:58 +00001273The available conflict handlers are:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001274\begin{quote}
1275\begin{description}
1276\item[\code{error} (default)]
1277assume option conflicts are a programming error and raise
Greg Wardab05edc2006-04-23 03:47:58 +00001278OptionConflictError
Greg Wardb6f7fb72004-09-28 01:30:23 +00001279\item[\code{resolve}]
1280resolve option conflicts intelligently (see below)
1281\end{description}
1282\end{quote}
Neal Norwitz488609e2003-01-06 16:51:37 +00001283
Greg Wardb6f7fb72004-09-28 01:30:23 +00001284As an example, let's define an OptionParser that resolves conflicts
1285intelligently and add conflicting options to it:
Neal Norwitz488609e2003-01-06 16:51:37 +00001286\begin{verbatim}
1287parser = OptionParser(conflict_handler="resolve")
Greg Wardb6f7fb72004-09-28 01:30:23 +00001288parser.add_option("-n", "--dry-run", ..., help="do no harm")
1289parser.add_option("-n", "--noisy", ..., help="be noisy")
Neal Norwitz488609e2003-01-06 16:51:37 +00001290\end{verbatim}
1291
Neal Norwitz488609e2003-01-06 16:51:37 +00001292At this point, \module{optparse} detects that a previously-added option is already
Greg Wardb6f7fb72004-09-28 01:30:23 +00001293using the \code{"-n"} option string. Since \code{conflict{\_}handler} is
1294\code{"resolve"}, it resolves the situation by removing \code{"-n"} from the
1295earlier option's list of option strings. Now \code{"-{}-dry-run"} is the
1296only way for the user to activate that option. If the user asks for
1297help, the help message will reflect that:
Neal Norwitz488609e2003-01-06 16:51:37 +00001298\begin{verbatim}
1299options:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001300 --dry-run do no harm
1301 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001302 -n, --noisy be noisy
1303\end{verbatim}
1304
Greg Wardb6f7fb72004-09-28 01:30:23 +00001305It's possible to whittle away the option strings for a previously-added
1306option until there are none left, and the user has no way of invoking
1307that option from the command-line. In that case, \module{optparse} removes that
1308option completely, so it doesn't show up in help text or anywhere else.
1309Carrying on with our existing OptionParser:
Neal Norwitz488609e2003-01-06 16:51:37 +00001310\begin{verbatim}
1311parser.add_option("--dry-run", ..., help="new dry-run option")
1312\end{verbatim}
1313
Greg Wardb6f7fb72004-09-28 01:30:23 +00001314At this point, the original \programopt{-n/-{}-dry-run} option is no longer
1315accessible, so \module{optparse} removes it, leaving this help text:
Neal Norwitz488609e2003-01-06 16:51:37 +00001316\begin{verbatim}
1317options:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001318 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001319 -n, --noisy be noisy
1320 --dry-run new dry-run option
1321\end{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +00001322
1323
1324\subsubsection{Cleanup\label{optparse-cleanup}}
1325
1326OptionParser instances have several cyclic references. This should not
1327be a problem for Python's garbage collector, but you may wish to break
1328the cyclic references explicitly by calling \code{destroy()} on your
1329OptionParser once you are done with it. This is particularly useful in
1330long-running applications where large object graphs are reachable from
1331your OptionParser.
1332
1333
1334\subsubsection{Other methods\label{optparse-other-methods}}
1335
1336OptionParser supports several other public methods:
1337\begin{itemize}
1338\item {}
1339\code{set{\_}usage(usage)}
1340
1341Set the usage string according to the rules described above for the
1342\code{usage} constructor keyword argument. Passing \code{None} sets the
1343default usage string; use \code{SUPPRESS{\_}USAGE} to suppress a usage
1344message.
1345
1346\item {}
1347\code{enable{\_}interspersed{\_}args()}, \code{disable{\_}interspersed{\_}args()}
1348
1349Enable/disable positional arguments interspersed with options, similar
1350to GNU getopt (enabled by default). For example, if \code{"-a"} and
1351\code{"-b"} are both simple options that take no arguments, \module{optparse}
1352normally accepts this syntax:
1353\begin{verbatim}
1354prog -a arg1 -b arg2
1355\end{verbatim}
1356
1357and treats it as equivalent to
1358\begin{verbatim}
1359prog -a -b arg1 arg2
1360\end{verbatim}
1361
1362To disable this feature, call \code{disable{\_}interspersed{\_}args()}. This
1363restores traditional \UNIX{} syntax, where option parsing stops with the
1364first non-option argument.
1365
1366\item {}
1367\code{set{\_}defaults(dest=value, ...)}
1368
1369Set default values for several option destinations at once. Using
1370\method{set{\_}defaults()} is the preferred way to set default values for
1371options, since multiple options can share the same destination. For
1372example, if several ``mode'' options all set the same destination, any
1373one of them can set the default, and the last one wins:
1374\begin{verbatim}
1375parser.add_option("--advanced", action="store_const",
1376 dest="mode", const="advanced",
1377 default="novice") # overridden below
1378parser.add_option("--novice", action="store_const",
1379 dest="mode", const="novice",
1380 default="advanced") # overrides above setting
1381\end{verbatim}
1382
1383To avoid this confusion, use \method{set{\_}defaults()}:
1384\begin{verbatim}
1385parser.set_defaults(mode="advanced")
1386parser.add_option("--advanced", action="store_const",
1387 dest="mode", const="advanced")
1388parser.add_option("--novice", action="store_const",
1389 dest="mode", const="novice")
1390\end{verbatim}
1391
1392\end{itemize}
1393% $Id: reference.txt 505 2005-07-22 01:52:40Z gward $
Neal Norwitz488609e2003-01-06 16:51:37 +00001394
Neal Norwitz488609e2003-01-06 16:51:37 +00001395
Greg Wardb6f7fb72004-09-28 01:30:23 +00001396\subsection{Option Callbacks\label{optparse-option-callbacks}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001397
Greg Wardb6f7fb72004-09-28 01:30:23 +00001398When \module{optparse}'s built-in actions and types aren't quite enough for your
1399needs, you have two choices: extend \module{optparse} or define a callback option.
1400Extending \module{optparse} is more general, but overkill for a lot of simple
1401cases. Quite often a simple callback is all you need.
Neal Norwitz488609e2003-01-06 16:51:37 +00001402
Greg Wardb6f7fb72004-09-28 01:30:23 +00001403There are two steps to defining a callback option:
1404\begin{itemize}
1405\item {}
1406define the option itself using the \code{callback} action
Neal Norwitz488609e2003-01-06 16:51:37 +00001407
Greg Wardb6f7fb72004-09-28 01:30:23 +00001408\item {}
1409write the callback; this is a function (or method) that
1410takes at least four arguments, as described below
1411
1412\end{itemize}
1413
1414
Greg Warde644a1b2004-10-01 01:16:39 +00001415\subsubsection{Defining a callback option\label{optparse-defining-callback-option}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001416
1417As always, the easiest way to define a callback option is by using the
1418\code{parser.add{\_}option()} method. Apart from \member{action}, the only option
1419attribute you must specify is \code{callback}, the function to call:
Neal Norwitz488609e2003-01-06 16:51:37 +00001420\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001421parser.add_option("-c", action="callback", callback=my_callback)
Neal Norwitz488609e2003-01-06 16:51:37 +00001422\end{verbatim}
1423
Greg Wardb6f7fb72004-09-28 01:30:23 +00001424\code{callback} is a function (or other callable object), so you must have
1425already defined \code{my{\_}callback()} when you create this callback option.
1426In this simple case, \module{optparse} doesn't even know if \programopt{-c} takes any
1427arguments, which usually means that the option takes no arguments{---}the
1428mere presence of \programopt{-c} on the command-line is all it needs to know. In
1429some circumstances, though, you might want your callback to consume an
1430arbitrary number of command-line arguments. This is where writing
1431callbacks gets tricky; it's covered later in this section.
1432
1433\module{optparse} always passes four particular arguments to your callback, and it
1434will only pass additional arguments if you specify them via
1435\code{callback{\_}args} and \code{callback{\_}kwargs}. Thus, the minimal callback
1436function signature is:
1437\begin{verbatim}
1438def my_callback(option, opt, value, parser):
1439\end{verbatim}
1440
1441The four arguments to a callback are described below.
Neal Norwitz488609e2003-01-06 16:51:37 +00001442
1443There are several other option attributes that you can supply when you
Greg Wardb6f7fb72004-09-28 01:30:23 +00001444define a callback option:
1445\begin{description}
1446\item[\member{type}]
1447has its usual meaning: as with the \code{store} or \code{append} actions,
1448it instructs \module{optparse} to consume one argument and convert it to
1449\member{type}. Rather than storing the converted value(s) anywhere,
1450though, \module{optparse} passes it to your callback function.
1451\item[\code{nargs}]
1452also has its usual meaning: if it is supplied and {\textgreater} 1, \module{optparse} will
1453consume \code{nargs} arguments, each of which must be convertible to
1454\member{type}. It then passes a tuple of converted values to your
1455callback.
1456\item[\code{callback{\_}args}]
1457a tuple of extra positional arguments to pass to the callback
1458\item[\code{callback{\_}kwargs}]
1459a dictionary of extra keyword arguments to pass to the callback
1460\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001461
Neal Norwitz488609e2003-01-06 16:51:37 +00001462
Greg Warde644a1b2004-10-01 01:16:39 +00001463\subsubsection{How callbacks are called\label{optparse-how-callbacks-called}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001464
1465All callbacks are called as follows:
Neal Norwitz488609e2003-01-06 16:51:37 +00001466\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001467func(option, opt_str, value, parser, *args, **kwargs)
Neal Norwitz488609e2003-01-06 16:51:37 +00001468\end{verbatim}
1469
1470where
Greg Wardb6f7fb72004-09-28 01:30:23 +00001471\begin{description}
1472\item[\code{option}]
1473is the Option instance that's calling the callback
1474\item[\code{opt{\_}str}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001475is the option string seen on the command-line that's triggering the
Greg Wardb6f7fb72004-09-28 01:30:23 +00001476callback. (If an abbreviated long option was used, \code{opt{\_}str} will
1477be the full, canonical option string{---}e.g. if the user puts
1478\code{"-{}-foo"} on the command-line as an abbreviation for
1479\code{"-{}-foobar"}, then \code{opt{\_}str} will be \code{"-{}-foobar"}.)
1480\item[\code{value}]
1481is the argument to this option seen on the command-line. \module{optparse} will
1482only expect an argument if \member{type} is set; the type of \code{value}
1483will be the type implied by the option's type. If \member{type} for this
1484option is \code{None} (no argument expected), then \code{value} will be
1485\code{None}. If \code{nargs} {\textgreater} 1, \code{value} will be a tuple of values of
1486the appropriate type.
1487\item[\code{parser}]
1488is the OptionParser instance driving the whole thing, mainly
1489useful because you can access some other interesting data through
1490its instance attributes:
1491\begin{description}
1492\item[\code{parser.largs}]
1493the current list of leftover arguments, ie. arguments that have
1494been consumed but are neither options nor option arguments.
1495Feel free to modify \code{parser.largs}, e.g. by adding more
Greg Wardab05edc2006-04-23 03:47:58 +00001496arguments to it. (This list will become \code{args}, the second
Greg Wardb6f7fb72004-09-28 01:30:23 +00001497return value of \method{parse{\_}args()}.)
1498\item[\code{parser.rargs}]
1499the current list of remaining arguments, ie. with \code{opt{\_}str} and
1500\code{value} (if applicable) removed, and only the arguments
1501following them still there. Feel free to modify
1502\code{parser.rargs}, e.g. by consuming more arguments.
1503\item[\code{parser.values}]
1504the object where option values are by default stored (an
1505instance of optparse.OptionValues). This lets callbacks use the
1506same mechanism as the rest of \module{optparse} for storing option values;
1507you don't need to mess around with globals or closures. You can
1508also access or modify the value(s) of any options already
1509encountered on the command-line.
1510\end{description}
Raymond Hettinger79e05312004-12-31 01:07:27 +00001511\item[\code{args}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001512is a tuple of arbitrary positional arguments supplied via the
Greg Wardb6f7fb72004-09-28 01:30:23 +00001513\code{callback{\_}args} option attribute.
1514\item[\code{kwargs}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001515is a dictionary of arbitrary keyword arguments supplied via
Greg Wardb6f7fb72004-09-28 01:30:23 +00001516\code{callback{\_}kwargs}.
1517\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001518
Neal Norwitz488609e2003-01-06 16:51:37 +00001519
Greg Warde644a1b2004-10-01 01:16:39 +00001520\subsubsection{Raising errors in a callback\label{optparse-raising-errors-in-callback}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001521
Greg Wardab05edc2006-04-23 03:47:58 +00001522The callback function should raise OptionValueError if there are any
Greg Wardb6f7fb72004-09-28 01:30:23 +00001523problems with the option or its argument(s). \module{optparse} catches this and
1524terminates the program, printing the error message you supply to
1525stderr. Your message should be clear, concise, accurate, and mention
1526the option at fault. Otherwise, the user will have a hard time
1527figuring out what he did wrong.
Neal Norwitz488609e2003-01-06 16:51:37 +00001528
Neal Norwitz488609e2003-01-06 16:51:37 +00001529
Greg Warde644a1b2004-10-01 01:16:39 +00001530\subsubsection{Callback example 1: trivial callback\label{optparse-callback-example-1}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001531
1532Here's an example of a callback option that takes no arguments, and
1533simply records that the option was seen:
Neal Norwitz488609e2003-01-06 16:51:37 +00001534\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001535def record_foo_seen(option, opt_str, value, parser):
1536 parser.saw_foo = True
Neal Norwitz488609e2003-01-06 16:51:37 +00001537
1538parser.add_option("--foo", action="callback", callback=record_foo_seen)
1539\end{verbatim}
1540
Greg Wardb6f7fb72004-09-28 01:30:23 +00001541Of course, you could do that with the \code{store{\_}true} action.
Neal Norwitz488609e2003-01-06 16:51:37 +00001542
Greg Wardb6f7fb72004-09-28 01:30:23 +00001543
Greg Warde644a1b2004-10-01 01:16:39 +00001544\subsubsection{Callback example 2: check option order\label{optparse-callback-example-2}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001545
1546Here's a slightly more interesting example: record the fact that
1547\code{"-a"} is seen, but blow up if it comes after \code{"-b"} in the
1548command-line.
Neal Norwitz488609e2003-01-06 16:51:37 +00001549\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001550def check_order(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001551 if parser.values.b:
1552 raise OptionValueError("can't use -a after -b")
1553 parser.values.a = 1
Greg Wardb6f7fb72004-09-28 01:30:23 +00001554[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001555parser.add_option("-a", action="callback", callback=check_order)
1556parser.add_option("-b", action="store_true", dest="b")
1557\end{verbatim}
1558
Neal Norwitz488609e2003-01-06 16:51:37 +00001559
Greg Warde644a1b2004-10-01 01:16:39 +00001560\subsubsection{Callback example 3: check option order (generalized)\label{optparse-callback-example-3}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001561
1562If you want to re-use this callback for several similar options (set a
1563flag, but blow up if \code{"-b"} has already been seen), it needs a bit of
1564work: the error message and the flag that it sets must be
1565generalized.
Neal Norwitz488609e2003-01-06 16:51:37 +00001566\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001567def check_order(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001568 if parser.values.b:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001569 raise OptionValueError("can't use %s after -b" % opt_str)
Neal Norwitz488609e2003-01-06 16:51:37 +00001570 setattr(parser.values, option.dest, 1)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001571[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001572parser.add_option("-a", action="callback", callback=check_order, dest='a')
1573parser.add_option("-b", action="store_true", dest="b")
1574parser.add_option("-c", action="callback", callback=check_order, dest='c')
1575\end{verbatim}
1576
Greg Wardb6f7fb72004-09-28 01:30:23 +00001577
Greg Warde644a1b2004-10-01 01:16:39 +00001578\subsubsection{Callback example 4: check arbitrary condition\label{optparse-callback-example-4}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001579
1580Of course, you could put any condition in there{---}you're not limited
Neal Norwitz488609e2003-01-06 16:51:37 +00001581to checking the values of already-defined options. For example, if
1582you have options that should not be called when the moon is full, all
1583you have to do is this:
Neal Norwitz488609e2003-01-06 16:51:37 +00001584\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001585def check_moon(option, opt_str, value, parser):
1586 if is_moon_full():
1587 raise OptionValueError("%s option invalid when moon is full"
1588 % opt_str)
Neal Norwitz488609e2003-01-06 16:51:37 +00001589 setattr(parser.values, option.dest, 1)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001590[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001591parser.add_option("--foo",
1592 action="callback", callback=check_moon, dest="foo")
1593\end{verbatim}
1594
Greg Wardb6f7fb72004-09-28 01:30:23 +00001595(The definition of \code{is{\_}moon{\_}full()} is left as an exercise for the
Neal Norwitz488609e2003-01-06 16:51:37 +00001596reader.)
1597
Greg Wardb6f7fb72004-09-28 01:30:23 +00001598
Greg Warde644a1b2004-10-01 01:16:39 +00001599\subsubsection{Callback example 5: fixed arguments\label{optparse-callback-example-5}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001600
1601Things get slightly more interesting when you define callback options
1602that take a fixed number of arguments. Specifying that a callback
Greg Wardb6f7fb72004-09-28 01:30:23 +00001603option takes arguments is similar to defining a \code{store} or \code{append}
1604option: if you define \member{type}, then the option takes one argument that
1605must be convertible to that type; if you further define \code{nargs}, then
1606the option takes \code{nargs} arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +00001607
Greg Wardb6f7fb72004-09-28 01:30:23 +00001608Here's an example that just emulates the standard \code{store} action:
Neal Norwitz488609e2003-01-06 16:51:37 +00001609\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001610def store_value(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001611 setattr(parser.values, option.dest, value)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001612[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001613parser.add_option("--foo",
1614 action="callback", callback=store_value,
1615 type="int", nargs=3, dest="foo")
1616\end{verbatim}
1617
Greg Wardb6f7fb72004-09-28 01:30:23 +00001618Note that \module{optparse} takes care of consuming 3 arguments and converting them
1619to integers for you; all you have to do is store them. (Or whatever;
1620obviously you don't need a callback for this example.)
Neal Norwitz488609e2003-01-06 16:51:37 +00001621
Greg Wardb6f7fb72004-09-28 01:30:23 +00001622
Greg Warde644a1b2004-10-01 01:16:39 +00001623\subsubsection{Callback example 6: variable arguments\label{optparse-callback-example-6}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001624
1625Things get hairy when you want an option to take a variable number of
Greg Wardb6f7fb72004-09-28 01:30:23 +00001626arguments. For this case, you must write a callback, as \module{optparse} doesn't
1627provide any built-in capabilities for it. And you have to deal with
1628certain intricacies of conventional \UNIX{} command-line parsing that \module{optparse}
1629normally handles for you. In particular, callbacks should implement
1630the conventional rules for bare \code{"-{}-"} and \code{"-"} arguments:
Neal Norwitz488609e2003-01-06 16:51:37 +00001631\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001632\item {}
1633either \code{"-{}-"} or \code{"-"} can be option arguments
Neal Norwitz488609e2003-01-06 16:51:37 +00001634
Greg Wardb6f7fb72004-09-28 01:30:23 +00001635\item {}
1636bare \code{"-{}-"} (if not the argument to some option): halt command-line
1637processing and discard the \code{"-{}-"}
Neal Norwitz488609e2003-01-06 16:51:37 +00001638
Greg Wardb6f7fb72004-09-28 01:30:23 +00001639\item {}
1640bare \code{"-"} (if not the argument to some option): halt command-line
1641processing but keep the \code{"-"} (append it to \code{parser.largs})
1642
Neal Norwitz488609e2003-01-06 16:51:37 +00001643\end{itemize}
1644
1645If you want an option that takes a variable number of arguments, there
1646are several subtle, tricky issues to worry about. The exact
1647implementation you choose will be based on which trade-offs you're
Greg Wardb6f7fb72004-09-28 01:30:23 +00001648willing to make for your application (which is why \module{optparse} doesn't support
1649this sort of thing directly).
Neal Norwitz488609e2003-01-06 16:51:37 +00001650
1651Nevertheless, here's a stab at a callback for an option with variable
1652arguments:
Neal Norwitz488609e2003-01-06 16:51:37 +00001653\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001654def vararg_callback(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001655 assert value is None
1656 done = 0
1657 value = []
1658 rargs = parser.rargs
1659 while rargs:
1660 arg = rargs[0]
1661
1662 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1663 # etc. Note that this also stops on "-3" or "-3.0", so if
1664 # your option takes numeric values, you will need to handle
1665 # this.
1666 if ((arg[:2] == "--" and len(arg) > 2) or
1667 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1668 break
1669 else:
1670 value.append(arg)
1671 del rargs[0]
1672
1673 setattr(parser.values, option.dest, value)
1674
Greg Wardb6f7fb72004-09-28 01:30:23 +00001675[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001676parser.add_option("-c", "--callback",
1677 action="callback", callback=varargs)
1678\end{verbatim}
1679
1680The main weakness with this particular implementation is that negative
Greg Wardb6f7fb72004-09-28 01:30:23 +00001681numbers in the arguments following \code{"-c"} will be interpreted as
1682further options (probably causing an error), rather than as arguments to
1683\code{"-c"}. Fixing this is left as an exercise for the reader.
Greg Warde644a1b2004-10-01 01:16:39 +00001684% $Id: callbacks.txt 415 2004-09-30 02:26:17Z greg $
Neal Norwitz488609e2003-01-06 16:51:37 +00001685
Greg Wardc5221e12006-06-10 16:40:01 +00001686
1687\subsection{Extending \module{optparse}\label{optparse-extending-optparse}}
1688
1689Since the two major controlling factors in how \module{optparse} interprets
1690command-line options are the action and type of each option, the most
1691likely direction of extension is to add new actions and new types.
1692
1693
1694\subsubsection{Adding new types\label{optparse-adding-new-types}}
1695
1696To add new types, you need to define your own subclass of \module{optparse}'s Option
1697class. This class has a couple of attributes that define \module{optparse}'s types:
1698\member{TYPES} and \member{TYPE{\_}CHECKER}.
1699
1700\member{TYPES} is a tuple of type names; in your subclass, simply define a new
1701tuple \member{TYPES} that builds on the standard one.
1702
1703\member{TYPE{\_}CHECKER} is a dictionary mapping type names to type-checking
1704functions. A type-checking function has the following signature:
1705\begin{verbatim}
1706def check_mytype(option, opt, value)
1707\end{verbatim}
1708
1709where \code{option} is an \class{Option} instance, \code{opt} is an option string
1710(e.g., \code{"-f"}), and \code{value} is the string from the command line that
1711must be checked and converted to your desired type. \code{check{\_}mytype()}
1712should return an object of the hypothetical type \code{mytype}. The value
1713returned by a type-checking function will wind up in the OptionValues
1714instance returned by \method{OptionParser.parse{\_}args()}, or be passed to a
1715callback as the \code{value} parameter.
1716
1717Your type-checking function should raise OptionValueError if it
1718encounters any problems. OptionValueError takes a single string
1719argument, which is passed as-is to OptionParser's \method{error()} method,
1720which in turn prepends the program name and the string \code{"error:"} and
1721prints everything to stderr before terminating the process.
1722
1723Here's a silly example that demonstrates adding a \code{complex} option
1724type to parse Python-style complex numbers on the command line. (This
1725is even sillier than it used to be, because \module{optparse} 1.3 added built-in
1726support for complex numbers, but never mind.)
1727
1728First, the necessary imports:
1729\begin{verbatim}
1730from copy import copy
1731from optparse import Option, OptionValueError
1732\end{verbatim}
1733
1734You need to define your type-checker first, since it's referred to later
1735(in the \member{TYPE{\_}CHECKER} class attribute of your Option subclass):
1736\begin{verbatim}
1737def check_complex(option, opt, value):
1738 try:
1739 return complex(value)
1740 except ValueError:
1741 raise OptionValueError(
1742 "option %s: invalid complex value: %r" % (opt, value))
1743\end{verbatim}
1744
1745Finally, the Option subclass:
1746\begin{verbatim}
1747class MyOption (Option):
1748 TYPES = Option.TYPES + ("complex",)
1749 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1750 TYPE_CHECKER["complex"] = check_complex
1751\end{verbatim}
1752
1753(If we didn't make a \function{copy()} of \member{Option.TYPE{\_}CHECKER}, we would end
1754up modifying the \member{TYPE{\_}CHECKER} attribute of \module{optparse}'s Option class.
1755This being Python, nothing stops you from doing that except good manners
1756and common sense.)
1757
1758That's it! Now you can write a script that uses the new option type
1759just like any other \module{optparse}-based script, except you have to instruct your
1760OptionParser to use MyOption instead of Option:
1761\begin{verbatim}
1762parser = OptionParser(option_class=MyOption)
1763parser.add_option("-c", type="complex")
1764\end{verbatim}
1765
1766Alternately, you can build your own option list and pass it to
1767OptionParser; if you don't use \method{add{\_}option()} in the above way, you
1768don't need to tell OptionParser which option class to use:
1769\begin{verbatim}
1770option_list = [MyOption("-c", action="store", type="complex", dest="c")]
1771parser = OptionParser(option_list=option_list)
1772\end{verbatim}
1773
1774
1775\subsubsection{Adding new actions\label{optparse-adding-new-actions}}
1776
1777Adding new actions is a bit trickier, because you have to understand
1778that \module{optparse} has a couple of classifications for actions:
1779\begin{description}
1780\item[``store'' actions]
1781actions that result in \module{optparse} storing a value to an attribute of the
1782current OptionValues instance; these options require a \member{dest}
1783attribute to be supplied to the Option constructor
1784\item[``typed'' actions]
1785actions that take a value from the command line and expect it to be
1786of a certain type; or rather, a string that can be converted to a
1787certain type. These options require a \member{type} attribute to the
1788Option constructor.
1789\end{description}
1790
1791These are overlapping sets: some default ``store'' actions are \code{store},
1792\code{store{\_}const}, \code{append}, and \code{count}, while the default ``typed''
1793actions are \code{store}, \code{append}, and \code{callback}.
1794
1795When you add an action, you need to categorize it by listing it in at
1796least one of the following class attributes of Option (all are lists of
1797strings):
1798\begin{description}
1799\item[\member{ACTIONS}]
1800all actions must be listed in ACTIONS
1801\item[\member{STORE{\_}ACTIONS}]
1802``store'' actions are additionally listed here
1803\item[\member{TYPED{\_}ACTIONS}]
1804``typed'' actions are additionally listed here
1805\item[\code{ALWAYS{\_}TYPED{\_}ACTIONS}]
1806actions that always take a type (i.e. whose options always take a
1807value) are additionally listed here. The only effect of this is
1808that \module{optparse} assigns the default type, \code{string}, to options with no
1809explicit type whose action is listed in \code{ALWAYS{\_}TYPED{\_}ACTIONS}.
1810\end{description}
1811
1812In order to actually implement your new action, you must override
1813Option's \method{take{\_}action()} method and add a case that recognizes your
1814action.
1815
1816For example, let's add an \code{extend} action. This is similar to the
1817standard \code{append} action, but instead of taking a single value from
1818the command-line and appending it to an existing list, \code{extend} will
1819take multiple values in a single comma-delimited string, and extend an
1820existing list with them. That is, if \code{"-{}-names"} is an \code{extend}
1821option of type \code{string}, the command line
1822\begin{verbatim}
1823--names=foo,bar --names blah --names ding,dong
1824\end{verbatim}
1825
1826would result in a list
1827\begin{verbatim}
1828["foo", "bar", "blah", "ding", "dong"]
1829\end{verbatim}
1830
1831Again we define a subclass of Option:
1832\begin{verbatim}
1833class MyOption (Option):
1834
1835 ACTIONS = Option.ACTIONS + ("extend",)
1836 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1837 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1838 ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)
1839
1840 def take_action(self, action, dest, opt, value, values, parser):
1841 if action == "extend":
1842 lvalue = value.split(",")
1843 values.ensure_value(dest, []).extend(lvalue)
1844 else:
1845 Option.take_action(
1846 self, action, dest, opt, value, values, parser)
1847\end{verbatim}
1848
1849Features of note:
1850\begin{itemize}
1851\item {}
1852\code{extend} both expects a value on the command-line and stores that
1853value somewhere, so it goes in both \member{STORE{\_}ACTIONS} and
1854\member{TYPED{\_}ACTIONS}
1855
1856\item {}
1857to ensure that \module{optparse} assigns the default type of \code{string} to
1858\code{extend} actions, we put the \code{extend} action in
1859\code{ALWAYS{\_}TYPED{\_}ACTIONS} as well
1860
1861\item {}
1862\method{MyOption.take{\_}action()} implements just this one new action, and
1863passes control back to \method{Option.take{\_}action()} for the standard
1864\module{optparse} actions
1865
1866\item {}
1867\code{values} is an instance of the optparse{\_}parser.Values class,
1868which provides the very useful \method{ensure{\_}value()} method.
1869\method{ensure{\_}value()} is essentially \function{getattr()} with a safety valve;
1870it is called as
1871\begin{verbatim}
1872values.ensure_value(attr, value)
1873\end{verbatim}
1874
1875If the \code{attr} attribute of \code{values} doesn't exist or is None, then
1876ensure{\_}value() first sets it to \code{value}, and then returns 'value.
1877This is very handy for actions like \code{extend}, \code{append}, and
1878\code{count}, all of which accumulate data in a variable and expect that
1879variable to be of a certain type (a list for the first two, an integer
1880for the latter). Using \method{ensure{\_}value()} means that scripts using
1881your action don't have to worry about setting a default value for the
1882option destinations in question; they can just leave the default as
1883None and \method{ensure{\_}value()} will take care of getting it right when
1884it's needed.
1885
1886\end{itemize}
1887% $Id: extending.txt 517 2006-06-10 16:18:11Z gward $
1888