blob: ec43e3df909043affa12d7770187733fbf1d6660 [file] [log] [blame]
Greg Wardb6f7fb72004-09-28 01:30:23 +00001\section{\module{optparse} --- More powerful command line option parser}
Neal Norwitz488609e2003-01-06 16:51:37 +00002\declaremodule{standard}{optparse}
3\moduleauthor{Greg Ward}{gward@python.net}
Greg Wardb6f7fb72004-09-28 01:30:23 +00004\modulesynopsis{More convenient, flexible, and powerful command-line parsing library.}
Neal Norwitz488609e2003-01-06 16:51:37 +00005\versionadded{2.3}
Greg Wardb6f7fb72004-09-28 01:30:23 +00006\sectionauthor{Greg Ward}{gward@python.net}
7% An intro blurb used only when generating LaTeX docs for the Python
8% manual (based on README.txt).
Neal Norwitz488609e2003-01-06 16:51:37 +00009
Greg Wardb6f7fb72004-09-28 01:30:23 +000010\code{optparse} is a more convenient, flexible, and powerful library for
11parsing command-line options than \code{getopt}. \code{optparse} uses a more
12declarative style of command-line parsing: you create an instance of
13\class{OptionParser}, populate it with options, and parse the command line.
14\code{optparse} allows users to specify options in the conventional GNU/POSIX
15syntax, and additionally generates usage and help messages for you.
Neal Norwitz488609e2003-01-06 16:51:37 +000016
Greg Wardb6f7fb72004-09-28 01:30:23 +000017Here's an example of using \code{optparse} in a simple script:
Neal Norwitz488609e2003-01-06 16:51:37 +000018\begin{verbatim}
19from optparse import OptionParser
Greg Wardb6f7fb72004-09-28 01:30:23 +000020[...]
Neal Norwitz488609e2003-01-06 16:51:37 +000021parser = OptionParser()
22parser.add_option("-f", "--file", dest="filename",
23 help="write report to FILE", metavar="FILE")
24parser.add_option("-q", "--quiet",
Greg Ward1f535172003-05-03 20:13:08 +000025 action="store_false", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +000026 help="don't print status messages to stdout")
27
Greg Wardb6f7fb72004-09-28 01:30:23 +000028(options, args) = parser.parse_args()
Neal Norwitz488609e2003-01-06 16:51:37 +000029\end{verbatim}
30
31With these few lines of code, users of your script can now do the
Greg Wardb6f7fb72004-09-28 01:30:23 +000032``usual thing'' on the command-line, for example:
Neal Norwitz488609e2003-01-06 16:51:37 +000033\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +000034<yourscript> --file=outfile -q
Neal Norwitz488609e2003-01-06 16:51:37 +000035\end{verbatim}
36
Greg Wardb6f7fb72004-09-28 01:30:23 +000037As it parses the command line, \code{optparse} sets attributes of the
Greg Wardab05edc2006-04-23 03:47:58 +000038\code{options} object returned by \method{parse{\_}args()} based on user-supplied
Greg Wardb6f7fb72004-09-28 01:30:23 +000039command-line values. When \method{parse{\_}args()} returns from parsing this
Greg Wardab05edc2006-04-23 03:47:58 +000040command line, \code{options.filename} will be \code{"outfile"} and
Greg Wardb6f7fb72004-09-28 01:30:23 +000041\code{options.verbose} will be \code{False}. \code{optparse} supports both long
42and short options, allows short options to be merged together, and
43allows options to be associated with their arguments in a variety of
44ways. Thus, the following command lines are all equivalent to the above
45example:
Neal Norwitz488609e2003-01-06 16:51:37 +000046\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +000047<yourscript> -f outfile --quiet
48<yourscript> --quiet --file outfile
49<yourscript> -q -foutfile
50<yourscript> -qfoutfile
Neal Norwitz488609e2003-01-06 16:51:37 +000051\end{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +000052
53Additionally, users can run one of
54\begin{verbatim}
55<yourscript> -h
56<yourscript> --help
57\end{verbatim}
58
59and \code{optparse} will print out a brief summary of your script's
Neal Norwitz488609e2003-01-06 16:51:37 +000060options:
Neal Norwitz488609e2003-01-06 16:51:37 +000061\begin{verbatim}
62usage: <yourscript> [options]
63
64options:
Greg Wardb6f7fb72004-09-28 01:30:23 +000065 -h, --help show this help message and exit
66 -f FILE, --file=FILE write report to FILE
67 -q, --quiet don't print status messages to stdout
Neal Norwitz488609e2003-01-06 16:51:37 +000068\end{verbatim}
69
Greg Wardb6f7fb72004-09-28 01:30:23 +000070where the value of \emph{yourscript} is determined at runtime (normally
71from \code{sys.argv{[}0]}).
Greg Warde644a1b2004-10-01 01:16:39 +000072% $Id: intro.txt 413 2004-09-28 00:59:13Z greg $
Neal Norwitz488609e2003-01-06 16:51:37 +000073
Neal Norwitz488609e2003-01-06 16:51:37 +000074
Greg Wardb6f7fb72004-09-28 01:30:23 +000075\subsection{Background\label{optparse-background}}
76
77\module{optparse} was explicitly designed to encourage the creation of programs with
78straightforward, conventional command-line interfaces. To that end, it
79supports only the most common command-line syntax and semantics
80conventionally used under \UNIX{}. If you are unfamiliar with these
81conventions, read this section to acquaint yourself with them.
82
Neal Norwitz488609e2003-01-06 16:51:37 +000083
84\subsubsection{Terminology\label{optparse-terminology}}
Greg Wardb6f7fb72004-09-28 01:30:23 +000085\begin{description}
86\item[argument]
87a string entered on the command-line, and passed by the shell to
88\code{execl()} or \code{execv()}. In Python, arguments are elements of
89\code{sys.argv{[}1:]} (\code{sys.argv{[}0]} is the name of the program being
90executed). \UNIX{} shells also use the term ``word''.
Neal Norwitz488609e2003-01-06 16:51:37 +000091
Greg Wardb6f7fb72004-09-28 01:30:23 +000092It is occasionally desirable to substitute an argument list other
93than \code{sys.argv{[}1:]}, so you should read ``argument'' as ``an element of
94\code{sys.argv{[}1:]}, or of some other list provided as a substitute for
95\code{sys.argv{[}1:]}''.
96\item[option ]
97an argument used to supply extra information to guide or customize the
98execution of a program. There are many different syntaxes for
99options; the traditional \UNIX{} syntax is a hyphen (``-'') followed by a
100single letter, e.g. \code{"-x"} or \code{"-F"}. Also, traditional \UNIX{}
101syntax allows multiple options to be merged into a single argument,
102e.g. \code{"-x -F"} is equivalent to \code{"-xF"}. The GNU project
Greg Wardab05edc2006-04-23 03:47:58 +0000103introduced \code{"-{}-"} followed by a series of hyphen-separated words,
104e.g. \code{"-{}-file"} or \code{"-{}-dry-run"}. These are the only two option
Greg Wardb6f7fb72004-09-28 01:30:23 +0000105syntaxes provided by \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000106
Greg Wardb6f7fb72004-09-28 01:30:23 +0000107Some other option syntaxes that the world has seen include:
Neal Norwitz488609e2003-01-06 16:51:37 +0000108\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000109\item {}
110a hyphen followed by a few letters, e.g. \code{"-pf"} (this is
111\emph{not} the same as multiple options merged into a single argument)
112
113\item {}
114a hyphen followed by a whole word, e.g. \code{"-file"} (this is
115technically equivalent to the previous syntax, but they aren't
116usually seen in the same program)
117
118\item {}
119a plus sign followed by a single letter, or a few letters,
120or a word, e.g. \code{"+f"}, \code{"+rgb"}
121
122\item {}
123a slash followed by a letter, or a few letters, or a word, e.g.
124\code{"/f"}, \code{"/file"}
125
Neal Norwitz488609e2003-01-06 16:51:37 +0000126\end{itemize}
127
Greg Wardb6f7fb72004-09-28 01:30:23 +0000128These option syntaxes are not supported by \module{optparse}, and they never will
129be. This is deliberate: the first three are non-standard on any
130environment, and the last only makes sense if you're exclusively
131targeting VMS, MS-DOS, and/or Windows.
132\item[option argument]
Neal Norwitz488609e2003-01-06 16:51:37 +0000133an argument that follows an option, is closely associated with that
Greg Wardb6f7fb72004-09-28 01:30:23 +0000134option, and is consumed from the argument list when that option is.
135With \module{optparse}, option arguments may either be in a separate argument
136from their option:
Neal Norwitz488609e2003-01-06 16:51:37 +0000137\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000138-f foo
139--file foo
Neal Norwitz488609e2003-01-06 16:51:37 +0000140\end{verbatim}
141
Greg Wardb6f7fb72004-09-28 01:30:23 +0000142or included in the same argument:
Neal Norwitz488609e2003-01-06 16:51:37 +0000143\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000144-ffoo
145--file=foo
Neal Norwitz488609e2003-01-06 16:51:37 +0000146\end{verbatim}
147
Greg Wardb6f7fb72004-09-28 01:30:23 +0000148Typically, a given option either takes an argument or it doesn't.
149Lots of people want an ``optional option arguments'' feature, meaning
150that some options will take an argument if they see it, and won't if
151they don't. This is somewhat controversial, because it makes parsing
152ambiguous: if \code{"-a"} takes an optional argument and \code{"-b"} is
153another option entirely, how do we interpret \code{"-ab"}? Because of
154this ambiguity, \module{optparse} does not support this feature.
155\item[positional argument]
Neal Norwitz488609e2003-01-06 16:51:37 +0000156something leftover in the argument list after options have been
Greg Wardb6f7fb72004-09-28 01:30:23 +0000157parsed, i.e. after options and their arguments have been parsed and
Neal Norwitz488609e2003-01-06 16:51:37 +0000158removed from the argument list.
Greg Wardb6f7fb72004-09-28 01:30:23 +0000159\item[required option]
160an option that must be supplied on the command-line; note that the
161phrase ``required option'' is self-contradictory in English. \module{optparse}
162doesn't prevent you from implementing required options, but doesn't
163give you much help at it either. See \code{examples/required{\_}1.py} and
164\code{examples/required{\_}2.py} in the \module{optparse} source distribution for two
165ways to implement required options with \module{optparse}.
166\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +0000167
168For example, consider this hypothetical command-line:
Neal Norwitz488609e2003-01-06 16:51:37 +0000169\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000170prog -v --report /tmp/report.txt foo bar
Neal Norwitz488609e2003-01-06 16:51:37 +0000171\end{verbatim}
172
Greg Wardab05edc2006-04-23 03:47:58 +0000173\code{"-v"} and \code{"-{}-report"} are both options. Assuming that
Greg Wardb6f7fb72004-09-28 01:30:23 +0000174\longprogramopt{report} takes one argument, \code{"/tmp/report.txt"} is an option
175argument. \code{"foo"} and \code{"bar"} are positional arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +0000176
Greg Wardb6f7fb72004-09-28 01:30:23 +0000177
Greg Warde644a1b2004-10-01 01:16:39 +0000178\subsubsection{What are options for?\label{optparse-what-options-for}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000179
180Options are used to provide extra information to tune or customize the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000181execution of a program. In case it wasn't clear, options are usually
182\emph{optional}. A program should be able to run just fine with no options
183whatsoever. (Pick a random program from the \UNIX{} or GNU toolsets. Can
184it run without any options at all and still make sense? The main
185exceptions are \code{find}, \code{tar}, and \code{dd}{---}all of which are mutant
186oddballs that have been rightly criticized for their non-standard syntax
187and confusing interfaces.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000188
Greg Wardb6f7fb72004-09-28 01:30:23 +0000189Lots of people want their programs to have ``required options''. Think
190about it. If it's required, then it's \emph{not optional}! If there is a
191piece of information that your program absolutely requires in order to
192run successfully, that's what positional arguments are for.
Neal Norwitz488609e2003-01-06 16:51:37 +0000193
Greg Wardb6f7fb72004-09-28 01:30:23 +0000194As an example of good command-line interface design, consider the humble
195\code{cp} utility, for copying files. It doesn't make much sense to try to
196copy files without supplying a destination and at least one source.
197Hence, \code{cp} fails if you run it with no arguments. However, it has a
198flexible, useful syntax that does not require any options at all:
Neal Norwitz488609e2003-01-06 16:51:37 +0000199\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000200cp SOURCE DEST
201cp SOURCE ... DEST-DIR
Neal Norwitz488609e2003-01-06 16:51:37 +0000202\end{verbatim}
203
Greg Wardb6f7fb72004-09-28 01:30:23 +0000204You can get pretty far with just that. Most \code{cp} implementations
205provide a bunch of options to tweak exactly how the files are copied:
206you can preserve mode and modification time, avoid following symlinks,
207ask before clobbering existing files, etc. But none of this distracts
208from the core mission of \code{cp}, which is to copy either one file to
209another, or several files to another directory.
Neal Norwitz488609e2003-01-06 16:51:37 +0000210
Neal Norwitz488609e2003-01-06 16:51:37 +0000211
Greg Warde644a1b2004-10-01 01:16:39 +0000212\subsubsection{What are positional arguments for?\label{optparse-what-positional-arguments-for}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000213
214Positional arguments are for those pieces of information that your
215program absolutely, positively requires to run.
Neal Norwitz488609e2003-01-06 16:51:37 +0000216
217A good user interface should have as few absolute requirements as
218possible. If your program requires 17 distinct pieces of information in
219order to run successfully, it doesn't much matter \emph{how} you get that
Greg Wardb6f7fb72004-09-28 01:30:23 +0000220information from the user{---}most people will give up and walk away
Neal Norwitz488609e2003-01-06 16:51:37 +0000221before they successfully run the program. This applies whether the user
Greg Wardb6f7fb72004-09-28 01:30:23 +0000222interface is a command-line, a configuration file, or a GUI: if you make
223that many demands on your users, most of them will simply give up.
Neal Norwitz488609e2003-01-06 16:51:37 +0000224
225In short, try to minimize the amount of information that users are
Greg Wardb6f7fb72004-09-28 01:30:23 +0000226absolutely required to supply{---}use sensible defaults whenever
Neal Norwitz488609e2003-01-06 16:51:37 +0000227possible. Of course, you also want to make your programs reasonably
228flexible. That's what options are for. Again, it doesn't matter if
Greg Wardb6f7fb72004-09-28 01:30:23 +0000229they are entries in a config file, widgets in the ``Preferences'' dialog
230of a GUI, or command-line options{---}the more options you implement, the
231more flexible your program is, and the more complicated its
232implementation becomes. Too much flexibility has drawbacks as well, of
233course; too many options can overwhelm users and make your code much
234harder to maintain.
Greg Warde644a1b2004-10-01 01:16:39 +0000235% $Id: tao.txt 413 2004-09-28 00:59:13Z greg $
Neal Norwitz488609e2003-01-06 16:51:37 +0000236
Neal Norwitz488609e2003-01-06 16:51:37 +0000237
Greg Wardb6f7fb72004-09-28 01:30:23 +0000238\subsection{Tutorial\label{optparse-tutorial}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000239
Greg Wardb6f7fb72004-09-28 01:30:23 +0000240While \module{optparse} is quite flexible and powerful, it's also straightforward to
241use in most cases. This section covers the code patterns that are
242common to any \module{optparse}-based program.
Neal Norwitz488609e2003-01-06 16:51:37 +0000243
Greg Wardb6f7fb72004-09-28 01:30:23 +0000244First, you need to import the OptionParser class; then, early in the
245main program, create an OptionParser instance:
Neal Norwitz488609e2003-01-06 16:51:37 +0000246\begin{verbatim}
247from optparse import OptionParser
Greg Wardb6f7fb72004-09-28 01:30:23 +0000248[...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000249parser = OptionParser()
250\end{verbatim}
251
Greg Wardb6f7fb72004-09-28 01:30:23 +0000252Then you can start defining options. The basic syntax is:
253\begin{verbatim}
254parser.add_option(opt_str, ...,
255 attr=value, ...)
256\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000257
Greg Wardb6f7fb72004-09-28 01:30:23 +0000258Each option has one or more option strings, such as \code{"-f"} or
259\code{"-{}-file"}, and several option attributes that tell \module{optparse} what to
260expect and what to do when it encounters that option on the command
261line.
262
263Typically, each option will have one short option string and one long
264option string, e.g.:
Neal Norwitz488609e2003-01-06 16:51:37 +0000265\begin{verbatim}
266parser.add_option("-f", "--file", ...)
267\end{verbatim}
268
Greg Wardb6f7fb72004-09-28 01:30:23 +0000269You're free to define as many short option strings and as many long
270option strings as you like (including zero), as long as there is at
271least one option string overall.
Neal Norwitz488609e2003-01-06 16:51:37 +0000272
Greg Wardb6f7fb72004-09-28 01:30:23 +0000273The option strings passed to \method{add{\_}option()} are effectively labels for
274the option defined by that call. For brevity, we will frequently refer
275to \emph{encountering an option} on the command line; in reality, \module{optparse}
276encounters \emph{option strings} and looks up options from them.
Neal Norwitz488609e2003-01-06 16:51:37 +0000277
Greg Wardb6f7fb72004-09-28 01:30:23 +0000278Once all of your options are defined, instruct \module{optparse} to parse your
279program's command line:
280\begin{verbatim}
281(options, args) = parser.parse_args()
282\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000283
Greg Wardb6f7fb72004-09-28 01:30:23 +0000284(If you like, you can pass a custom argument list to \method{parse{\_}args()},
285but that's rarely necessary: by default it uses \code{sys.argv{[}1:]}.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000286
Greg Wardb6f7fb72004-09-28 01:30:23 +0000287\method{parse{\_}args()} returns two values:
288\begin{itemize}
289\item {}
Greg Wardab05edc2006-04-23 03:47:58 +0000290\code{options}, an object containing values for all of your options{---}e.g. if \code{"-{}-file"} takes a single string argument, then
291\code{options.file} will be the filename supplied by the user, or
Greg Wardb6f7fb72004-09-28 01:30:23 +0000292\code{None} if the user did not supply that option
293
294\item {}
Greg Wardab05edc2006-04-23 03:47:58 +0000295\code{args}, the list of positional arguments leftover after parsing
Greg Wardb6f7fb72004-09-28 01:30:23 +0000296options
297
298\end{itemize}
299
300This tutorial section only covers the four most important option
301attributes: \member{action}, \member{type}, \member{dest} (destination), and \member{help}.
302Of these, \member{action} is the most fundamental.
303
304
Greg Warde644a1b2004-10-01 01:16:39 +0000305\subsubsection{Understanding option actions\label{optparse-understanding-option-actions}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000306
307Actions tell \module{optparse} what to do when it encounters an option on the
308command line. There is a fixed set of actions hard-coded into \module{optparse};
309adding new actions is an advanced topic covered in section~\ref{optparse-extending}, Extending \module{optparse}.
310Most actions tell \module{optparse} to store a value in some variable{---}for
311example, take a string from the command line and store it in an
Greg Wardab05edc2006-04-23 03:47:58 +0000312attribute of \code{options}.
Greg Wardb6f7fb72004-09-28 01:30:23 +0000313
314If you don't specify an option action, \module{optparse} defaults to \code{store}.
315
316
Greg Warde644a1b2004-10-01 01:16:39 +0000317\subsubsection{The store action\label{optparse-store-action}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000318
319The most common option action is \code{store}, which tells \module{optparse} to take
320the next argument (or the remainder of the current argument), ensure
321that it is of the correct type, and store it to your chosen destination.
322
323For example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000324\begin{verbatim}
325parser.add_option("-f", "--file",
326 action="store", type="string", dest="filename")
327\end{verbatim}
328
Greg Wardb6f7fb72004-09-28 01:30:23 +0000329Now let's make up a fake command line and ask \module{optparse} to parse it:
Neal Norwitz488609e2003-01-06 16:51:37 +0000330\begin{verbatim}
331args = ["-f", "foo.txt"]
Greg Wardb6f7fb72004-09-28 01:30:23 +0000332(options, args) = parser.parse_args(args)
Neal Norwitz488609e2003-01-06 16:51:37 +0000333\end{verbatim}
334
Greg Wardb6f7fb72004-09-28 01:30:23 +0000335When \module{optparse} sees the option string \code{"-f"}, it consumes the next
Greg Wardab05edc2006-04-23 03:47:58 +0000336argument, \code{"foo.txt"}, and stores it in \code{options.filename}. So,
337after this call to \method{parse{\_}args()}, \code{options.filename} is
Greg Wardb6f7fb72004-09-28 01:30:23 +0000338\code{"foo.txt"}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000339
Greg Wardb6f7fb72004-09-28 01:30:23 +0000340Some other option types supported by \module{optparse} are \code{int} and \code{float}.
341Here's an option that expects an integer argument:
Neal Norwitz488609e2003-01-06 16:51:37 +0000342\begin{verbatim}
343parser.add_option("-n", type="int", dest="num")
344\end{verbatim}
345
Greg Wardb6f7fb72004-09-28 01:30:23 +0000346Note that this option has no long option string, which is perfectly
347acceptable. Also, there's no explicit action, since the default is
348\code{store}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000349
Greg Wardb6f7fb72004-09-28 01:30:23 +0000350Let's parse another fake command-line. This time, we'll jam the option
351argument right up against the option: since \code{"-n42"} (one argument) is
352equivalent to \code{"-n 42"} (two arguments), the code
Neal Norwitz488609e2003-01-06 16:51:37 +0000353\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000354(options, args) = parser.parse_args(["-n42"])
Neal Norwitz488609e2003-01-06 16:51:37 +0000355print options.num
356\end{verbatim}
357
Greg Wardb6f7fb72004-09-28 01:30:23 +0000358will print \code{"42"}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000359
Greg Wardb6f7fb72004-09-28 01:30:23 +0000360If you don't specify a type, \module{optparse} assumes \code{string}. Combined with the
361fact that the default action is \code{store}, that means our first example
362can be a lot shorter:
Neal Norwitz488609e2003-01-06 16:51:37 +0000363\begin{verbatim}
364parser.add_option("-f", "--file", dest="filename")
365\end{verbatim}
366
Greg Wardb6f7fb72004-09-28 01:30:23 +0000367If you don't supply a destination, \module{optparse} figures out a sensible default
368from the option strings: if the first long option string is
369\code{"-{}-foo-bar"}, then the default destination is \code{foo{\_}bar}. If there
370are no long option strings, \module{optparse} looks at the first short option
371string: the default destination for \code{"-f"} is \code{f}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000372
Greg Wardb6f7fb72004-09-28 01:30:23 +0000373\module{optparse} also includes built-in \code{long} and \code{complex} types. Adding
374types is covered in section~\ref{optparse-extending}, Extending \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000375
Neal Norwitz488609e2003-01-06 16:51:37 +0000376
Greg Warde644a1b2004-10-01 01:16:39 +0000377\subsubsection{Handling boolean (flag) options\label{optparse-handling-boolean-options}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000378
Greg Wardb6f7fb72004-09-28 01:30:23 +0000379Flag options{---}set a variable to true or false when a particular option
380is seen{---}are quite common. \module{optparse} supports them with two separate
381actions, \code{store{\_}true} and \code{store{\_}false}. For example, you might have a
Greg Wardab05edc2006-04-23 03:47:58 +0000382\code{verbose} flag that is turned on with \code{"-v"} and off with \code{"-q"}:
Neal Norwitz488609e2003-01-06 16:51:37 +0000383\begin{verbatim}
384parser.add_option("-v", action="store_true", dest="verbose")
385parser.add_option("-q", action="store_false", dest="verbose")
386\end{verbatim}
387
388Here we have two different options with the same destination, which is
389perfectly OK. (It just means you have to be a bit careful when setting
Greg Warde644a1b2004-10-01 01:16:39 +0000390default values{---}see below.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000391
Greg Wardb6f7fb72004-09-28 01:30:23 +0000392When \module{optparse} encounters \code{"-v"} on the command line, it sets
393\code{options.verbose} to \code{True}; when it encounters \code{"-q"},
394\code{options.verbose} is set to \code{False}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000395
Greg Wardb6f7fb72004-09-28 01:30:23 +0000396
397\subsubsection{Other actions\label{optparse-other-actions}}
398
399Some other actions supported by \module{optparse} are:
400\begin{description}
401\item[\code{store{\_}const}]
402store a constant value
403\item[\code{append}]
404append this option's argument to a list
405\item[\code{count}]
406increment a counter by one
407\item[\code{callback}]
408call a specified function
409\end{description}
410
Greg Warde644a1b2004-10-01 01:16:39 +0000411These are covered in section~\ref{optparse-reference-guide}, Reference Guide and section~\ref{optparse-option-callbacks}, Option Callbacks.
Greg Wardb6f7fb72004-09-28 01:30:23 +0000412
413
414\subsubsection{Default values\label{optparse-default-values}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000415
416All of the above examples involve setting some variable (the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000417``destination'') when certain command-line options are seen. What happens
418if those options are never seen? Since we didn't supply any defaults,
419they are all set to \code{None}. This is usually fine, but sometimes you
420want more control. \module{optparse} lets you supply a default value for each
421destination, which is assigned before the command line is parsed.
Neal Norwitz488609e2003-01-06 16:51:37 +0000422
Greg Wardb6f7fb72004-09-28 01:30:23 +0000423First, consider the verbose/quiet example. If we want \module{optparse} to set
Greg Wardab05edc2006-04-23 03:47:58 +0000424\code{verbose} to \code{True} unless \code{"-q"} is seen, then we can do this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000425\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000426parser.add_option("-v", action="store_true", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000427parser.add_option("-q", action="store_false", dest="verbose")
428\end{verbatim}
429
Greg Wardb6f7fb72004-09-28 01:30:23 +0000430Since default values apply to the \emph{destination} rather than to any
431particular option, and these two options happen to have the same
432destination, this is exactly equivalent:
Neal Norwitz488609e2003-01-06 16:51:37 +0000433\begin{verbatim}
434parser.add_option("-v", action="store_true", dest="verbose")
Greg Ward1f535172003-05-03 20:13:08 +0000435parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000436\end{verbatim}
437
Neal Norwitz488609e2003-01-06 16:51:37 +0000438Consider this:
Neal Norwitz488609e2003-01-06 16:51:37 +0000439\begin{verbatim}
Greg Ward1f535172003-05-03 20:13:08 +0000440parser.add_option("-v", action="store_true", dest="verbose", default=False)
441parser.add_option("-q", action="store_false", dest="verbose", default=True)
Neal Norwitz488609e2003-01-06 16:51:37 +0000442\end{verbatim}
443
Greg Wardab05edc2006-04-23 03:47:58 +0000444Again, the default value for \code{verbose} will be \code{True}: the last
Greg Wardd7231282003-05-03 21:22:58 +0000445default value supplied for any particular destination is the one that
446counts.
Neal Norwitz488609e2003-01-06 16:51:37 +0000447
Greg Wardb6f7fb72004-09-28 01:30:23 +0000448A clearer way to specify default values is the \method{set{\_}defaults()}
449method of OptionParser, which you can call at any time before calling
450\method{parse{\_}args()}:
451\begin{verbatim}
452parser.set_defaults(verbose=True)
453parser.add_option(...)
454(options, args) = parser.parse_args()
455\end{verbatim}
456
457As before, the last value specified for a given option destination is
458the one that counts. For clarity, try to use one method or the other of
459setting default values, not both.
460
461
Neal Norwitz488609e2003-01-06 16:51:37 +0000462\subsubsection{Generating help\label{optparse-generating-help}}
463
Greg Wardb6f7fb72004-09-28 01:30:23 +0000464\module{optparse}'s ability to generate help and usage text automatically is useful
465for creating user-friendly command-line interfaces. All you have to do
466is supply a \member{help} value for each option, and optionally a short usage
467message for your whole program. Here's an OptionParser populated with
468user-friendly (documented) options:
Neal Norwitz488609e2003-01-06 16:51:37 +0000469\begin{verbatim}
470usage = "usage: %prog [options] arg1 arg2"
471parser = OptionParser(usage=usage)
472parser.add_option("-v", "--verbose",
Greg Ward1f535172003-05-03 20:13:08 +0000473 action="store_true", dest="verbose", default=True,
Neal Norwitz488609e2003-01-06 16:51:37 +0000474 help="make lots of noise [default]")
475parser.add_option("-q", "--quiet",
476 action="store_false", dest="verbose",
477 help="be vewwy quiet (I'm hunting wabbits)")
Greg Wardb6f7fb72004-09-28 01:30:23 +0000478parser.add_option("-f", "--filename",
Neal Norwitz488609e2003-01-06 16:51:37 +0000479 metavar="FILE", help="write output to FILE"),
480parser.add_option("-m", "--mode",
481 default="intermediate",
Greg Wardb6f7fb72004-09-28 01:30:23 +0000482 help="interaction mode: novice, intermediate, "
483 "or expert [default: %default]")
Neal Norwitz488609e2003-01-06 16:51:37 +0000484\end{verbatim}
485
Greg Wardb6f7fb72004-09-28 01:30:23 +0000486If \module{optparse} encounters either \code{"-h"} or \code{"-{}-help"} on the command-line,
487or if you just call \method{parser.print{\_}help()}, it prints the following to
488standard output:
Neal Norwitz488609e2003-01-06 16:51:37 +0000489\begin{verbatim}
490usage: <yourscript> [options] arg1 arg2
491
492options:
Greg Wardb6f7fb72004-09-28 01:30:23 +0000493 -h, --help show this help message and exit
494 -v, --verbose make lots of noise [default]
495 -q, --quiet be vewwy quiet (I'm hunting wabbits)
496 -f FILE, --filename=FILE
497 write output to FILE
498 -m MODE, --mode=MODE interaction mode: novice, intermediate, or
499 expert [default: intermediate]
Neal Norwitz488609e2003-01-06 16:51:37 +0000500\end{verbatim}
501
Greg Wardb6f7fb72004-09-28 01:30:23 +0000502(If the help output is triggered by a help option, \module{optparse} exits after
503printing the help text.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000504
Greg Wardb6f7fb72004-09-28 01:30:23 +0000505There's a lot going on here to help \module{optparse} generate the best possible
506help message:
Neal Norwitz488609e2003-01-06 16:51:37 +0000507\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000508\item {}
509the script defines its own usage message:
Neal Norwitz488609e2003-01-06 16:51:37 +0000510\begin{verbatim}
511usage = "usage: %prog [options] arg1 arg2"
512\end{verbatim}
513
Greg Wardb6f7fb72004-09-28 01:30:23 +0000514\module{optparse} expands \code{"{\%}prog"} in the usage string to the name of the current
515program, i.e. \code{os.path.basename(sys.argv{[}0])}. The expanded string
516is then printed before the detailed option help.
Neal Norwitz488609e2003-01-06 16:51:37 +0000517
Greg Wardb6f7fb72004-09-28 01:30:23 +0000518If you don't supply a usage string, \module{optparse} uses a bland but sensible
519default: ``\code{usage: {\%}prog {[}options]"}, which is fine if your script
520doesn't take any positional arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +0000521
Greg Wardb6f7fb72004-09-28 01:30:23 +0000522\item {}
523every option defines a help string, and doesn't worry about line-
524wrapping{---}\module{optparse} takes care of wrapping lines and making the
525help output look good.
Neal Norwitz488609e2003-01-06 16:51:37 +0000526
Greg Wardb6f7fb72004-09-28 01:30:23 +0000527\item {}
528options that take a value indicate this fact in their
Neal Norwitz488609e2003-01-06 16:51:37 +0000529automatically-generated help message, e.g. for the ``mode'' option:
Neal Norwitz488609e2003-01-06 16:51:37 +0000530\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000531-m MODE, --mode=MODE
Neal Norwitz488609e2003-01-06 16:51:37 +0000532\end{verbatim}
533
534Here, ``MODE'' is called the meta-variable: it stands for the argument
Greg Wardb6f7fb72004-09-28 01:30:23 +0000535that the user is expected to supply to \programopt{-m}/\longprogramopt{mode}. By default,
536\module{optparse} converts the destination variable name to uppercase and uses
537that for the meta-variable. Sometimes, that's not what you want{---}for example, the \longprogramopt{filename} option explicitly sets
538\code{metavar="FILE"}, resulting in this automatically-generated option
539description:
Neal Norwitz488609e2003-01-06 16:51:37 +0000540\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000541-f FILE, --filename=FILE
Neal Norwitz488609e2003-01-06 16:51:37 +0000542\end{verbatim}
543
544This is important for more than just saving space, though: the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000545manually written help text uses the meta-variable ``FILE'' to clue the
546user in that there's a connection between the semi-formal syntax ``-f
547FILE'' and the informal semantic description ``write output to FILE''.
548This is a simple but effective way to make your help text a lot
549clearer and more useful for end users.
550
551\item {}
552options that have a default value can include \code{{\%}default} in
553the help string{---}\module{optparse} will replace it with \function{str()} of the
554option's default value. If an option has no default value (or the
555default value is \code{None}), \code{{\%}default} expands to \code{none}.
556
Neal Norwitz488609e2003-01-06 16:51:37 +0000557\end{itemize}
558
Fred Drakecf6d74a2003-04-18 15:50:13 +0000559
Greg Warde644a1b2004-10-01 01:16:39 +0000560\subsubsection{Printing a version string\label{optparse-printing-version-string}}
Fred Drakecf6d74a2003-04-18 15:50:13 +0000561
Greg Wardb6f7fb72004-09-28 01:30:23 +0000562Similar to the brief usage string, \module{optparse} can also print a version string
563for your program. You have to supply the string as the \code{version}
564argument to OptionParser:
Neal Norwitz488609e2003-01-06 16:51:37 +0000565\begin{verbatim}
566parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
567\end{verbatim}
568
Greg Wardab05edc2006-04-23 03:47:58 +0000569Note that \code{"{\%}prog"} is expanded just like it is in \code{usage}. Apart
Greg Wardb6f7fb72004-09-28 01:30:23 +0000570from that, \code{version} can contain anything you like. When you supply
571it, \module{optparse} automatically adds a \code{"-{}-version"} option to your parser.
572If it encounters this option on the command line, it expands your
573\code{version} string (by replacing \code{"{\%}prog"}), prints it to stdout, and
574exits.
Neal Norwitz488609e2003-01-06 16:51:37 +0000575
Greg Wardb6f7fb72004-09-28 01:30:23 +0000576For example, if your script is called \code{/usr/bin/foo}:
Neal Norwitz488609e2003-01-06 16:51:37 +0000577\begin{verbatim}
578$ /usr/bin/foo --version
579foo 1.0
Greg Wardb6f7fb72004-09-28 01:30:23 +0000580\end{verbatim}
581
Neal Norwitz488609e2003-01-06 16:51:37 +0000582
Greg Wardab05edc2006-04-23 03:47:58 +0000583\subsubsection{How \module{optparse} handles errors\label{optparse-how-optparse-handles-errors}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000584
Greg Wardb6f7fb72004-09-28 01:30:23 +0000585There are two broad classes of errors that \module{optparse} has to worry about:
586programmer errors and user errors. Programmer errors are usually
Greg Wardab05edc2006-04-23 03:47:58 +0000587erroneous calls to \code{parser.add{\_}option()}, e.g. invalid option strings,
Greg Wardb6f7fb72004-09-28 01:30:23 +0000588unknown option attributes, missing option attributes, etc. These are
589dealt with in the usual way: raise an exception (either
Greg Wardab05edc2006-04-23 03:47:58 +0000590\code{optparse.OptionError} or \code{TypeError}) and let the program crash.
Neal Norwitz488609e2003-01-06 16:51:37 +0000591
Greg Wardb6f7fb72004-09-28 01:30:23 +0000592Handling user errors is much more important, since they are guaranteed
593to happen no matter how stable your code is. \module{optparse} can automatically
594detect some user errors, such as bad option arguments (passing \code{"-n
5954x"} where \programopt{-n} takes an integer argument), missing arguments
596(\code{"-n"} at the end of the command line, where \programopt{-n} takes an argument
597of any type). Also, you can call \code{parser.error()} to signal an
598application-defined error condition:
599\begin{verbatim}
600(options, args) = parser.parse_args()
601[...]
602if options.a and options.b:
603 parser.error("options -a and -b are mutually exclusive")
604\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000605
Greg Wardb6f7fb72004-09-28 01:30:23 +0000606In either case, \module{optparse} handles the error the same way: it prints the
607program's usage message and an error message to standard error and
608exits with error status 2.
Neal Norwitz488609e2003-01-06 16:51:37 +0000609
Greg Wardb6f7fb72004-09-28 01:30:23 +0000610Consider the first example above, where the user passes \code{"4x"} to an
611option that takes an integer:
612\begin{verbatim}
613$ /usr/bin/foo -n 4x
614usage: foo [options]
Neal Norwitz488609e2003-01-06 16:51:37 +0000615
Greg Wardb6f7fb72004-09-28 01:30:23 +0000616foo: error: option -n: invalid integer value: '4x'
617\end{verbatim}
618
619Or, where the user fails to pass a value at all:
620\begin{verbatim}
621$ /usr/bin/foo -n
622usage: foo [options]
623
624foo: error: -n option requires an argument
625\end{verbatim}
626
627\module{optparse}-generated error messages take care always to mention the option
628involved in the error; be sure to do the same when calling
629\code{parser.error()} from your application code.
630
631If \module{optparse}'s default error-handling behaviour does not suite your needs,
632you'll need to subclass OptionParser and override \code{exit()} and/or
633\method{error()}.
634
635
636\subsubsection{Putting it all together\label{optparse-putting-it-all-together}}
637
638Here's what \module{optparse}-based scripts usually look like:
Neal Norwitz488609e2003-01-06 16:51:37 +0000639\begin{verbatim}
640from optparse import OptionParser
Greg Wardd7231282003-05-03 21:22:58 +0000641[...]
642def main():
Greg Wardb6f7fb72004-09-28 01:30:23 +0000643 usage = "usage: %prog [options] arg"
Neal Norwitz488609e2003-01-06 16:51:37 +0000644 parser = OptionParser(usage)
Greg Wardb6f7fb72004-09-28 01:30:23 +0000645 parser.add_option("-f", "--file", dest="filename",
Neal Norwitz488609e2003-01-06 16:51:37 +0000646 help="read data from FILENAME")
647 parser.add_option("-v", "--verbose",
648 action="store_true", dest="verbose")
649 parser.add_option("-q", "--quiet",
650 action="store_false", dest="verbose")
Greg Wardb6f7fb72004-09-28 01:30:23 +0000651 [...]
652 (options, args) = parser.parse_args()
653 if len(args) != 1:
Neal Norwitz488609e2003-01-06 16:51:37 +0000654 parser.error("incorrect number of arguments")
Neal Norwitz488609e2003-01-06 16:51:37 +0000655 if options.verbose:
Johannes Gijsbersc9c37ca2004-09-11 15:47:30 +0000656 print "reading %s..." % options.filename
Greg Wardb6f7fb72004-09-28 01:30:23 +0000657 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +0000658
659if __name__ == "__main__":
660 main()
661\end{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +0000662% $Id: tutorial.txt 505 2005-07-22 01:52:40Z gward $
Neal Norwitz488609e2003-01-06 16:51:37 +0000663
Neal Norwitz488609e2003-01-06 16:51:37 +0000664
Greg Wardb6f7fb72004-09-28 01:30:23 +0000665\subsection{Reference Guide\label{optparse-reference-guide}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000666
Neal Norwitz488609e2003-01-06 16:51:37 +0000667
Greg Wardab05edc2006-04-23 03:47:58 +0000668\subsubsection{Creating the parser\label{optparse-creating-parser}}
669
670The first step in using \module{optparse} is to create an OptionParser instance:
671\begin{verbatim}
672parser = OptionParser(...)
673\end{verbatim}
674
675The OptionParser constructor has no required arguments, but a number of
676optional keyword arguments. You should always pass them as keyword
677arguments, i.e. do not rely on the order in which the arguments are
678declared.
679\begin{quote}
680\begin{description}
681\item[\code{usage} (default: \code{"{\%}prog {[}options]"})]
682The usage summary to print when your program is run incorrectly or
683with a help option. When \module{optparse} prints the usage string, it expands
684\code{{\%}prog} to \code{os.path.basename(sys.argv{[}0])} (or to \code{prog} if
685you passed that keyword argument). To suppress a usage message,
686pass the special value \code{optparse.SUPPRESS{\_}USAGE}.
687\item[\code{option{\_}list} (default: \code{{[}]})]
688A list of Option objects to populate the parser with. The options
689in \code{option{\_}list} are added after any options in
690\code{standard{\_}option{\_}list} (a class attribute that may be set by
691OptionParser subclasses), but before any version or help options.
692Deprecated; use \method{add{\_}option()} after creating the parser instead.
693\item[\code{option{\_}class} (default: optparse.Option)]
694Class to use when adding options to the parser in \method{add{\_}option()}.
695\item[\code{version} (default: \code{None})]
696A version string to print when the user supplies a version option.
697If you supply a true value for \code{version}, \module{optparse} automatically adds
698a version option with the single option string \code{"-{}-version"}. The
699substring \code{"{\%}prog"} is expanded the same as for \code{usage}.
700\item[\code{conflict{\_}handler} (default: \code{"error"})]
701Specifies what to do when options with conflicting option strings
702are added to the parser; see section~\ref{optparse-conflicts-between-options}, Conflicts between options.
703\item[\code{description} (default: \code{None})]
704A paragraph of text giving a brief overview of your program. \module{optparse}
705reformats this paragraph to fit the current terminal width and
706prints it when the user requests help (after \code{usage}, but before
707the list of options).
708\item[\code{formatter} (default: a new IndentedHelpFormatter)]
709An instance of optparse.HelpFormatter that will be used for
710printing help text. \module{optparse} provides two concrete classes for this
711purpose: IndentedHelpFormatter and TitledHelpFormatter.
712\item[\code{add{\_}help{\_}option} (default: \code{True})]
713If true, \module{optparse} will add a help option (with option strings \code{"-h"}
714and \code{"-{}-help"}) to the parser.
715\item[\code{prog}]
716The string to use when expanding \code{"{\%}prog"} in \code{usage} and
717\code{version} instead of \code{os.path.basename(sys.argv{[}0])}.
718\end{description}
719\end{quote}
720
721
Greg Warde644a1b2004-10-01 01:16:39 +0000722\subsubsection{Populating the parser\label{optparse-populating-parser}}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000723
724There are several ways to populate the parser with options. The
725preferred way is by using \code{OptionParser.add{\_}option()}, as shown in
Greg Warde644a1b2004-10-01 01:16:39 +0000726section~\ref{optparse-tutorial}, the tutorial. \method{add{\_}option()} can be called in one of two
Greg Wardb6f7fb72004-09-28 01:30:23 +0000727ways:
728\begin{itemize}
729\item {}
730pass it an Option instance (as returned by \function{make{\_}option()})
731
732\item {}
733pass it any combination of positional and keyword arguments that are
734acceptable to \function{make{\_}option()} (i.e., to the Option constructor),
735and it will create the Option instance for you
736
737\end{itemize}
738
739The other alternative is to pass a list of pre-constructed Option
740instances to the OptionParser constructor, as in:
Neal Norwitz488609e2003-01-06 16:51:37 +0000741\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000742option_list = [
Neal Norwitz488609e2003-01-06 16:51:37 +0000743 make_option("-f", "--filename",
744 action="store", type="string", dest="filename"),
745 make_option("-q", "--quiet",
Greg Wardb6f7fb72004-09-28 01:30:23 +0000746 action="store_false", dest="verbose"),
747 ]
Neal Norwitz488609e2003-01-06 16:51:37 +0000748parser = OptionParser(option_list=option_list)
749\end{verbatim}
750
Greg Wardb6f7fb72004-09-28 01:30:23 +0000751(\function{make{\_}option()} is a factory function for creating Option instances;
752currently it is an alias for the Option constructor. A future version
753of \module{optparse} may split Option into several classes, and \function{make{\_}option()}
754will pick the right class to instantiate. Do not instantiate Option
755directly.)
Neal Norwitz488609e2003-01-06 16:51:37 +0000756
Neal Norwitz488609e2003-01-06 16:51:37 +0000757
758\subsubsection{Defining options\label{optparse-defining-options}}
759
Greg Wardb6f7fb72004-09-28 01:30:23 +0000760Each Option instance represents a set of synonymous command-line option
Greg Ward961eda72004-11-12 01:20:17 +0000761strings, e.g. \programopt{-f} and \longprogramopt{file}. You can
Greg Wardb6f7fb72004-09-28 01:30:23 +0000762specify any number of short or long option strings, but you must specify
763at least one overall option string.
764
Greg Wardab05edc2006-04-23 03:47:58 +0000765The canonical way to create an Option instance is with the
766\method{add{\_}option()} method of \class{OptionParser}:
Greg Wardb6f7fb72004-09-28 01:30:23 +0000767\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +0000768parser.add_option(opt_str[, ...], attr=value, ...)
Greg Wardb6f7fb72004-09-28 01:30:23 +0000769\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +0000770
771To define an option with only a short option string:
Neal Norwitz488609e2003-01-06 16:51:37 +0000772\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +0000773parser.add_option("-f", attr=value, ...)
Neal Norwitz488609e2003-01-06 16:51:37 +0000774\end{verbatim}
775
776And to define an option with only a long option string:
Neal Norwitz488609e2003-01-06 16:51:37 +0000777\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +0000778parser.add_option("--foo", attr=value, ...)
Neal Norwitz488609e2003-01-06 16:51:37 +0000779\end{verbatim}
780
Greg Wardab05edc2006-04-23 03:47:58 +0000781The keyword arguments define attributes of the new Option object. The
782most important option attribute is \member{action}, and it largely determines
783which other attributes are relevant or required. If you pass irrelevant
784option attributes, or fail to pass required ones, \module{optparse} raises an
785OptionError exception explaining your mistake.
Neal Norwitz488609e2003-01-06 16:51:37 +0000786
Greg Wardab05edc2006-04-23 03:47:58 +0000787An options's \emph{action} determines what \module{optparse} does when it encounters this
788option on the command-line. The standard option actions hard-coded into
789\module{optparse} are:
Greg Wardb6f7fb72004-09-28 01:30:23 +0000790\begin{description}
791\item[\code{store}]
Greg Wardab05edc2006-04-23 03:47:58 +0000792store this option's argument (default)
Greg Wardb6f7fb72004-09-28 01:30:23 +0000793\item[\code{store{\_}const}]
794store a constant value
795\item[\code{store{\_}true}]
796store a true value
797\item[\code{store{\_}false}]
798store a false value
799\item[\code{append}]
800append this option's argument to a list
Greg Wardab05edc2006-04-23 03:47:58 +0000801\item[\code{append{\_}const}]
802append a constant value to a list
Greg Wardb6f7fb72004-09-28 01:30:23 +0000803\item[\code{count}]
804increment a counter by one
805\item[\code{callback}]
806call a specified function
807\item[\member{help}]
808print a usage message including all options and the
809documentation for them
810\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +0000811
Greg Wardb6f7fb72004-09-28 01:30:23 +0000812(If you don't supply an action, the default is \code{store}. For this
813action, you may also supply \member{type} and \member{dest} option attributes; see
Neal Norwitz488609e2003-01-06 16:51:37 +0000814below.)
815
816As you can see, most actions involve storing or updating a value
Greg Wardab05edc2006-04-23 03:47:58 +0000817somewhere. \module{optparse} always creates a special object for this,
818conventionally called \code{options} (it happens to be an instance of
819\code{optparse.Values}). Option arguments (and various other values) are
820stored as attributes of this object, according to the \member{dest}
821(destination) option attribute.
Neal Norwitz488609e2003-01-06 16:51:37 +0000822
Greg Wardb6f7fb72004-09-28 01:30:23 +0000823For example, when you call
Neal Norwitz488609e2003-01-06 16:51:37 +0000824\begin{verbatim}
825parser.parse_args()
826\end{verbatim}
827
Greg Wardab05edc2006-04-23 03:47:58 +0000828one of the first things \module{optparse} does is create the \code{options} object:
Neal Norwitz488609e2003-01-06 16:51:37 +0000829\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000830options = Values()
Neal Norwitz488609e2003-01-06 16:51:37 +0000831\end{verbatim}
832
Greg Wardb6f7fb72004-09-28 01:30:23 +0000833If one of the options in this parser is defined with
Neal Norwitz488609e2003-01-06 16:51:37 +0000834\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +0000835parser.add_option("-f", "--file", action="store", type="string", dest="filename")
Neal Norwitz488609e2003-01-06 16:51:37 +0000836\end{verbatim}
837
838and the command-line being parsed includes any of the following:
Neal Norwitz488609e2003-01-06 16:51:37 +0000839\begin{verbatim}
840-ffoo
841-f foo
842--file=foo
843--file foo
844\end{verbatim}
845
Greg Wardab05edc2006-04-23 03:47:58 +0000846then \module{optparse}, on seeing this option, will do the equivalent of
Neal Norwitz488609e2003-01-06 16:51:37 +0000847\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000848options.filename = "foo"
Neal Norwitz488609e2003-01-06 16:51:37 +0000849\end{verbatim}
850
Greg Wardb6f7fb72004-09-28 01:30:23 +0000851The \member{type} and \member{dest} option attributes are almost as important as
852\member{action}, but \member{action} is the only one that makes sense for \emph{all}
853options.
854
Neal Norwitz488609e2003-01-06 16:51:37 +0000855
Greg Warde644a1b2004-10-01 01:16:39 +0000856\subsubsection{Standard option actions\label{optparse-standard-option-actions}}
Neal Norwitz488609e2003-01-06 16:51:37 +0000857
Greg Wardb6f7fb72004-09-28 01:30:23 +0000858The various option actions all have slightly different requirements and
859effects. Most actions have several relevant option attributes which you
860may specify to guide \module{optparse}'s behaviour; a few have required attributes,
861which you must specify for any option using that action.
862\begin{itemize}
863\item {}
864\code{store} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000865
Greg Wardb6f7fb72004-09-28 01:30:23 +0000866The option must be followed by an argument, which is
867converted to a value according to \member{type} and stored in
868\member{dest}. If \code{nargs} {\textgreater} 1, multiple arguments will be consumed
869from the command line; all will be converted according to
870\member{type} and stored to \member{dest} as a tuple. See the ``Option
871types'' section below.
Neal Norwitz488609e2003-01-06 16:51:37 +0000872
Greg Wardb6f7fb72004-09-28 01:30:23 +0000873If \code{choices} is supplied (a list or tuple of strings), the type
874defaults to \code{choice}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000875
Greg Wardb6f7fb72004-09-28 01:30:23 +0000876If \member{type} is not supplied, it defaults to \code{string}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000877
Greg Wardb6f7fb72004-09-28 01:30:23 +0000878If \member{dest} is not supplied, \module{optparse} derives a destination from the
879first long option string (e.g., \code{"-{}-foo-bar"} implies \code{foo{\_}bar}).
880If there are no long option strings, \module{optparse} derives a destination from
881the first short option string (e.g., \code{"-f"} implies \code{f}).
Neal Norwitz488609e2003-01-06 16:51:37 +0000882
883Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000884\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000885parser.add_option("-f")
886parser.add_option("-p", type="float", nargs=3, dest="point")
Neal Norwitz488609e2003-01-06 16:51:37 +0000887\end{verbatim}
888
Greg Wardb6f7fb72004-09-28 01:30:23 +0000889As it parses the command line
Neal Norwitz488609e2003-01-06 16:51:37 +0000890\begin{verbatim}
891-f foo.txt -p 1 -3.5 4 -fbar.txt
892\end{verbatim}
893
Greg Wardb6f7fb72004-09-28 01:30:23 +0000894\module{optparse} will set
Neal Norwitz488609e2003-01-06 16:51:37 +0000895\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000896options.f = "foo.txt"
897options.point = (1.0, -3.5, 4.0)
898options.f = "bar.txt"
Neal Norwitz488609e2003-01-06 16:51:37 +0000899\end{verbatim}
900
Greg Wardb6f7fb72004-09-28 01:30:23 +0000901\item {}
902\code{store{\_}const} {[}required: \code{const}; relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000903
Greg Wardb6f7fb72004-09-28 01:30:23 +0000904The value \code{const} is stored in \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000905
906Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000907\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000908parser.add_option("-q", "--quiet",
909 action="store_const", const=0, dest="verbose")
910parser.add_option("-v", "--verbose",
911 action="store_const", const=1, dest="verbose")
912parser.add_option("--noisy",
913 action="store_const", const=2, dest="verbose")
Neal Norwitz488609e2003-01-06 16:51:37 +0000914\end{verbatim}
915
Greg Wardb6f7fb72004-09-28 01:30:23 +0000916If \code{"-{}-noisy"} is seen, \module{optparse} will set
Neal Norwitz488609e2003-01-06 16:51:37 +0000917\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000918options.verbose = 2
Neal Norwitz488609e2003-01-06 16:51:37 +0000919\end{verbatim}
920
Greg Wardb6f7fb72004-09-28 01:30:23 +0000921\item {}
922\code{store{\_}true} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000923
Greg Wardb6f7fb72004-09-28 01:30:23 +0000924A special case of \code{store{\_}const} that stores a true value
925to \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000926
Greg Wardb6f7fb72004-09-28 01:30:23 +0000927\item {}
928\code{store{\_}false} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000929
Greg Wardb6f7fb72004-09-28 01:30:23 +0000930Like \code{store{\_}true}, but stores a false value.
Neal Norwitz488609e2003-01-06 16:51:37 +0000931
932Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000933\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000934parser.add_option("--clobber", action="store_true", dest="clobber")
935parser.add_option("--no-clobber", action="store_false", dest="clobber")
Neal Norwitz488609e2003-01-06 16:51:37 +0000936\end{verbatim}
937
Greg Wardb6f7fb72004-09-28 01:30:23 +0000938\item {}
939\code{append} {[}relevant: \member{type}, \member{dest}, \code{nargs}, \code{choices}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000940
941The option must be followed by an argument, which is appended to the
Greg Wardb6f7fb72004-09-28 01:30:23 +0000942list in \member{dest}. If no default value for \member{dest} is supplied, an
943empty list is automatically created when \module{optparse} first encounters this
944option on the command-line. If \code{nargs} {\textgreater} 1, multiple arguments are
945consumed, and a tuple of length \code{nargs} is appended to \member{dest}.
Neal Norwitz488609e2003-01-06 16:51:37 +0000946
Greg Wardb6f7fb72004-09-28 01:30:23 +0000947The defaults for \member{type} and \member{dest} are the same as for the
948\code{store} action.
Neal Norwitz488609e2003-01-06 16:51:37 +0000949
950Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000951\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000952parser.add_option("-t", "--tracks", action="append", type="int")
Neal Norwitz488609e2003-01-06 16:51:37 +0000953\end{verbatim}
954
Greg Wardb6f7fb72004-09-28 01:30:23 +0000955If \code{"-t3"} is seen on the command-line, \module{optparse} does the equivalent of:
Neal Norwitz488609e2003-01-06 16:51:37 +0000956\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000957options.tracks = []
958options.tracks.append(int("3"))
Neal Norwitz488609e2003-01-06 16:51:37 +0000959\end{verbatim}
960
Greg Wardb6f7fb72004-09-28 01:30:23 +0000961If, a little later on, \code{"-{}-tracks=4"} is seen, it does:
Neal Norwitz488609e2003-01-06 16:51:37 +0000962\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000963options.tracks.append(int("4"))
Neal Norwitz488609e2003-01-06 16:51:37 +0000964\end{verbatim}
965
Greg Wardb6f7fb72004-09-28 01:30:23 +0000966\item {}
Greg Wardab05edc2006-04-23 03:47:58 +0000967\code{append{\_}const} {[}required: \code{const}; relevant: \member{dest}]
968
969Like \code{store{\_}const}, but the value \code{const} is appended to \member{dest};
970as with \code{append}, \member{dest} defaults to \code{None}, and an an empty list is
971automatically created the first time the option is encountered.
972
973\item {}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000974\code{count} {[}relevant: \member{dest}]
Neal Norwitz488609e2003-01-06 16:51:37 +0000975
Greg Wardb6f7fb72004-09-28 01:30:23 +0000976Increment the integer stored at \member{dest}. If no default value is
977supplied, \member{dest} is set to zero before being incremented the first
978time.
Neal Norwitz488609e2003-01-06 16:51:37 +0000979
980Example:
Neal Norwitz488609e2003-01-06 16:51:37 +0000981\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000982parser.add_option("-v", action="count", dest="verbosity")
Neal Norwitz488609e2003-01-06 16:51:37 +0000983\end{verbatim}
984
Greg Wardb6f7fb72004-09-28 01:30:23 +0000985The first time \code{"-v"} is seen on the command line, \module{optparse} does the
986equivalent of:
Neal Norwitz488609e2003-01-06 16:51:37 +0000987\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000988options.verbosity = 0
989options.verbosity += 1
Neal Norwitz488609e2003-01-06 16:51:37 +0000990\end{verbatim}
991
Greg Wardb6f7fb72004-09-28 01:30:23 +0000992Every subsequent occurrence of \code{"-v"} results in
Neal Norwitz488609e2003-01-06 16:51:37 +0000993\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +0000994options.verbosity += 1
Neal Norwitz488609e2003-01-06 16:51:37 +0000995\end{verbatim}
996
Greg Wardb6f7fb72004-09-28 01:30:23 +0000997\item {}
998\code{callback} {[}required: \code{callback};
999relevant: \member{type}, \code{nargs}, \code{callback{\_}args}, \code{callback{\_}kwargs}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001000
Greg Wardab05edc2006-04-23 03:47:58 +00001001Call the function specified by \code{callback}, which is called as
Neal Norwitz488609e2003-01-06 16:51:37 +00001002\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +00001003func(option, opt_str, value, parser, *args, **kwargs)
Neal Norwitz488609e2003-01-06 16:51:37 +00001004\end{verbatim}
1005
Greg Warde644a1b2004-10-01 01:16:39 +00001006See section~\ref{optparse-option-callbacks}, Option Callbacks for more detail.
Neal Norwitz488609e2003-01-06 16:51:37 +00001007
Greg Wardb6f7fb72004-09-28 01:30:23 +00001008\item {}
1009\member{help}
Neal Norwitz488609e2003-01-06 16:51:37 +00001010
Greg Wardb6f7fb72004-09-28 01:30:23 +00001011Prints a complete help message for all the options in the
1012current option parser. The help message is constructed from
Greg Wardab05edc2006-04-23 03:47:58 +00001013the \code{usage} string passed to OptionParser's constructor and
Greg Wardb6f7fb72004-09-28 01:30:23 +00001014the \member{help} string passed to every option.
Neal Norwitz488609e2003-01-06 16:51:37 +00001015
Greg Wardb6f7fb72004-09-28 01:30:23 +00001016If no \member{help} string is supplied for an option, it will still be
1017listed in the help message. To omit an option entirely, use
1018the special value \code{optparse.SUPPRESS{\_}HELP}.
1019
1020\module{optparse} automatically adds a \member{help} option to all OptionParsers, so
1021you do not normally need to create one.
Neal Norwitz488609e2003-01-06 16:51:37 +00001022
1023Example:
Neal Norwitz488609e2003-01-06 16:51:37 +00001024\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001025from optparse import OptionParser, SUPPRESS_HELP
Neal Norwitz488609e2003-01-06 16:51:37 +00001026
Greg Wardb6f7fb72004-09-28 01:30:23 +00001027parser = OptionParser()
1028parser.add_option("-h", "--help", action="help"),
1029parser.add_option("-v", action="store_true", dest="verbose",
1030 help="Be moderately verbose")
1031parser.add_option("--file", dest="filename",
1032 help="Input file to read data from"),
1033parser.add_option("--secret", help=SUPPRESS_HELP)
Neal Norwitz488609e2003-01-06 16:51:37 +00001034\end{verbatim}
1035
Greg Wardb6f7fb72004-09-28 01:30:23 +00001036If \module{optparse} sees either \code{"-h"} or \code{"-{}-help"} on the command line, it
1037will print something like the following help message to stdout
1038(assuming \code{sys.argv{[}0]} is \code{"foo.py"}):
Neal Norwitz488609e2003-01-06 16:51:37 +00001039\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001040usage: foo.py [options]
Neal Norwitz488609e2003-01-06 16:51:37 +00001041
1042options:
1043 -h, --help Show this help message and exit
1044 -v Be moderately verbose
1045 --file=FILENAME Input file to read data from
1046\end{verbatim}
1047
1048After printing the help message, \module{optparse} terminates your process
1049with \code{sys.exit(0)}.
1050
Greg Wardb6f7fb72004-09-28 01:30:23 +00001051\item {}
1052\code{version}
Neal Norwitz488609e2003-01-06 16:51:37 +00001053
Greg Wardb6f7fb72004-09-28 01:30:23 +00001054Prints the version number supplied to the OptionParser to stdout and
1055exits. The version number is actually formatted and printed by the
1056\code{print{\_}version()} method of OptionParser. Generally only relevant
1057if the \code{version} argument is supplied to the OptionParser
1058constructor. As with \member{help} options, you will rarely create
1059\code{version} options, since \module{optparse} automatically adds them when needed.
1060
1061\end{itemize}
1062
Neal Norwitz488609e2003-01-06 16:51:37 +00001063
Greg Wardab05edc2006-04-23 03:47:58 +00001064\subsubsection{Option attributes\label{optparse-option-attributes}}
1065
1066The following option attributes may be passed as keyword arguments
1067to \code{parser.add{\_}option()}. If you pass an option attribute
1068that is not relevant to a particular option, or fail to pass a required
1069option attribute, \module{optparse} raises OptionError.
1070\begin{itemize}
1071\item {}
1072\member{action} (default: \code{"store"})
1073
1074Determines \module{optparse}'s behaviour when this option is seen on the command
1075line; the available options are documented above.
1076
1077\item {}
1078\member{type} (default: \code{"string"})
1079
1080The argument type expected by this option (e.g., \code{"string"} or
1081\code{"int"}); the available option types are documented below.
1082
1083\item {}
1084\member{dest} (default: derived from option strings)
1085
1086If the option's action implies writing or modifying a value somewhere,
1087this tells \module{optparse} where to write it: \member{dest} names an attribute of the
1088\code{options} object that \module{optparse} builds as it parses the command line.
1089
1090\item {}
1091\code{default} (deprecated)
1092
1093The value to use for this option's destination if the option is not
1094seen on the command line. Deprecated; use \code{parser.set{\_}defaults()}
1095instead.
1096
1097\item {}
1098\code{nargs} (default: 1)
1099
1100How many arguments of type \member{type} should be consumed when this
1101option is seen. If {\textgreater} 1, \module{optparse} will store a tuple of values to
1102\member{dest}.
1103
1104\item {}
1105\code{const}
1106
1107For actions that store a constant value, the constant value to store.
1108
1109\item {}
1110\code{choices}
1111
1112For options of type \code{"choice"}, the list of strings the user
1113may choose from.
1114
1115\item {}
1116\code{callback}
1117
1118For options with action \code{"callback"}, the callable to call when this
1119option is seen. See section~\ref{optparse-option-callbacks}, Option Callbacks for detail on the arguments
1120passed to \code{callable}.
1121
1122\item {}
1123\code{callback{\_}args}, \code{callback{\_}kwargs}
1124
1125Additional positional and keyword arguments to pass to \code{callback}
1126after the four standard callback arguments.
1127
1128\item {}
1129\member{help}
1130
1131Help text to print for this option when listing all available options
1132after the user supplies a \member{help} option (such as \code{"-{}-help"}).
1133If no help text is supplied, the option will be listed without help
1134text. To hide this option, use the special value \code{SUPPRESS{\_}HELP}.
1135
1136\item {}
1137\code{metavar} (default: derived from option strings)
1138
1139Stand-in for the option argument(s) to use when printing help text.
1140See section~\ref{optparse-tutorial}, the tutorial for an example.
1141
1142\end{itemize}
1143
1144
Greg Warde644a1b2004-10-01 01:16:39 +00001145\subsubsection{Standard option types\label{optparse-standard-option-types}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001146
Greg Wardb6f7fb72004-09-28 01:30:23 +00001147\module{optparse} has six built-in option types: \code{string}, \code{int}, \code{long},
1148\code{choice}, \code{float} and \code{complex}. If you need to add new option
1149types, see section~\ref{optparse-extending}, Extending \module{optparse}.
Neal Norwitz488609e2003-01-06 16:51:37 +00001150
Greg Wardb6f7fb72004-09-28 01:30:23 +00001151Arguments to string options are not checked or converted in any way: the
1152text on the command line is stored in the destination (or passed to the
1153callback) as-is.
Neal Norwitz488609e2003-01-06 16:51:37 +00001154
Greg Wardab05edc2006-04-23 03:47:58 +00001155Integer arguments (type \code{int} or \code{long}) are parsed as follows:
1156\begin{quote}
1157\begin{itemize}
1158\item {}
1159if the number starts with \code{0x}, it is parsed as a hexadecimal number
Neal Norwitz488609e2003-01-06 16:51:37 +00001160
Greg Wardab05edc2006-04-23 03:47:58 +00001161\item {}
1162if the number starts with \code{0}, it is parsed as an octal number
1163
1164\item {}
1165if the number starts with \code{0b}, is is parsed as a binary number
1166
1167\item {}
1168otherwise, the number is parsed as a decimal number
1169
1170\end{itemize}
1171\end{quote}
1172
1173The conversion is done by calling either \code{int()} or \code{long()} with
1174the appropriate base (2, 8, 10, or 16). If this fails, so will \module{optparse},
1175although with a more useful error message.
1176
1177\code{float} and \code{complex} option arguments are converted directly with
1178\code{float()} and \code{complex()}, with similar error-handling.
Neal Norwitz488609e2003-01-06 16:51:37 +00001179
Greg Wardb6f7fb72004-09-28 01:30:23 +00001180\code{choice} options are a subtype of \code{string} options. The \code{choices}
1181option attribute (a sequence of strings) defines the set of allowed
Greg Wardab05edc2006-04-23 03:47:58 +00001182option arguments. \code{optparse.check{\_}choice()} compares
Greg Wardb6f7fb72004-09-28 01:30:23 +00001183user-supplied option arguments against this master list and raises
Greg Wardab05edc2006-04-23 03:47:58 +00001184OptionValueError if an invalid string is given.
1185
1186
1187\subsubsection{Parsing arguments\label{optparse-parsing-arguments}}
1188
1189The whole point of creating and populating an OptionParser is to call
1190its \method{parse{\_}args()} method:
1191\begin{verbatim}
1192(options, args) = parser.parse_args(args=None, options=None)
1193\end{verbatim}
1194
1195where the input parameters are
1196\begin{description}
1197\item[\code{args}]
1198the list of arguments to process (\code{sys.argv{[}1:]} by default)
1199\item[\code{options}]
1200object to store option arguments in (a new instance of
1201optparse.Values by default)
1202\end{description}
1203
1204and the return values are
1205\begin{description}
1206\item[\code{options}]
1207the same object as was passed in as \code{options}, or the new
1208optparse.Values instance created by \module{optparse}
1209\item[\code{args}]
1210the leftover positional arguments after all options have been
1211processed
1212\end{description}
1213
1214The most common usage is to supply neither keyword argument. If you
1215supply a \code{values} object, it will be repeatedly modified with a
1216\code{setattr()} call for every option argument written to an option
1217destination, and finally returned by \method{parse{\_}args()}.
1218
1219If \method{parse{\_}args()} encounters any errors in the argument list, it calls
1220the OptionParser's \method{error()} method with an appropriate end-user error
1221message. This ultimately terminates your process with an exit status of
12222 (the traditional \UNIX{} exit status for command-line errors).
Neal Norwitz488609e2003-01-06 16:51:37 +00001223
Greg Wardb6f7fb72004-09-28 01:30:23 +00001224
Greg Warde644a1b2004-10-01 01:16:39 +00001225\subsubsection{Querying and manipulating your option parser\label{optparse-querying-manipulating-option-parser}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001226
1227Sometimes, it's useful to poke around your option parser and see what's
Greg Wardb6f7fb72004-09-28 01:30:23 +00001228there. OptionParser provides a couple of methods to help you out:
1229\begin{description}
1230\item[\code{has{\_}option(opt{\_}str)}]
1231Return true if the OptionParser has an option with
1232option string \code{opt{\_}str} (e.g., \code{"-q"} or \code{"-{}-verbose"}).
1233\item[\code{get{\_}option(opt{\_}str)}]
1234Returns the Option instance with the option string \code{opt{\_}str}, or
1235\code{None} if no options have that option string.
1236\item[\code{remove{\_}option(opt{\_}str)}]
1237If the OptionParser has an option corresponding to \code{opt{\_}str},
1238that option is removed. If that option provided any other
1239option strings, all of those option strings become invalid.
Greg Wardb6f7fb72004-09-28 01:30:23 +00001240If \code{opt{\_}str} does not occur in any option belonging to this
Greg Wardab05edc2006-04-23 03:47:58 +00001241OptionParser, raises ValueError.
Greg Wardb6f7fb72004-09-28 01:30:23 +00001242\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001243
Neal Norwitz488609e2003-01-06 16:51:37 +00001244
Greg Wardb6f7fb72004-09-28 01:30:23 +00001245\subsubsection{Conflicts between options\label{optparse-conflicts-between-options}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001246
Greg Wardb6f7fb72004-09-28 01:30:23 +00001247If you're not careful, it's easy to define options with conflicting
1248option strings:
Neal Norwitz488609e2003-01-06 16:51:37 +00001249\begin{verbatim}
1250parser.add_option("-n", "--dry-run", ...)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001251[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001252parser.add_option("-n", "--noisy", ...)
Neal Norwitz488609e2003-01-06 16:51:37 +00001253\end{verbatim}
1254
Greg Wardb6f7fb72004-09-28 01:30:23 +00001255(This is particularly true if you've defined your own OptionParser
1256subclass with some standard options.)
Neal Norwitz488609e2003-01-06 16:51:37 +00001257
Greg Wardb6f7fb72004-09-28 01:30:23 +00001258Every time you add an option, \module{optparse} checks for conflicts with existing
1259options. If it finds any, it invokes the current conflict-handling
1260mechanism. You can set the conflict-handling mechanism either in the
1261constructor:
Neal Norwitz488609e2003-01-06 16:51:37 +00001262\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +00001263parser = OptionParser(..., conflict_handler=handler)
Neal Norwitz488609e2003-01-06 16:51:37 +00001264\end{verbatim}
1265
Greg Wardb6f7fb72004-09-28 01:30:23 +00001266or with a separate call:
1267\begin{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +00001268parser.set_conflict_handler(handler)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001269\end{verbatim}
Neal Norwitz488609e2003-01-06 16:51:37 +00001270
Greg Wardab05edc2006-04-23 03:47:58 +00001271The available conflict handlers are:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001272\begin{quote}
1273\begin{description}
1274\item[\code{error} (default)]
1275assume option conflicts are a programming error and raise
Greg Wardab05edc2006-04-23 03:47:58 +00001276OptionConflictError
Greg Wardb6f7fb72004-09-28 01:30:23 +00001277\item[\code{resolve}]
1278resolve option conflicts intelligently (see below)
1279\end{description}
1280\end{quote}
Neal Norwitz488609e2003-01-06 16:51:37 +00001281
Greg Wardb6f7fb72004-09-28 01:30:23 +00001282As an example, let's define an OptionParser that resolves conflicts
1283intelligently and add conflicting options to it:
Neal Norwitz488609e2003-01-06 16:51:37 +00001284\begin{verbatim}
1285parser = OptionParser(conflict_handler="resolve")
Greg Wardb6f7fb72004-09-28 01:30:23 +00001286parser.add_option("-n", "--dry-run", ..., help="do no harm")
1287parser.add_option("-n", "--noisy", ..., help="be noisy")
Neal Norwitz488609e2003-01-06 16:51:37 +00001288\end{verbatim}
1289
Neal Norwitz488609e2003-01-06 16:51:37 +00001290At this point, \module{optparse} detects that a previously-added option is already
Greg Wardb6f7fb72004-09-28 01:30:23 +00001291using the \code{"-n"} option string. Since \code{conflict{\_}handler} is
1292\code{"resolve"}, it resolves the situation by removing \code{"-n"} from the
1293earlier option's list of option strings. Now \code{"-{}-dry-run"} is the
1294only way for the user to activate that option. If the user asks for
1295help, the help message will reflect that:
Neal Norwitz488609e2003-01-06 16:51:37 +00001296\begin{verbatim}
1297options:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001298 --dry-run do no harm
1299 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001300 -n, --noisy be noisy
1301\end{verbatim}
1302
Greg Wardb6f7fb72004-09-28 01:30:23 +00001303It's possible to whittle away the option strings for a previously-added
1304option until there are none left, and the user has no way of invoking
1305that option from the command-line. In that case, \module{optparse} removes that
1306option completely, so it doesn't show up in help text or anywhere else.
1307Carrying on with our existing OptionParser:
Neal Norwitz488609e2003-01-06 16:51:37 +00001308\begin{verbatim}
1309parser.add_option("--dry-run", ..., help="new dry-run option")
1310\end{verbatim}
1311
Greg Wardb6f7fb72004-09-28 01:30:23 +00001312At this point, the original \programopt{-n/-{}-dry-run} option is no longer
1313accessible, so \module{optparse} removes it, leaving this help text:
Neal Norwitz488609e2003-01-06 16:51:37 +00001314\begin{verbatim}
1315options:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001316 [...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001317 -n, --noisy be noisy
1318 --dry-run new dry-run option
1319\end{verbatim}
Greg Wardab05edc2006-04-23 03:47:58 +00001320
1321
1322\subsubsection{Cleanup\label{optparse-cleanup}}
1323
1324OptionParser instances have several cyclic references. This should not
1325be a problem for Python's garbage collector, but you may wish to break
1326the cyclic references explicitly by calling \code{destroy()} on your
1327OptionParser once you are done with it. This is particularly useful in
1328long-running applications where large object graphs are reachable from
1329your OptionParser.
1330
1331
1332\subsubsection{Other methods\label{optparse-other-methods}}
1333
1334OptionParser supports several other public methods:
1335\begin{itemize}
1336\item {}
1337\code{set{\_}usage(usage)}
1338
1339Set the usage string according to the rules described above for the
1340\code{usage} constructor keyword argument. Passing \code{None} sets the
1341default usage string; use \code{SUPPRESS{\_}USAGE} to suppress a usage
1342message.
1343
1344\item {}
1345\code{enable{\_}interspersed{\_}args()}, \code{disable{\_}interspersed{\_}args()}
1346
1347Enable/disable positional arguments interspersed with options, similar
1348to GNU getopt (enabled by default). For example, if \code{"-a"} and
1349\code{"-b"} are both simple options that take no arguments, \module{optparse}
1350normally accepts this syntax:
1351\begin{verbatim}
1352prog -a arg1 -b arg2
1353\end{verbatim}
1354
1355and treats it as equivalent to
1356\begin{verbatim}
1357prog -a -b arg1 arg2
1358\end{verbatim}
1359
1360To disable this feature, call \code{disable{\_}interspersed{\_}args()}. This
1361restores traditional \UNIX{} syntax, where option parsing stops with the
1362first non-option argument.
1363
1364\item {}
1365\code{set{\_}defaults(dest=value, ...)}
1366
1367Set default values for several option destinations at once. Using
1368\method{set{\_}defaults()} is the preferred way to set default values for
1369options, since multiple options can share the same destination. For
1370example, if several ``mode'' options all set the same destination, any
1371one of them can set the default, and the last one wins:
1372\begin{verbatim}
1373parser.add_option("--advanced", action="store_const",
1374 dest="mode", const="advanced",
1375 default="novice") # overridden below
1376parser.add_option("--novice", action="store_const",
1377 dest="mode", const="novice",
1378 default="advanced") # overrides above setting
1379\end{verbatim}
1380
1381To avoid this confusion, use \method{set{\_}defaults()}:
1382\begin{verbatim}
1383parser.set_defaults(mode="advanced")
1384parser.add_option("--advanced", action="store_const",
1385 dest="mode", const="advanced")
1386parser.add_option("--novice", action="store_const",
1387 dest="mode", const="novice")
1388\end{verbatim}
1389
1390\end{itemize}
1391% $Id: reference.txt 505 2005-07-22 01:52:40Z gward $
Neal Norwitz488609e2003-01-06 16:51:37 +00001392
Neal Norwitz488609e2003-01-06 16:51:37 +00001393
Greg Wardb6f7fb72004-09-28 01:30:23 +00001394\subsection{Option Callbacks\label{optparse-option-callbacks}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001395
Greg Wardb6f7fb72004-09-28 01:30:23 +00001396When \module{optparse}'s built-in actions and types aren't quite enough for your
1397needs, you have two choices: extend \module{optparse} or define a callback option.
1398Extending \module{optparse} is more general, but overkill for a lot of simple
1399cases. Quite often a simple callback is all you need.
Neal Norwitz488609e2003-01-06 16:51:37 +00001400
Greg Wardb6f7fb72004-09-28 01:30:23 +00001401There are two steps to defining a callback option:
1402\begin{itemize}
1403\item {}
1404define the option itself using the \code{callback} action
Neal Norwitz488609e2003-01-06 16:51:37 +00001405
Greg Wardb6f7fb72004-09-28 01:30:23 +00001406\item {}
1407write the callback; this is a function (or method) that
1408takes at least four arguments, as described below
1409
1410\end{itemize}
1411
1412
Greg Warde644a1b2004-10-01 01:16:39 +00001413\subsubsection{Defining a callback option\label{optparse-defining-callback-option}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001414
1415As always, the easiest way to define a callback option is by using the
1416\code{parser.add{\_}option()} method. Apart from \member{action}, the only option
1417attribute you must specify is \code{callback}, the function to call:
Neal Norwitz488609e2003-01-06 16:51:37 +00001418\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001419parser.add_option("-c", action="callback", callback=my_callback)
Neal Norwitz488609e2003-01-06 16:51:37 +00001420\end{verbatim}
1421
Greg Wardb6f7fb72004-09-28 01:30:23 +00001422\code{callback} is a function (or other callable object), so you must have
1423already defined \code{my{\_}callback()} when you create this callback option.
1424In this simple case, \module{optparse} doesn't even know if \programopt{-c} takes any
1425arguments, which usually means that the option takes no arguments{---}the
1426mere presence of \programopt{-c} on the command-line is all it needs to know. In
1427some circumstances, though, you might want your callback to consume an
1428arbitrary number of command-line arguments. This is where writing
1429callbacks gets tricky; it's covered later in this section.
1430
1431\module{optparse} always passes four particular arguments to your callback, and it
1432will only pass additional arguments if you specify them via
1433\code{callback{\_}args} and \code{callback{\_}kwargs}. Thus, the minimal callback
1434function signature is:
1435\begin{verbatim}
1436def my_callback(option, opt, value, parser):
1437\end{verbatim}
1438
1439The four arguments to a callback are described below.
Neal Norwitz488609e2003-01-06 16:51:37 +00001440
1441There are several other option attributes that you can supply when you
Greg Wardb6f7fb72004-09-28 01:30:23 +00001442define a callback option:
1443\begin{description}
1444\item[\member{type}]
1445has its usual meaning: as with the \code{store} or \code{append} actions,
1446it instructs \module{optparse} to consume one argument and convert it to
1447\member{type}. Rather than storing the converted value(s) anywhere,
1448though, \module{optparse} passes it to your callback function.
1449\item[\code{nargs}]
1450also has its usual meaning: if it is supplied and {\textgreater} 1, \module{optparse} will
1451consume \code{nargs} arguments, each of which must be convertible to
1452\member{type}. It then passes a tuple of converted values to your
1453callback.
1454\item[\code{callback{\_}args}]
1455a tuple of extra positional arguments to pass to the callback
1456\item[\code{callback{\_}kwargs}]
1457a dictionary of extra keyword arguments to pass to the callback
1458\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001459
Neal Norwitz488609e2003-01-06 16:51:37 +00001460
Greg Warde644a1b2004-10-01 01:16:39 +00001461\subsubsection{How callbacks are called\label{optparse-how-callbacks-called}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001462
1463All callbacks are called as follows:
Neal Norwitz488609e2003-01-06 16:51:37 +00001464\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001465func(option, opt_str, value, parser, *args, **kwargs)
Neal Norwitz488609e2003-01-06 16:51:37 +00001466\end{verbatim}
1467
1468where
Greg Wardb6f7fb72004-09-28 01:30:23 +00001469\begin{description}
1470\item[\code{option}]
1471is the Option instance that's calling the callback
1472\item[\code{opt{\_}str}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001473is the option string seen on the command-line that's triggering the
Greg Wardb6f7fb72004-09-28 01:30:23 +00001474callback. (If an abbreviated long option was used, \code{opt{\_}str} will
1475be the full, canonical option string{---}e.g. if the user puts
1476\code{"-{}-foo"} on the command-line as an abbreviation for
1477\code{"-{}-foobar"}, then \code{opt{\_}str} will be \code{"-{}-foobar"}.)
1478\item[\code{value}]
1479is the argument to this option seen on the command-line. \module{optparse} will
1480only expect an argument if \member{type} is set; the type of \code{value}
1481will be the type implied by the option's type. If \member{type} for this
1482option is \code{None} (no argument expected), then \code{value} will be
1483\code{None}. If \code{nargs} {\textgreater} 1, \code{value} will be a tuple of values of
1484the appropriate type.
1485\item[\code{parser}]
1486is the OptionParser instance driving the whole thing, mainly
1487useful because you can access some other interesting data through
1488its instance attributes:
1489\begin{description}
1490\item[\code{parser.largs}]
1491the current list of leftover arguments, ie. arguments that have
1492been consumed but are neither options nor option arguments.
1493Feel free to modify \code{parser.largs}, e.g. by adding more
Greg Wardab05edc2006-04-23 03:47:58 +00001494arguments to it. (This list will become \code{args}, the second
Greg Wardb6f7fb72004-09-28 01:30:23 +00001495return value of \method{parse{\_}args()}.)
1496\item[\code{parser.rargs}]
1497the current list of remaining arguments, ie. with \code{opt{\_}str} and
1498\code{value} (if applicable) removed, and only the arguments
1499following them still there. Feel free to modify
1500\code{parser.rargs}, e.g. by consuming more arguments.
1501\item[\code{parser.values}]
1502the object where option values are by default stored (an
1503instance of optparse.OptionValues). This lets callbacks use the
1504same mechanism as the rest of \module{optparse} for storing option values;
1505you don't need to mess around with globals or closures. You can
1506also access or modify the value(s) of any options already
1507encountered on the command-line.
1508\end{description}
Raymond Hettinger79e05312004-12-31 01:07:27 +00001509\item[\code{args}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001510is a tuple of arbitrary positional arguments supplied via the
Greg Wardb6f7fb72004-09-28 01:30:23 +00001511\code{callback{\_}args} option attribute.
1512\item[\code{kwargs}]
Neal Norwitz488609e2003-01-06 16:51:37 +00001513is a dictionary of arbitrary keyword arguments supplied via
Greg Wardb6f7fb72004-09-28 01:30:23 +00001514\code{callback{\_}kwargs}.
1515\end{description}
Neal Norwitz488609e2003-01-06 16:51:37 +00001516
Neal Norwitz488609e2003-01-06 16:51:37 +00001517
Greg Warde644a1b2004-10-01 01:16:39 +00001518\subsubsection{Raising errors in a callback\label{optparse-raising-errors-in-callback}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001519
Greg Wardab05edc2006-04-23 03:47:58 +00001520The callback function should raise OptionValueError if there are any
Greg Wardb6f7fb72004-09-28 01:30:23 +00001521problems with the option or its argument(s). \module{optparse} catches this and
1522terminates the program, printing the error message you supply to
1523stderr. Your message should be clear, concise, accurate, and mention
1524the option at fault. Otherwise, the user will have a hard time
1525figuring out what he did wrong.
Neal Norwitz488609e2003-01-06 16:51:37 +00001526
Neal Norwitz488609e2003-01-06 16:51:37 +00001527
Greg Warde644a1b2004-10-01 01:16:39 +00001528\subsubsection{Callback example 1: trivial callback\label{optparse-callback-example-1}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001529
1530Here's an example of a callback option that takes no arguments, and
1531simply records that the option was seen:
Neal Norwitz488609e2003-01-06 16:51:37 +00001532\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001533def record_foo_seen(option, opt_str, value, parser):
1534 parser.saw_foo = True
Neal Norwitz488609e2003-01-06 16:51:37 +00001535
1536parser.add_option("--foo", action="callback", callback=record_foo_seen)
1537\end{verbatim}
1538
Greg Wardb6f7fb72004-09-28 01:30:23 +00001539Of course, you could do that with the \code{store{\_}true} action.
Neal Norwitz488609e2003-01-06 16:51:37 +00001540
Greg Wardb6f7fb72004-09-28 01:30:23 +00001541
Greg Warde644a1b2004-10-01 01:16:39 +00001542\subsubsection{Callback example 2: check option order\label{optparse-callback-example-2}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001543
1544Here's a slightly more interesting example: record the fact that
1545\code{"-a"} is seen, but blow up if it comes after \code{"-b"} in the
1546command-line.
Neal Norwitz488609e2003-01-06 16:51:37 +00001547\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001548def check_order(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001549 if parser.values.b:
1550 raise OptionValueError("can't use -a after -b")
1551 parser.values.a = 1
Greg Wardb6f7fb72004-09-28 01:30:23 +00001552[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001553parser.add_option("-a", action="callback", callback=check_order)
1554parser.add_option("-b", action="store_true", dest="b")
1555\end{verbatim}
1556
Neal Norwitz488609e2003-01-06 16:51:37 +00001557
Greg Warde644a1b2004-10-01 01:16:39 +00001558\subsubsection{Callback example 3: check option order (generalized)\label{optparse-callback-example-3}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001559
1560If you want to re-use this callback for several similar options (set a
1561flag, but blow up if \code{"-b"} has already been seen), it needs a bit of
1562work: the error message and the flag that it sets must be
1563generalized.
Neal Norwitz488609e2003-01-06 16:51:37 +00001564\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001565def check_order(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001566 if parser.values.b:
Greg Wardb6f7fb72004-09-28 01:30:23 +00001567 raise OptionValueError("can't use %s after -b" % opt_str)
Neal Norwitz488609e2003-01-06 16:51:37 +00001568 setattr(parser.values, option.dest, 1)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001569[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001570parser.add_option("-a", action="callback", callback=check_order, dest='a')
1571parser.add_option("-b", action="store_true", dest="b")
1572parser.add_option("-c", action="callback", callback=check_order, dest='c')
1573\end{verbatim}
1574
Greg Wardb6f7fb72004-09-28 01:30:23 +00001575
Greg Warde644a1b2004-10-01 01:16:39 +00001576\subsubsection{Callback example 4: check arbitrary condition\label{optparse-callback-example-4}}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001577
1578Of course, you could put any condition in there{---}you're not limited
Neal Norwitz488609e2003-01-06 16:51:37 +00001579to checking the values of already-defined options. For example, if
1580you have options that should not be called when the moon is full, all
1581you have to do is this:
Neal Norwitz488609e2003-01-06 16:51:37 +00001582\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001583def check_moon(option, opt_str, value, parser):
1584 if is_moon_full():
1585 raise OptionValueError("%s option invalid when moon is full"
1586 % opt_str)
Neal Norwitz488609e2003-01-06 16:51:37 +00001587 setattr(parser.values, option.dest, 1)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001588[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001589parser.add_option("--foo",
1590 action="callback", callback=check_moon, dest="foo")
1591\end{verbatim}
1592
Greg Wardb6f7fb72004-09-28 01:30:23 +00001593(The definition of \code{is{\_}moon{\_}full()} is left as an exercise for the
Neal Norwitz488609e2003-01-06 16:51:37 +00001594reader.)
1595
Greg Wardb6f7fb72004-09-28 01:30:23 +00001596
Greg Warde644a1b2004-10-01 01:16:39 +00001597\subsubsection{Callback example 5: fixed arguments\label{optparse-callback-example-5}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001598
1599Things get slightly more interesting when you define callback options
1600that take a fixed number of arguments. Specifying that a callback
Greg Wardb6f7fb72004-09-28 01:30:23 +00001601option takes arguments is similar to defining a \code{store} or \code{append}
1602option: if you define \member{type}, then the option takes one argument that
1603must be convertible to that type; if you further define \code{nargs}, then
1604the option takes \code{nargs} arguments.
Neal Norwitz488609e2003-01-06 16:51:37 +00001605
Greg Wardb6f7fb72004-09-28 01:30:23 +00001606Here's an example that just emulates the standard \code{store} action:
Neal Norwitz488609e2003-01-06 16:51:37 +00001607\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001608def store_value(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001609 setattr(parser.values, option.dest, value)
Greg Wardb6f7fb72004-09-28 01:30:23 +00001610[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001611parser.add_option("--foo",
1612 action="callback", callback=store_value,
1613 type="int", nargs=3, dest="foo")
1614\end{verbatim}
1615
Greg Wardb6f7fb72004-09-28 01:30:23 +00001616Note that \module{optparse} takes care of consuming 3 arguments and converting them
1617to integers for you; all you have to do is store them. (Or whatever;
1618obviously you don't need a callback for this example.)
Neal Norwitz488609e2003-01-06 16:51:37 +00001619
Greg Wardb6f7fb72004-09-28 01:30:23 +00001620
Greg Warde644a1b2004-10-01 01:16:39 +00001621\subsubsection{Callback example 6: variable arguments\label{optparse-callback-example-6}}
Neal Norwitz488609e2003-01-06 16:51:37 +00001622
1623Things get hairy when you want an option to take a variable number of
Greg Wardb6f7fb72004-09-28 01:30:23 +00001624arguments. For this case, you must write a callback, as \module{optparse} doesn't
1625provide any built-in capabilities for it. And you have to deal with
1626certain intricacies of conventional \UNIX{} command-line parsing that \module{optparse}
1627normally handles for you. In particular, callbacks should implement
1628the conventional rules for bare \code{"-{}-"} and \code{"-"} arguments:
Neal Norwitz488609e2003-01-06 16:51:37 +00001629\begin{itemize}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001630\item {}
1631either \code{"-{}-"} or \code{"-"} can be option arguments
Neal Norwitz488609e2003-01-06 16:51:37 +00001632
Greg Wardb6f7fb72004-09-28 01:30:23 +00001633\item {}
1634bare \code{"-{}-"} (if not the argument to some option): halt command-line
1635processing and discard the \code{"-{}-"}
Neal Norwitz488609e2003-01-06 16:51:37 +00001636
Greg Wardb6f7fb72004-09-28 01:30:23 +00001637\item {}
1638bare \code{"-"} (if not the argument to some option): halt command-line
1639processing but keep the \code{"-"} (append it to \code{parser.largs})
1640
Neal Norwitz488609e2003-01-06 16:51:37 +00001641\end{itemize}
1642
1643If you want an option that takes a variable number of arguments, there
1644are several subtle, tricky issues to worry about. The exact
1645implementation you choose will be based on which trade-offs you're
Greg Wardb6f7fb72004-09-28 01:30:23 +00001646willing to make for your application (which is why \module{optparse} doesn't support
1647this sort of thing directly).
Neal Norwitz488609e2003-01-06 16:51:37 +00001648
1649Nevertheless, here's a stab at a callback for an option with variable
1650arguments:
Neal Norwitz488609e2003-01-06 16:51:37 +00001651\begin{verbatim}
Greg Wardb6f7fb72004-09-28 01:30:23 +00001652def vararg_callback(option, opt_str, value, parser):
Neal Norwitz488609e2003-01-06 16:51:37 +00001653 assert value is None
1654 done = 0
1655 value = []
1656 rargs = parser.rargs
1657 while rargs:
1658 arg = rargs[0]
1659
1660 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1661 # etc. Note that this also stops on "-3" or "-3.0", so if
1662 # your option takes numeric values, you will need to handle
1663 # this.
1664 if ((arg[:2] == "--" and len(arg) > 2) or
1665 (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
1666 break
1667 else:
1668 value.append(arg)
1669 del rargs[0]
1670
1671 setattr(parser.values, option.dest, value)
1672
Greg Wardb6f7fb72004-09-28 01:30:23 +00001673[...]
Neal Norwitz488609e2003-01-06 16:51:37 +00001674parser.add_option("-c", "--callback",
1675 action="callback", callback=varargs)
1676\end{verbatim}
1677
1678The main weakness with this particular implementation is that negative
Greg Wardb6f7fb72004-09-28 01:30:23 +00001679numbers in the arguments following \code{"-c"} will be interpreted as
1680further options (probably causing an error), rather than as arguments to
1681\code{"-c"}. Fixing this is left as an exercise for the reader.
Greg Warde644a1b2004-10-01 01:16:39 +00001682% $Id: callbacks.txt 415 2004-09-30 02:26:17Z greg $
Neal Norwitz488609e2003-01-06 16:51:37 +00001683